Ejemplo n.º 1
0
 /**
  * Takes an associative array and creates a participant object.
  *
  * the function extract all the params it needs to initialize the create a
  * participant object. the params array could contain additional unused name/value
  * pairs
  *
  * @param array $params
  *   (reference ) an assoc array of name/value pairs.
  *
  * @return CRM_Event_BAO_Participant
  */
 public static function &add(&$params)
 {
     if (!empty($params['id'])) {
         CRM_Utils_Hook::pre('edit', 'Participant', $params['id'], $params);
     } else {
         CRM_Utils_Hook::pre('create', 'Participant', NULL, $params);
     }
     // converting dates to mysql format
     if (!empty($params['register_date'])) {
         $params['register_date'] = CRM_Utils_Date::isoToMysql($params['register_date']);
     }
     if (!empty($params['participant_fee_amount'])) {
         $params['participant_fee_amount'] = CRM_Utils_Rule::cleanMoney($params['participant_fee_amount']);
     }
     if (!empty($params['fee_amount'])) {
         $params['fee_amount'] = CRM_Utils_Rule::cleanMoney($params['fee_amount']);
     }
     // ensure that role ids are encoded as a string
     if (isset($params['role_id']) && is_array($params['role_id'])) {
         if (in_array(key($params['role_id']), CRM_Core_DAO::acceptedSQLOperators(), TRUE)) {
             $op = key($params['role_id']);
             $params['role_id'] = $params['role_id'][$op];
         } else {
             $params['role_id'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, $params['role_id']);
         }
     }
     $participantBAO = new CRM_Event_BAO_Participant();
     if (!empty($params['id'])) {
         $participantBAO->id = CRM_Utils_Array::value('id', $params);
         $participantBAO->find(TRUE);
         $participantBAO->register_date = CRM_Utils_Date::isoToMysql($participantBAO->register_date);
     }
     $participantBAO->copyValues($params);
     //CRM-6910
     //1. If currency present, it should be valid one.
     //2. We should have currency when amount is not null.
     $currency = $participantBAO->fee_currency;
     if ($currency || !CRM_Utils_System::isNull($participantBAO->fee_amount)) {
         if (!CRM_Utils_Rule::currencyCode($currency)) {
             $config = CRM_Core_Config::singleton();
             $currency = $config->defaultCurrency;
         }
     }
     $participantBAO->fee_currency = $currency;
     $participantBAO->save();
     $session = CRM_Core_Session::singleton();
     // reset the group contact cache for this group
     CRM_Contact_BAO_GroupContactCache::remove();
     if (!empty($params['id'])) {
         CRM_Utils_Hook::post('edit', 'Participant', $participantBAO->id, $participantBAO);
     } else {
         CRM_Utils_Hook::post('create', 'Participant', $participantBAO->id, $participantBAO);
     }
     return $participantBAO;
 }
/**
 * File for the CiviCRM APIv3 group functions
 *
 * @package CiviCRM_APIv3
 * @subpackage API_pcpteams
 * @copyright CiviCRM LLC (c) 2004-2014
 */
function civicrm_api3_pcpteams_create($params)
{
    // since we are allowing html input from the user
    // we also need to purify it, so lets clean it up
    // $params['pcp_title']      = $pcp['title'];
    // $params['pcp_contact_id'] = $pcp['contact_id'];
    $htmlFields = array('intro_text', 'page_text', 'title');
    foreach ($htmlFields as $field) {
        if (!empty($params[$field])) {
            $params[$field] = CRM_Utils_String::purifyHTML($params[$field]);
        }
    }
    $entity_table = CRM_PCP_BAO_PCP::getPcpEntityTable($params['page_type']);
    $pcpBlock = new CRM_PCP_DAO_PCPBlock();
    $pcpBlock->entity_table = $entity_table;
    $pcpBlock->entity_id = $params['page_id'];
    $pcpBlock->find(TRUE);
    $params['pcp_block_id'] = $pcpBlock->id;
    $params['goal_amount'] = CRM_Utils_Rule::cleanMoney($params['goal_amount']);
    // 1 -> waiting review
    // 2 -> active / approved (default for now)
    $params['status_id'] = CRM_Utils_Array::value('status_id', $params, 2);
    // active by default for now
    $params['is_active'] = CRM_Utils_Array::value('is_active', $params, 1);
    $pcp = CRM_Pcpteams_BAO_PCP::create($params, FALSE);
    //Custom Set
    $customFields = CRM_Core_BAO_CustomField::getFields('PCP', FALSE, FALSE, NULL, NULL, TRUE);
    $isCustomValueSet = FALSE;
    foreach ($customFields as $fieldID => $fieldValue) {
        list($tableName, $columnName, $cgId) = CRM_Core_BAO_CustomField::getTableColumnGroup($fieldID);
        if (!empty($params[$columnName]) || !empty($params["custom_{$fieldID}"])) {
            $isCustomValueSet = TRUE;
            //FIXME: to find out the custom value exists, set -1 as default now
            $params["custom_{$fieldID}_-1"] = !empty($params[$columnName]) ? $params[$columnName] : $params["custom_{$fieldID}"];
        }
    }
    if ($isCustomValueSet) {
        $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $customFields, $pcp->id, 'PCP');
        CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_pcp', $pcp->id);
    }
    //end custom set
    $values = array();
    @_civicrm_api3_object_to_array_unique_fields($pcp, $values[$pcp->id]);
    return civicrm_api3_create_success($values, $params, 'Pcpteams', 'create');
}
Ejemplo n.º 3
0
 /**
  * takes an associative array and creates a participant object
  *
  * the function extract all the params it needs to initialize the create a
  * participant object. the params array could contain additional unused name/value
  * pairs
  *
  * @param array  $params (reference ) an assoc array of name/value pairs
  * @param array $ids    the array that holds all the db ids
  *
  * @return object CRM_Event_BAO_Participant object
  * @access public
  * @static
  */
 static function &add(&$params)
 {
     require_once 'CRM/Utils/Hook.php';
     if (CRM_Utils_Array::value('id', $params)) {
         CRM_Utils_Hook::pre('edit', 'Participant', $params['id'], $params);
     } else {
         CRM_Utils_Hook::pre('create', 'Participant', null, $params);
     }
     // converting dates to mysql format
     if (CRM_Utils_Array::value('register_date', $params)) {
         $params['register_date'] = CRM_Utils_Date::isoToMysql($params['register_date']);
     }
     if (CRM_Utils_Array::value('participant_fee_amount', $params)) {
         $params['participant_fee_amount'] = CRM_Utils_Rule::cleanMoney($params['participant_fee_amount']);
     }
     $participantBAO = new CRM_Event_BAO_Participant();
     if (CRM_Utils_Array::value('id', $params)) {
         $participantBAO->id = CRM_Utils_Array::value('id', $params);
         $participantBAO->find(true);
         $participantBAO->register_date = CRM_Utils_Date::isoToMysql($participantBAO->register_date);
     }
     $participantBAO->copyValues($params);
     //make sure we have currency when amount is not null CRM-4453
     require_once 'CRM/Utils/Rule.php';
     if (!CRM_Utils_System::isNull($participantBAO->fee_amount) && !CRM_Utils_Rule::currencyCode($participantBAO->fee_currency)) {
         require_once 'CRM/Core/Config.php';
         $config =& CRM_Core_Config::singleton();
         $participantBAO->fee_currency = $config->defaultCurrency;
     }
     $participantBAO->save();
     $session =& CRM_Core_Session::singleton();
     // reset the group contact cache for this group
     require_once 'CRM/Contact/BAO/GroupContactCache.php';
     CRM_Contact_BAO_GroupContactCache::remove();
     if (CRM_Utils_Array::value('id', $params)) {
         CRM_Utils_Hook::post('edit', 'Participant', $participantBAO->id, $participantBAO);
     } else {
         CRM_Utils_Hook::post('create', 'Participant', $participantBAO->id, $participantBAO);
     }
     return $participantBAO;
 }
 /**
  * Process the form submission.
  *
  *
  * @return void
  */
 public function postProcess()
 {
     $params = $this->controller->exportValues($this->_name);
     $checkBoxes = array('is_thermometer', 'is_honor_roll', 'is_active', 'is_notify');
     foreach ($checkBoxes as $key) {
         if (!isset($params[$key])) {
             $params[$key] = 0;
         }
     }
     $session = CRM_Core_Session::singleton();
     $contactID = isset($this->_contactID) ? $this->_contactID : $session->get('userID');
     if (!$contactID) {
         $contactID = $this->get('contactID');
     }
     $params['title'] = $params['pcp_title'];
     $params['intro_text'] = $params['pcp_intro_text'];
     $params['contact_id'] = $contactID;
     $params['page_id'] = $this->get('component_page_id') ? $this->get('component_page_id') : $this->_contriPageId;
     $params['page_type'] = $this->_component;
     // since we are allowing html input from the user
     // we also need to purify it, so lets clean it up
     $htmlFields = array('intro_text', 'page_text', 'title');
     foreach ($htmlFields as $field) {
         if (!empty($params[$field])) {
             $params[$field] = CRM_Utils_String::purifyHTML($params[$field]);
         }
     }
     $entity_table = CRM_PCP_BAO_PCP::getPcpEntityTable($params['page_type']);
     $pcpBlock = new CRM_PCP_DAO_PCPBlock();
     $pcpBlock->entity_table = $entity_table;
     $pcpBlock->entity_id = $params['page_id'];
     $pcpBlock->find(TRUE);
     $params['pcp_block_id'] = $pcpBlock->id;
     $params['goal_amount'] = CRM_Utils_Rule::cleanMoney($params['goal_amount']);
     $approval_needed = $pcpBlock->is_approval_needed;
     $approvalMessage = NULL;
     if ($this->get('action') & CRM_Core_Action::ADD) {
         $params['status_id'] = $approval_needed ? 1 : 2;
         $approvalMessage = $approval_needed ? ts('but requires administrator review before you can begin promoting your campaign. You will receive an email confirmation shortly which includes a link to return to this page.') : ts('and is ready to use.');
     }
     $params['id'] = $this->_pageId;
     $pcp = CRM_PCP_BAO_PCP::add($params, FALSE);
     //create page in wordpress
     create_wp_campaign($pcp->title, $pcp->contact_id, $pcp->id);
     CRM_Core_Error::debug_log_message("Calling create_wp_campaign.... Params title: {$pcp->title}, contact_id: {$pcp->contact_id}, pcp_id: {$pcp->id} ");
     // add attachments as needed
     CRM_Core_BAO_File::formatAttachment($params, $params, 'civicrm_pcp', $pcp->id);
     $pageStatus = isset($this->_pageId) ? ts('updated') : ts('created');
     $statusId = CRM_Core_DAO::getFieldValue('CRM_PCP_DAO_PCP', $pcp->id, 'status_id');
     //send notification of PCP create/update.
     $pcpParams = array('entity_table' => $entity_table, 'entity_id' => $pcp->page_id);
     $notifyParams = array();
     $notifyStatus = "";
     CRM_Core_DAO::commonRetrieve('CRM_PCP_DAO_PCPBlock', $pcpParams, $notifyParams, array('notify_email'));
     if ($emails = $pcpBlock->notify_email) {
         $this->assign('pcpTitle', $pcp->title);
         if ($this->_pageId) {
             $this->assign('mode', 'Update');
         } else {
             $this->assign('mode', 'Add');
         }
         $pcpStatus = CRM_Core_OptionGroup::getLabel('pcp_status', $statusId);
         $this->assign('pcpStatus', $pcpStatus);
         $this->assign('pcpId', $pcp->id);
         $supporterUrl = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$pcp->contact_id}", TRUE, NULL, FALSE, FALSE);
         $this->assign('supporterUrl', $supporterUrl);
         $supporterName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $pcp->contact_id, 'display_name');
         $this->assign('supporterName', $supporterName);
         if ($this->_component == 'contribute') {
             $pageUrl = CRM_Utils_System::url('civicrm/contribute/transact', "reset=1&id={$pcpBlock->entity_id}", TRUE, NULL, FALSE, TRUE);
             $contribPageTitle = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionPage', $pcpBlock->entity_id, 'title');
         } elseif ($this->_component == 'event') {
             $pageUrl = CRM_Utils_System::url('civicrm/event', "reset=1&id={$pcpBlock->entity_id}", TRUE, NULL, FALSE, TRUE);
             $contribPageTitle = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $pcpBlock->entity_id, 'title');
         }
         $this->assign('contribPageUrl', $pageUrl);
         $this->assign('contribPageTitle', $contribPageTitle);
         $managePCPUrl = CRM_Utils_System::url('civicrm/admin/pcp', "reset=1", TRUE, NULL, FALSE, FALSE);
         $this->assign('managePCPUrl', $managePCPUrl);
         //get the default domain email address.
         list($domainEmailName, $domainEmailAddress) = CRM_Core_BAO_Domain::getNameAndEmail();
         if (!$domainEmailAddress || $domainEmailAddress == '*****@*****.**') {
             $fixUrl = CRM_Utils_System::url('civicrm/admin/domain', 'action=update&reset=1');
             CRM_Core_Error::fatal(ts('The site administrator needs to enter a valid \'FROM Email Address\' in <a href="%1">Administer CiviCRM &raquo; Communications &raquo; FROM Email Addresses</a>. The email address used may need to be a valid mail account with your email service provider.', array(1 => $fixUrl)));
         }
         //if more than one email present for PCP notification ,
         //first email take it as To and other as CC and First email
         //address should be sent in users email receipt for
         //support purpose.
         $emailArray = explode(',', $emails);
         $to = $emailArray[0];
         unset($emailArray[0]);
         $cc = implode(',', $emailArray);
         list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate(array('groupName' => 'msg_tpl_workflow_contribution', 'valueName' => 'pcp_notify', 'contactId' => $contactID, 'from' => "{$domainEmailName} <{$domainEmailAddress}>", 'toEmail' => $to, 'cc' => $cc));
         if ($sent) {
             $notifyStatus = ts('A notification email has been sent to the site administrator.');
         }
     }
     CRM_Core_BAO_File::processAttachment($params, 'civicrm_pcp', $pcp->id);
     // send email notification to supporter, if initial setup / add mode.
     if (!$this->_pageId) {
         CRM_PCP_BAO_PCP::sendStatusUpdate($pcp->id, $statusId, TRUE, $this->_component);
         if ($approvalMessage && CRM_Utils_Array::value('status_id', $params) == 1) {
             $notifyStatus .= ts(' You will receive a second email as soon as the review process is complete.');
         }
     }
     //check if pcp created by anonymous user
     $anonymousPCP = 0;
     if (!$session->get('userID')) {
         $anonymousPCP = 1;
     }
     CRM_Core_Session::setStatus(ts("Your Personal Campaign Page has been %1 %2 %3", array(1 => $pageStatus, 2 => $approvalMessage, 3 => $notifyStatus)), '', 'info');
     if (!$this->_pageId) {
         $session->pushUserContext(CRM_Utils_System::url('civicrm/pcp/info', "reset=1&id={$pcp->id}&ap={$anonymousPCP}"));
     } elseif ($this->_context == 'dashboard') {
         $session->pushUserContext(CRM_Utils_System::url('civicrm/admin/pcp', 'reset=1'));
     }
 }
Ejemplo n.º 5
0
 /**
  * Process the form
  *
  * @return void
  * @access public
  */
 public function postProcess()
 {
     // get the submitted form values.
     $params = $this->controller->exportValues($this->_name);
     if (array_key_exists('payment_processor', $params)) {
         if (array_key_exists(CRM_Core_DAO::getFieldValue('CRM_Core_DAO_PaymentProcessor', 'AuthNet', 'id', 'payment_processor_type'), CRM_Utils_Array::value('payment_processor', $params))) {
             CRM_Core_Session::setStatus(ts(' Please note that the Authorize.net payment processor only allows recurring contributions and auto-renew memberships with payment intervals from 7-365 days or 1-12 months (i.e. not greater than 1 year).'));
         }
     }
     // check for price set.
     $priceSetID = CRM_Utils_Array::value('price_set_id', $params);
     // get required fields.
     $fields = array('id' => $this->_id, 'is_recur' => FALSE, 'min_amount' => "null", 'max_amount' => "null", 'is_monetary' => FALSE, 'is_pay_later' => FALSE, 'is_recur_interval' => FALSE, 'recur_frequency_unit' => "null", 'default_amount_id' => "null", 'is_allow_other_amount' => FALSE, 'amount_block_is_active' => FALSE);
     $resetFields = array();
     if ($priceSetID) {
         $resetFields = array('min_amount', 'max_amount', 'is_allow_other_amount');
     }
     if (!CRM_Utils_Array::value('is_recur', $params)) {
         $resetFields = array_merge($resetFields, array('is_recur_interval', 'recur_frequency_unit'));
     }
     foreach ($fields as $field => $defaultVal) {
         $val = CRM_Utils_Array::value($field, $params, $defaultVal);
         if (in_array($field, $resetFields)) {
             $val = $defaultVal;
         }
         if (in_array($field, array('min_amount', 'max_amount'))) {
             $val = CRM_Utils_Rule::cleanMoney($val);
         }
         $params[$field] = $val;
     }
     if ($params['is_recur']) {
         $params['recur_frequency_unit'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, array_keys($params['recur_frequency_unit']));
         $params['is_recur_interval'] = CRM_Utils_Array::value('is_recur_interval', $params, FALSE);
     }
     if (array_key_exists('payment_processor', $params) && !CRM_Utils_System::isNull($params['payment_processor'])) {
         $params['payment_processor'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, array_keys($params['payment_processor']));
     } else {
         $params['payment_processor'] = 'null';
     }
     $contributionPage = CRM_Contribute_BAO_ContributionPage::create($params);
     $contributionPageID = $contributionPage->id;
     // prepare for data cleanup.
     $deleteAmountBlk = $deletePledgeBlk = $deletePriceSet = FALSE;
     if ($this->_priceSetID) {
         $deletePriceSet = TRUE;
     }
     if ($this->_pledgeBlockID) {
         $deletePledgeBlk = TRUE;
     }
     if (!empty($this->_amountBlock)) {
         $deleteAmountBlk = TRUE;
     }
     if ($contributionPageID) {
         if (CRM_Utils_Array::value('amount_block_is_active', $params)) {
             // handle price set.
             if ($priceSetID) {
                 // add/update price set.
                 $deletePriceSet = FALSE;
                 if (CRM_Utils_Array::value('price_field_id', $params) || CRM_Utils_Array::value('price_field_other', $params)) {
                     $deleteAmountBlk = TRUE;
                 }
                 CRM_Price_BAO_Set::addTo('civicrm_contribution_page', $contributionPageID, $priceSetID);
             } else {
                 $deletePriceSet = FALSE;
                 // process contribution amount block
                 $deleteAmountBlk = FALSE;
                 $labels = CRM_Utils_Array::value('label', $params);
                 $values = CRM_Utils_Array::value('value', $params);
                 $default = CRM_Utils_Array::value('default', $params);
                 $options = array();
                 for ($i = 1; $i < self::NUM_OPTION; $i++) {
                     if (isset($values[$i]) && strlen(trim($values[$i])) > 0) {
                         $options[] = array('label' => trim($labels[$i]), 'value' => CRM_Utils_Rule::cleanMoney(trim($values[$i])), 'weight' => $i, 'is_active' => 1, 'is_default' => $default == $i);
                     }
                 }
                 /* || CRM_Utils_Array::value( 'price_field_value', $params )|| CRM_Utils_Array::value( 'price_field_other', $params )*/
                 if (!empty($options) || CRM_Utils_Array::value('is_allow_other_amount', $params)) {
                     $fieldParams['is_quick_config'] = 1;
                     $noContriAmount = NULL;
                     $usedPriceSetId = CRM_Price_BAO_Set::getFor('civicrm_contribution_page', $this->_id, 3);
                     if (!(CRM_Utils_Array::value('price_field_id', $params) || CRM_Utils_Array::value('price_field_other', $params)) && !$usedPriceSetId) {
                         $pageTitle = strtolower(CRM_Utils_String::munge($this->_values['title'], '_', 245));
                         $setParams['title'] = $this->_values['title'];
                         if (!CRM_Core_DAO::getFieldValue('CRM_Price_BAO_Set', $pageTitle, 'id', 'name')) {
                             $setParams['name'] = $pageTitle;
                         } elseif (!CRM_Core_DAO::getFieldValue('CRM_Price_BAO_Set', $pageTitle . '_' . $this->_id, 'id', 'name')) {
                             $setParams['name'] = $pageTitle . '_' . $this->_id;
                         } else {
                             $timeSec = explode(".", microtime(true));
                             $setParams['name'] = $pageTitle . '_' . date('is', $timeSec[0]) . $timeSec[1];
                         }
                         $setParams['is_quick_config'] = 1;
                         $setParams['extends'] = CRM_Core_Component::getComponentID('CiviContribute');
                         $priceSet = CRM_Price_BAO_Set::create($setParams);
                         $priceSetId = $priceSet->id;
                     } elseif ($usedPriceSetId && !CRM_Utils_Array::value('price_field_id', $params)) {
                         $priceSetId = $usedPriceSetId;
                     } else {
                         if ($priceFieldId = CRM_Utils_Array::value('price_field_id', $params)) {
                             foreach ($params['price_field_value'] as $arrayID => $fieldValueID) {
                                 if (empty($params['label'][$arrayID]) && empty($params['value'][$arrayID]) && !empty($fieldValueID)) {
                                     CRM_Price_BAO_FieldValue::setIsActive($fieldValueID, '0');
                                     unset($params['price_field_value'][$arrayID]);
                                 }
                             }
                             if (implode('', $params['price_field_value'])) {
                                 $fieldParams['id'] = CRM_Utils_Array::value('price_field_id', $params);
                                 $fieldParams['option_id'] = $params['price_field_value'];
                             } else {
                                 $noContriAmount = 0;
                                 CRM_Price_BAO_Field::setIsActive($priceFieldId, '0');
                             }
                         } else {
                             $priceFieldId = CRM_Utils_Array::value('price_field_other', $params);
                         }
                         $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_Field', $priceFieldId, 'price_set_id');
                     }
                     CRM_Price_BAO_Set::addTo('civicrm_contribution_page', $this->_id, $priceSetId);
                     if (!empty($options)) {
                         $editedFieldParams = array('price_set_id' => $priceSetId, 'name' => 'contribution_amount');
                         $editedResults = array();
                         $noContriAmount = 1;
                         CRM_Price_BAO_Field::retrieve($editedFieldParams, $editedResults);
                         if (!CRM_Utils_Array::value('id', $editedResults)) {
                             $fieldParams['name'] = strtolower(CRM_Utils_String::munge("Contribution Amount", '_', 245));
                             $fieldParams['label'] = "Contribution Amount";
                         } else {
                             $fieldParams['id'] = CRM_Utils_Array::value('id', $editedResults);
                         }
                         $fieldParams['price_set_id'] = $priceSetId;
                         $fieldParams['is_active'] = 1;
                         $fieldParams['weight'] = 2;
                         if (CRM_Utils_Array::value('is_allow_other_amount', $params)) {
                             $fieldParams['is_required'] = 0;
                         } else {
                             $fieldParams['is_required'] = 1;
                         }
                         $fieldParams['html_type'] = 'Radio';
                         $fieldParams['option_label'] = $params['label'];
                         $fieldParams['option_amount'] = $params['value'];
                         foreach ($options as $value) {
                             $fieldParams['option_weight'][$value['weight']] = $value['weight'];
                         }
                         $fieldParams['default_option'] = $params['default'];
                         $priceField = CRM_Price_BAO_Field::create($fieldParams);
                     }
                     if (CRM_Utils_Array::value('is_allow_other_amount', $params) && !CRM_Utils_Array::value('price_field_other', $params)) {
                         $editedFieldParams = array('price_set_id' => $priceSetId, 'name' => 'other_amount');
                         $editedResults = array();
                         CRM_Price_BAO_Field::retrieve($editedFieldParams, $editedResults);
                         if (!($priceFieldID = CRM_Utils_Array::value('id', $editedResults))) {
                             $fieldParams = array('name' => 'other_amount', 'label' => 'Other Amount', 'price_set_id' => $priceSetId, 'html_type' => 'Text', 'is_display_amounts' => 0, 'weight' => 3);
                             $fieldParams['option_weight'][1] = 1;
                             $fieldParams['option_amount'][1] = 1;
                             if (!$noContriAmount) {
                                 $fieldParams['is_required'] = 1;
                                 $fieldParams['option_label'][1] = 'Contribution Amount';
                             } else {
                                 $fieldParams['is_required'] = 0;
                                 $fieldParams['option_label'][1] = 'Other Amount';
                             }
                             $priceField = CRM_Price_BAO_Field::create($fieldParams);
                         } else {
                             if (!CRM_Utils_Array::value('is_active', $editedResults)) {
                                 CRM_Price_BAO_Field::setIsActive($priceFieldID, '1');
                             }
                         }
                     } elseif (!CRM_Utils_Array::value('is_allow_other_amount', $params) && CRM_Utils_Array::value('price_field_other', $params)) {
                         CRM_Price_BAO_Field::setIsActive($params['price_field_other'], '0');
                     } elseif ($priceFieldID = CRM_Utils_Array::value('price_field_other', $params)) {
                         $priceFieldValueID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_FieldValue', $priceFieldID, 'id', 'price_field_id');
                         if (!$noContriAmount) {
                             CRM_Core_DAO::setFieldValue('CRM_Price_DAO_Field', $priceFieldID, 'is_required', 1);
                             CRM_Core_DAO::setFieldValue('CRM_Price_DAO_FieldValue', $priceFieldValueID, 'label', 'Contribution Amount');
                         } else {
                             CRM_Core_DAO::setFieldValue('CRM_Price_DAO_Field', $priceFieldID, 'is_required', 0);
                             CRM_Core_DAO::setFieldValue('CRM_Price_DAO_FieldValue', $priceFieldValueID, 'label', 'Other Amount');
                         }
                     }
                 }
                 if (CRM_Utils_Array::value('is_pledge_active', $params)) {
                     $deletePledgeBlk = FALSE;
                     $pledgeBlockParams = array('entity_id' => $contributionPageID, 'entity_table' => ts('civicrm_contribution_page'));
                     if ($this->_pledgeBlockID) {
                         $pledgeBlockParams['id'] = $this->_pledgeBlockID;
                     }
                     $pledgeBlock = array('pledge_frequency_unit', 'max_reminders', 'initial_reminder_day', 'additional_reminder_day');
                     foreach ($pledgeBlock as $key) {
                         $pledgeBlockParams[$key] = CRM_Utils_Array::value($key, $params);
                     }
                     $pledgeBlockParams['is_pledge_interval'] = CRM_Utils_Array::value('is_pledge_interval', $params, FALSE);
                     // create pledge block.
                     CRM_Pledge_BAO_PledgeBlock::create($pledgeBlockParams);
                 }
             }
         } else {
             if (CRM_Utils_Array::value('price_field_id', $params) || CRM_Utils_Array::value('price_field_other', $params)) {
                 $usedPriceSetId = CRM_Price_BAO_Set::getFor('civicrm_contribution_page', $this->_id, 3);
                 if ($usedPriceSetId) {
                     if (CRM_Utils_Array::value('price_field_id', $params)) {
                         CRM_Price_BAO_Field::setIsActive($params['price_field_id'], '0');
                     }
                     if (CRM_Utils_Array::value('price_field_other', $params)) {
                         CRM_Price_BAO_Field::setIsActive($params['price_field_other'], '0');
                     }
                 } else {
                     $deleteAmountBlk = TRUE;
                     $deletePriceSet = TRUE;
                 }
             }
         }
         // delete pledge block.
         if ($deletePledgeBlk) {
             CRM_Pledge_BAO_PledgeBlock::deletePledgeBlock($this->_pledgeBlockID);
         }
         // delete previous price set.
         if ($deletePriceSet) {
             CRM_Price_BAO_Set::removeFrom('civicrm_contribution_page', $contributionPageID);
         }
         if ($deleteAmountBlk) {
             $priceField = CRM_Utils_Array::value('price_field_id', $params) ? $params['price_field_id'] : CRM_Utils_Array::value('price_field_other', $params);
             if ($priceField) {
                 $priceSetID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_Field', $priceField, 'price_set_id');
                 CRM_Price_BAO_Set::setIsQuickConfig($priceSetID, 0);
             }
         }
     }
     parent::endPostProcess();
 }
Ejemplo n.º 6
0
 static function updateCustomValues($params)
 {
     $optionDAO = new CRM_Core_DAO_OptionValue();
     $optionDAO->id = $params['optionId'];
     $optionDAO->find(TRUE);
     $oldValue = $optionDAO->value;
     // get the table, column, html_type and data type for this field
     $query = "\nSELECT g.table_name  as tableName ,\n       f.column_name as columnName,\n       f.data_type   as dataType,\n       f.html_type   as htmlType\nFROM   civicrm_custom_group g,\n       civicrm_custom_field f\nWHERE  f.custom_group_id = g.id\n  AND  f.id = %1";
     $queryParams = array(1 => array($params['fieldId'], 'Integer'));
     $dao = CRM_Core_DAO::executeQuery($query, $queryParams);
     if ($dao->fetch()) {
         if ($dao->dataType == 'Money') {
             $params['value'] = CRM_Utils_Rule::cleanMoney($params['value']);
         }
         switch ($dao->htmlType) {
             case 'Autocomplete-Select':
             case 'Select':
             case 'Radio':
                 $query = "\nUPDATE {$dao->tableName}\nSET    {$dao->columnName} = %1\nWHERE  id = %2";
                 if ($dao->dataType == 'Auto-complete') {
                     $dataType = "String";
                 } else {
                     $dataType = $dao->dataType;
                 }
                 $queryParams = array(1 => array($params['value'], $dataType), 2 => array($params['optionId'], 'Integer'));
                 break;
             case 'AdvMulti-Select':
             case 'Multi-Select':
             case 'CheckBox':
                 $oldString = CRM_Core_DAO::VALUE_SEPARATOR . $oldValue . CRM_Core_DAO::VALUE_SEPARATOR;
                 $newString = CRM_Core_DAO::VALUE_SEPARATOR . $params['value'] . CRM_Core_DAO::VALUE_SEPARATOR;
                 $query = "\nUPDATE {$dao->tableName}\nSET    {$dao->columnName} = REPLACE( {$dao->columnName}, %1, %2 )";
                 $queryParams = array(1 => array($oldString, 'String'), 2 => array($newString, 'String'));
                 break;
             default:
                 CRM_Core_Error::fatal();
         }
         $dao = CRM_Core_DAO::executeQuery($query, $queryParams);
     }
 }
Ejemplo n.º 7
0
 /**
  * Process the form.
  */
 public function postProcess()
 {
     $eventTitle = '';
     $params = $this->exportValues();
     $this->set('discountSection', 0);
     if (!empty($_POST['_qf_Fee_submit'])) {
         $this->buildAmountLabel();
         $this->set('discountSection', 2);
         return;
     }
     if (!empty($params['payment_processor'])) {
         $params['payment_processor'] = str_replace(',', CRM_Core_DAO::VALUE_SEPARATOR, $params['payment_processor']);
     } else {
         $params['payment_processor'] = 'null';
     }
     $params['is_pay_later'] = CRM_Utils_Array::value('is_pay_later', $params, 0);
     $params['is_billing_required'] = CRM_Utils_Array::value('is_billing_required', $params, 0);
     if ($this->_id) {
         // delete all the prior label values or discounts in the custom options table
         // and delete a price set if one exists
         //@todo note that this removes the reference from existing participants -
         // even where there is not change - redress?
         // note that a more tentative form of this is invoked by passing price_set_id as an array
         // to event.create see CRM-14069
         // @todo get all of this logic out of form layer (currently partially in BAO/api layer)
         if (CRM_Price_BAO_PriceSet::removeFrom('civicrm_event', $this->_id)) {
             CRM_Core_BAO_Discount::del($this->_id, 'civicrm_event');
         }
     }
     if ($params['is_monetary']) {
         if (!empty($params['price_set_id'])) {
             //@todo this is now being done in the event BAO if passed price_set_id as an array
             // per notes on that fn - looking at the api converting to an array
             // so calling via the api may cause this to be done in the api
             CRM_Price_BAO_PriceSet::addTo('civicrm_event', $this->_id, $params['price_set_id']);
             if (!empty($params['price_field_id'])) {
                 $priceSetID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $params['price_field_id'], 'price_set_id');
                 CRM_Price_BAO_PriceSet::setIsQuickConfig($priceSetID, 0);
             }
         } else {
             // if there are label / values, create custom options for them
             $labels = CRM_Utils_Array::value('label', $params);
             $values = CRM_Utils_Array::value('value', $params);
             $default = CRM_Utils_Array::value('default', $params);
             $options = array();
             if (!CRM_Utils_System::isNull($labels) && !CRM_Utils_System::isNull($values)) {
                 for ($i = 1; $i < self::NUM_OPTION; $i++) {
                     if (!empty($labels[$i]) && !CRM_Utils_System::isNull($values[$i])) {
                         $options[] = array('label' => trim($labels[$i]), 'value' => CRM_Utils_Rule::cleanMoney(trim($values[$i])), 'weight' => $i, 'is_active' => 1, 'is_default' => $default == $i);
                     }
                 }
                 if (!empty($options)) {
                     $params['default_fee_id'] = NULL;
                     if (empty($params['price_set_id'])) {
                         if (empty($params['price_field_id'])) {
                             $setParams['title'] = $eventTitle = $this->_isTemplate ? $this->_defaultValues['template_title'] : $this->_defaultValues['title'];
                             $eventTitle = strtolower(CRM_Utils_String::munge($eventTitle, '_', 245));
                             if (!CRM_Core_DAO::getFieldValue('CRM_Price_BAO_PriceSet', $eventTitle, 'id', 'name')) {
                                 $setParams['name'] = $eventTitle;
                             } elseif (!CRM_Core_DAO::getFieldValue('CRM_Price_BAO_PriceSet', $eventTitle . '_' . $this->_id, 'id', 'name')) {
                                 $setParams['name'] = $eventTitle . '_' . $this->_id;
                             } else {
                                 $timeSec = explode('.', microtime(TRUE));
                                 $setParams['name'] = $eventTitle . '_' . date('is', $timeSec[0]) . $timeSec[1];
                             }
                             $setParams['is_quick_config'] = 1;
                             $setParams['financial_type_id'] = $params['financial_type_id'];
                             $setParams['extends'] = CRM_Core_Component::getComponentID('CiviEvent');
                             $priceSet = CRM_Price_BAO_PriceSet::create($setParams);
                             $fieldParams['name'] = strtolower(CRM_Utils_String::munge($params['fee_label'], '_', 245));
                             $fieldParams['price_set_id'] = $priceSet->id;
                         } else {
                             foreach ($params['price_field_value'] as $arrayID => $fieldValueID) {
                                 if (empty($params['label'][$arrayID]) && empty($params['value'][$arrayID]) && !empty($fieldValueID)) {
                                     CRM_Price_BAO_PriceFieldValue::setIsActive($fieldValueID, '0');
                                     unset($params['price_field_value'][$arrayID]);
                                 }
                             }
                             $fieldParams['id'] = CRM_Utils_Array::value('price_field_id', $params);
                             $fieldParams['option_id'] = $params['price_field_value'];
                             $priceSet = new CRM_Price_BAO_PriceSet();
                             $priceSet->id = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', CRM_Utils_Array::value('price_field_id', $params), 'price_set_id');
                             if ($this->_defaultValues['financial_type_id'] != $params['financial_type_id']) {
                                 CRM_Core_DAO::setFieldValue('CRM_Price_DAO_PriceSet', $priceSet->id, 'financial_type_id', $params['financial_type_id']);
                             }
                         }
                         $fieldParams['label'] = $params['fee_label'];
                         $fieldParams['html_type'] = 'Radio';
                         CRM_Price_BAO_PriceSet::addTo('civicrm_event', $this->_id, $priceSet->id);
                         $fieldParams['option_label'] = $params['label'];
                         $fieldParams['option_amount'] = $params['value'];
                         $fieldParams['financial_type_id'] = $params['financial_type_id'];
                         foreach ($options as $value) {
                             $fieldParams['option_weight'][$value['weight']] = $value['weight'];
                         }
                         $fieldParams['default_option'] = $params['default'];
                         $priceField = CRM_Price_BAO_PriceField::create($fieldParams);
                     }
                 }
             }
             $discountPriceSets = !empty($this->_defaultValues['discount_price_set']) ? $this->_defaultValues['discount_price_set'] : array();
             $discountFieldIDs = !empty($this->_defaultValues['discount_option_id']) ? $this->_defaultValues['discount_option_id'] : array();
             if (CRM_Utils_Array::value('is_discount', $params) == 1) {
                 // if there are discounted set of label / values,
                 // create custom options for them
                 $labels = CRM_Utils_Array::value('discounted_label', $params);
                 $values = CRM_Utils_Array::value('discounted_value', $params);
                 $default = CRM_Utils_Array::value('discounted_default', $params);
                 if (!CRM_Utils_System::isNull($labels) && !CRM_Utils_System::isNull($values)) {
                     for ($j = 1; $j <= self::NUM_DISCOUNT; $j++) {
                         $discountOptions = array();
                         for ($i = 1; $i < self::NUM_OPTION; $i++) {
                             if (!empty($labels[$i]) && !CRM_Utils_System::isNull(CRM_Utils_Array::value($j, $values[$i]))) {
                                 $discountOptions[] = array('label' => trim($labels[$i]), 'value' => CRM_Utils_Rule::cleanMoney(trim($values[$i][$j])), 'weight' => $i, 'is_active' => 1, 'is_default' => $default == $i);
                             }
                         }
                         if (!empty($discountOptions)) {
                             $fieldParams = array();
                             $params['default_discount_fee_id'] = NULL;
                             $keyCheck = $j - 1;
                             $setParams = array();
                             if (empty($discountPriceSets[$keyCheck])) {
                                 if (!$eventTitle) {
                                     $eventTitle = strtolower(CRM_Utils_String::munge($this->_defaultValues['title'], '_', 200));
                                 }
                                 $setParams['title'] = $params['discount_name'][$j];
                                 if (!CRM_Core_DAO::getFieldValue('CRM_Price_BAO_PriceSet', $eventTitle . '_' . $params['discount_name'][$j], 'id', 'name')) {
                                     $setParams['name'] = $eventTitle . '_' . $params['discount_name'][$j];
                                 } elseif (!CRM_Core_DAO::getFieldValue('CRM_Price_BAO_PriceSet', $eventTitle . '_' . $params['discount_name'][$j] . '_' . $this->_id, 'id', 'name')) {
                                     $setParams['name'] = $eventTitle . '_' . $params['discount_name'][$j] . '_' . $this->_id;
                                 } else {
                                     $timeSec = explode('.', microtime(TRUE));
                                     $setParams['name'] = $eventTitle . '_' . $params['discount_name'][$j] . '_' . date('is', $timeSec[0]) . $timeSec[1];
                                 }
                                 $setParams['is_quick_config'] = 1;
                                 $setParams['financial_type_id'] = $params['financial_type_id'];
                                 $setParams['extends'] = CRM_Core_Component::getComponentID('CiviEvent');
                                 $priceSet = CRM_Price_BAO_PriceSet::create($setParams);
                                 $priceSetID = $priceSet->id;
                             } else {
                                 $priceSetID = $discountPriceSets[$j - 1];
                                 $setParams = array('title' => $params['discount_name'][$j], 'id' => $priceSetID);
                                 if ($this->_defaultValues['financial_type_id'] != $params['financial_type_id']) {
                                     $setParams['financial_type_id'] = $params['financial_type_id'];
                                 }
                                 CRM_Price_BAO_PriceSet::create($setParams);
                                 unset($discountPriceSets[$j - 1]);
                                 $fieldParams['id'] = CRM_Core_DAO::getFieldValue('CRM_Price_BAO_PriceField', $priceSetID, 'id', 'price_set_id');
                             }
                             $fieldParams['name'] = $fieldParams['label'] = $params['fee_label'];
                             $fieldParams['is_required'] = 1;
                             $fieldParams['price_set_id'] = $priceSetID;
                             $fieldParams['html_type'] = 'Radio';
                             $fieldParams['financial_type_id'] = $params['financial_type_id'];
                             foreach ($discountOptions as $value) {
                                 $fieldParams['option_label'][$value['weight']] = $value['label'];
                                 $fieldParams['option_amount'][$value['weight']] = $value['value'];
                                 $fieldParams['option_weight'][$value['weight']] = $value['weight'];
                                 if (!empty($value['is_default'])) {
                                     $fieldParams['default_option'] = $value['weight'];
                                 }
                                 if (!empty($discountFieldIDs[$j]) && !empty($discountFieldIDs[$j][$value['weight']])) {
                                     $fieldParams['option_id'][$value['weight']] = $discountFieldIDs[$j][$value['weight']];
                                     unset($discountFieldIDs[$j][$value['weight']]);
                                 }
                             }
                             //create discount priceset
                             $priceField = CRM_Price_BAO_PriceField::create($fieldParams);
                             if (!empty($discountFieldIDs[$j])) {
                                 foreach ($discountFieldIDs[$j] as $fID) {
                                     CRM_Price_BAO_PriceFieldValue::setIsActive($fID, '0');
                                 }
                             }
                             $discountParams = array('entity_table' => 'civicrm_event', 'entity_id' => $this->_id, 'price_set_id' => $priceSetID, 'start_date' => CRM_Utils_Date::processDate($params['discount_start_date'][$j]), 'end_date' => CRM_Utils_Date::processDate($params['discount_end_date'][$j]));
                             CRM_Core_BAO_Discount::add($discountParams);
                         }
                     }
                 }
             }
             if (!empty($discountPriceSets)) {
                 foreach ($discountPriceSets as $setId) {
                     CRM_Price_BAO_PriceSet::setIsQuickConfig($setId, 0);
                 }
             }
         }
     } else {
         if (!empty($params['price_field_id'])) {
             $priceSetID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $params['price_field_id'], 'price_set_id');
             CRM_Price_BAO_PriceSet::setIsQuickConfig($priceSetID, 0);
         }
         $params['financial_type_id'] = '';
         $params['is_pay_later'] = 0;
         $params['is_billing_required'] = 0;
     }
     //update 'is_billing_required'
     if (empty($params['is_pay_later'])) {
         $params['is_billing_required'] = FALSE;
     }
     //update events table
     $params['id'] = $this->_id;
     // skip update of financial type in price set
     $params['skipFinancialType'] = TRUE;
     CRM_Event_BAO_Event::add($params);
     // Update tab "disabled" css class
     $this->ajaxResponse['tabValid'] = !empty($params['is_monetary']);
     parent::endPostProcess();
 }
Ejemplo n.º 8
0
 /**
  * Process the form.
  *
  * @return void
  */
 public function postProcess()
 {
     if ($this->_action == CRM_Core_Action::DELETE) {
         $fieldValues = array('price_field_id' => $this->_fid);
         $wt = CRM_Utils_Weight::delWeight('CRM_Price_DAO_PriceFieldValue', $this->_oid, $fieldValues);
         $label = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $this->_oid, 'label', 'id');
         if (CRM_Price_BAO_PriceFieldValue::del($this->_oid)) {
             CRM_Core_Session::setStatus(ts('%1 option has been deleted.', array(1 => $label)), ts('Record Deleted'), 'success');
         }
         return NULL;
     } else {
         $params = $ids = array();
         $params = $this->controller->exportValues('Option');
         $fieldLabel = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $this->_fid, 'label');
         $params['amount'] = CRM_Utils_Rule::cleanMoney(trim($params['amount']));
         $params['price_field_id'] = $this->_fid;
         $params['is_default'] = CRM_Utils_Array::value('is_default', $params, FALSE);
         $params['is_active'] = CRM_Utils_Array::value('is_active', $params, FALSE);
         $ids = array();
         if ($this->_oid) {
             $ids['id'] = $this->_oid;
         }
         $optionValue = CRM_Price_BAO_PriceFieldValue::create($params, $ids);
         CRM_Core_Session::setStatus(ts("The option '%1' has been saved.", array(1 => $params['label'])), ts('Value Saved'), 'success');
     }
 }
Ejemplo n.º 9
0
 /**
  * takes an associative array and creates a contribution object
  *
  * the function extract all the params it needs to initialize the create a
  * contribution object. the params array could contain additional unused name/value
  * pairs
  *
  * @param array  $params (reference ) an assoc array of name/value pairs
  * @param array $ids    the array that holds all the db ids
  *
  * @return object CRM_Contribute_BAO_Contribution object
  * @access public
  * @static
  */
 static function add(&$params, &$ids)
 {
     if (empty($params)) {
         return;
     }
     $duplicates = array();
     if (self::checkDuplicate($params, $duplicates, CRM_Utils_Array::value('contribution', $ids))) {
         $error =& CRM_Core_Error::singleton();
         $d = implode(', ', $duplicates);
         $error->push(CRM_Core_Error::DUPLICATE_CONTRIBUTION, 'Fatal', array($d), "Duplicate error - existing contribution record(s) have a matching Transaction ID or Invoice ID. Contribution record ID(s) are: {$d}");
         return $error;
     }
     // first clean up all the money fields
     $moneyFields = array('total_amount', 'net_amount', 'fee_amount', 'non_deductible_amount');
     //if priceset is used, no need to cleanup money
     if (CRM_UTils_Array::value('skipCleanMoney', $params)) {
         unset($moneyFields[0]);
     }
     foreach ($moneyFields as $field) {
         if (isset($params[$field])) {
             $params[$field] = CRM_Utils_Rule::cleanMoney($params[$field]);
         }
     }
     if (CRM_Utils_Array::value('payment_instrument_id', $params)) {
         require_once 'CRM/Contribute/PseudoConstant.php';
         $paymentInstruments = CRM_Contribute_PseudoConstant::paymentInstrument('name');
         if ($params['payment_instrument_id'] != array_search('Check', $paymentInstruments)) {
             $params['check_number'] = 'null';
         }
     }
     require_once 'CRM/Utils/Hook.php';
     if (CRM_Utils_Array::value('contribution', $ids)) {
         CRM_Utils_Hook::pre('edit', 'Contribution', $ids['contribution'], $params);
     } else {
         CRM_Utils_Hook::pre('create', 'Contribution', null, $params);
     }
     $contribution = new CRM_Contribute_BAO_Contribution();
     $contribution->copyValues($params);
     $contribution->id = CRM_Utils_Array::value('contribution', $ids);
     // also add financial_trxn details as part of fix for CRM-4724
     $contribution->trxn_result_code = CRM_Utils_Array::value('trxn_result_code', $params);
     $contribution->payment_processor = CRM_Utils_Array::value('payment_processor', $params);
     require_once 'CRM/Utils/Rule.php';
     if (!CRM_Utils_Rule::currencyCode($contribution->currency)) {
         require_once 'CRM/Core/Config.php';
         $config = CRM_Core_Config::singleton();
         $contribution->currency = $config->defaultCurrency;
     }
     $result = $contribution->save();
     // reset the group contact cache for this group
     require_once 'CRM/Contact/BAO/GroupContactCache.php';
     CRM_Contact_BAO_GroupContactCache::remove();
     if (CRM_Utils_Array::value('contribution', $ids)) {
         CRM_Utils_Hook::post('edit', 'Contribution', $contribution->id, $contribution);
     } else {
         CRM_Utils_Hook::post('create', 'Contribution', $contribution->id, $contribution);
     }
     return $result;
 }
Ejemplo n.º 10
0
 /**
  * The post processing of the form gets done here.
  *
  * Key things done during post processing are
  *      - check for reset or next request. if present, skip post processing.
  *      - now check if user requested running a saved search, if so, then
  *        the form values associated with the saved search are used for searching.
  *      - if user has done a submit with new values the regular post submission is
  *        done.
  * The processing consists of using a Selector / Controller framework for getting the
  * search results.
  */
 public function postProcess()
 {
     if ($this->_done) {
         return;
     }
     $this->_done = TRUE;
     if (!empty($_POST)) {
         $this->_formValues = $this->controller->exportValues($this->_name);
     }
     $this->fixFormValues();
     // We don't show test records in summaries or dashboards
     if (empty($this->_formValues['contribution_test']) && $this->_force && !empty($this->_context) && $this->_context == 'dashboard') {
         $this->_formValues["contribution_test"] = 0;
     }
     foreach (array('contribution_amount_low', 'contribution_amount_high') as $f) {
         if (isset($this->_formValues[$f])) {
             $this->_formValues[$f] = CRM_Utils_Rule::cleanMoney($this->_formValues[$f]);
         }
     }
     $config = CRM_Core_Config::singleton();
     if (!empty($_POST)) {
         $specialParams = array('financial_type_id', 'contribution_soft_credit_type_id', 'contribution_status_id', 'contribution_source', 'contribution_trxn_id', 'contribution_page_id', 'contribution_product_id');
         foreach ($specialParams as $element) {
             $value = CRM_Utils_Array::value($element, $this->_formValues);
             if ($value) {
                 if (is_array($value)) {
                     $this->_formValues[$element] = array('IN' => $value);
                 } else {
                     $this->_formValues[$element] = array('LIKE' => "%{$value}%");
                 }
             }
         }
         $tags = CRM_Utils_Array::value('contact_tags', $this->_formValues);
         if ($tags && !is_array($tags)) {
             unset($this->_formValues['contact_tags']);
             $this->_formValues['contact_tags'][$tags] = 1;
         }
         if ($tags && is_array($tags)) {
             unset($this->_formValues['contact_tags']);
             foreach ($tags as $notImportant => $tagID) {
                 $this->_formValues['contact_tags'][$tagID] = 1;
             }
         }
         if (!$config->groupTree) {
             $group = CRM_Utils_Array::value('group', $this->_formValues);
             if ($group && !is_array($group)) {
                 unset($this->_formValues['group']);
                 $this->_formValues['group'][$group] = 1;
             }
             if ($group && is_array($group)) {
                 unset($this->_formValues['group']);
                 foreach ($group as $notImportant => $groupID) {
                     $this->_formValues['group'][$groupID] = 1;
                 }
             }
         }
     }
     CRM_Core_BAO_CustomValue::fixFieldValueOfTypeMemo($this->_formValues);
     $this->_queryParams = CRM_Contact_BAO_Query::convertFormValues($this->_formValues);
     $this->set('formValues', $this->_formValues);
     $this->set('queryParams', $this->_queryParams);
     $buttonName = $this->controller->getButtonName();
     if ($buttonName == $this->_actionButtonName) {
         // check actionName and if next, then do not repeat a search, since we are going to the next page
         // hack, make sure we reset the task values
         $stateMachine = $this->controller->getStateMachine();
         $formName = $stateMachine->getTaskFormName();
         $this->controller->resetPage($formName);
         return;
     }
     $sortID = NULL;
     if ($this->get(CRM_Utils_Sort::SORT_ID)) {
         $sortID = CRM_Utils_Sort::sortIDValue($this->get(CRM_Utils_Sort::SORT_ID), $this->get(CRM_Utils_Sort::SORT_DIRECTION));
     }
     $this->_queryParams = CRM_Contact_BAO_Query::convertFormValues($this->_formValues);
     $selector = new CRM_Contribute_Selector_Search($this->_queryParams, $this->_action, NULL, $this->_single, $this->_limit, $this->_context);
     $selector->setKey($this->controller->_key);
     $prefix = NULL;
     if ($this->_context == 'basic' || $this->_context == 'user') {
         $prefix = $this->_prefix;
     }
     $controller = new CRM_Core_Selector_Controller($selector, $this->get(CRM_Utils_Pager::PAGE_ID), $sortID, CRM_Core_Action::VIEW, $this, CRM_Core_Selector_Controller::SESSION, $prefix);
     $controller->setEmbedded(TRUE);
     $query =& $selector->getQuery();
     if ($this->_context == 'user') {
         $query->setSkipPermission(TRUE);
     }
     $summary =& $query->summaryContribution($this->_context);
     $this->set('summary', $summary);
     $this->assign('contributionSummary', $summary);
     $controller->run();
 }
Ejemplo n.º 11
0
 /**
  * Submit function.
  *
  * This is the guts of the postProcess made also accessible to the test suite.
  *
  * @param array $params
  *   Submitted values.
  */
 public function submit($params)
 {
     //carry campaign from profile.
     if (array_key_exists('contribution_campaign_id', $params)) {
         $params['campaign_id'] = $params['contribution_campaign_id'];
     }
     $params['currencyID'] = CRM_Core_Config::singleton()->defaultCurrency;
     $is_quick_config = 0;
     if (!empty($params['priceSetId'])) {
         $is_quick_config = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config');
         if ($is_quick_config) {
             $priceField = new CRM_Price_DAO_PriceField();
             $priceField->price_set_id = $params['priceSetId'];
             $priceField->orderBy('weight');
             $priceField->find();
             $priceOptions = array();
             while ($priceField->fetch()) {
                 CRM_Price_BAO_PriceFieldValue::getValues($priceField->id, $priceOptions);
                 if (($selectedPriceOptionID = CRM_Utils_Array::value("price_{$priceField->id}", $params)) != FALSE && $selectedPriceOptionID > 0) {
                     switch ($priceField->name) {
                         case 'membership_amount':
                             $this->_params['selectMembership'] = $params['selectMembership'] = CRM_Utils_Array::value('membership_type_id', $priceOptions[$selectedPriceOptionID]);
                             $this->set('selectMembership', $params['selectMembership']);
                         case 'contribution_amount':
                             $params['amount'] = $selectedPriceOptionID;
                             if ($priceField->name == 'contribution_amount' || $priceField->name == 'membership_amount' && CRM_Utils_Array::value('is_separate_payment', $this->_membershipBlock) == 0) {
                                 $this->_values['amount'] = CRM_Utils_Array::value('amount', $priceOptions[$selectedPriceOptionID]);
                             }
                             $this->_values[$selectedPriceOptionID]['value'] = CRM_Utils_Array::value('amount', $priceOptions[$selectedPriceOptionID]);
                             $this->_values[$selectedPriceOptionID]['label'] = CRM_Utils_Array::value('label', $priceOptions[$selectedPriceOptionID]);
                             $this->_values[$selectedPriceOptionID]['amount_id'] = CRM_Utils_Array::value('id', $priceOptions[$selectedPriceOptionID]);
                             $this->_values[$selectedPriceOptionID]['weight'] = CRM_Utils_Array::value('weight', $priceOptions[$selectedPriceOptionID]);
                             break;
                         case 'other_amount':
                             $params['amount_other'] = $selectedPriceOptionID;
                             break;
                     }
                 }
             }
         }
     }
     if (!empty($this->_ccid) && !empty($this->_pendingAmount)) {
         $params['amount'] = $this->_pendingAmount;
     } else {
         // from here on down, $params['amount'] holds a monetary value (or null) rather than an option ID
         $params['amount'] = self::computeAmount($params, $this->_values);
     }
     $params['separate_amount'] = $params['amount'];
     $memFee = NULL;
     if (!empty($params['selectMembership'])) {
         if (empty($this->_membershipTypeValues)) {
             $this->_membershipTypeValues = CRM_Member_BAO_Membership::buildMembershipTypeValues($this, (array) $params['selectMembership']);
         }
         $membershipTypeValues = $this->_membershipTypeValues[$params['selectMembership']];
         $memFee = $membershipTypeValues['minimum_fee'];
         if (!$params['amount'] && !$this->_separateMembershipPayment) {
             $params['amount'] = $memFee ? $memFee : 0;
         }
     }
     //If the membership & contribution is used in contribution page & not separate payment
     $fieldId = $memPresent = $membershipLabel = $fieldOption = $is_quick_config = NULL;
     $proceFieldAmount = 0;
     if (property_exists($this, '_separateMembershipPayment') && $this->_separateMembershipPayment == 0) {
         $is_quick_config = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config');
         if ($is_quick_config) {
             foreach ($this->_priceSet['fields'] as $fieldKey => $fieldVal) {
                 if ($fieldVal['name'] == 'membership_amount' && !empty($params['price_' . $fieldKey])) {
                     $fieldId = $fieldVal['id'];
                     $fieldOption = $params['price_' . $fieldId];
                     $proceFieldAmount += $fieldVal['options'][$this->_submitValues['price_' . $fieldId]]['amount'];
                     $memPresent = TRUE;
                 } else {
                     if (!empty($params['price_' . $fieldKey]) && $memPresent && ($fieldVal['name'] == 'other_amount' || $fieldVal['name'] == 'contribution_amount')) {
                         $fieldId = $fieldVal['id'];
                         if ($fieldVal['name'] == 'other_amount') {
                             $proceFieldAmount += $this->_submitValues['price_' . $fieldId];
                         } elseif ($fieldVal['name'] == 'contribution_amount' && $this->_submitValues['price_' . $fieldId] > 0) {
                             $proceFieldAmount += $fieldVal['options'][$this->_submitValues['price_' . $fieldId]]['amount'];
                         }
                         unset($params['price_' . $fieldId]);
                         break;
                     }
                 }
             }
         }
     }
     if (!isset($params['amount_other'])) {
         $this->set('amount_level', CRM_Utils_Array::value('amount_level', $params));
     }
     if (!empty($this->_ccid)) {
         $this->set('lineItem', $this->_lineItem);
     } elseif ($priceSetId = CRM_Utils_Array::value('priceSetId', $params)) {
         $lineItem = array();
         $is_quick_config = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
         if ($is_quick_config) {
             foreach ($this->_values['fee'] as $key => &$val) {
                 if ($val['name'] == 'other_amount' && $val['html_type'] == 'Text' && !empty($params['price_' . $key])) {
                     // Clean out any currency symbols.
                     $params['price_' . $key] = CRM_Utils_Rule::cleanMoney($params['price_' . $key]);
                     if ($params['price_' . $key] != 0) {
                         foreach ($val['options'] as $optionKey => &$options) {
                             $options['amount'] = CRM_Utils_Array::value('price_' . $key, $params);
                             break;
                         }
                     }
                     $params['price_' . $key] = 1;
                     break;
                 }
             }
         }
         $component = '';
         if ($this->_membershipBlock) {
             $component = 'membership';
         }
         CRM_Price_BAO_PriceSet::processAmount($this->_values['fee'], $params, $lineItem[$priceSetId], $component);
         if ($params['tax_amount']) {
             $this->set('tax_amount', $params['tax_amount']);
         }
         if ($proceFieldAmount) {
             $lineItem[$params['priceSetId']][$fieldOption]['unit_price'] = $proceFieldAmount;
             $lineItem[$params['priceSetId']][$fieldOption]['line_total'] = $proceFieldAmount;
             if (isset($lineItem[$params['priceSetId']][$fieldOption]['tax_amount'])) {
                 $proceFieldAmount += $lineItem[$params['priceSetId']][$fieldOption]['tax_amount'];
             }
             if (!$this->_membershipBlock['is_separate_payment']) {
                 //require when separate membership not used
                 $params['amount'] = $proceFieldAmount;
             }
         }
         $this->set('lineItem', $lineItem);
     }
     if ($params['amount'] != 0 && ($this->_values['is_pay_later'] && empty($this->_paymentProcessor) && !array_key_exists('hidden_processor', $params) || CRM_Utils_Array::value('payment_processor_id', $params) == 0)) {
         $params['is_pay_later'] = 1;
     } else {
         $params['is_pay_later'] = 0;
     }
     // Would be nice to someday understand the point of this set.
     $this->set('is_pay_later', $params['is_pay_later']);
     // assign pay later stuff
     $this->_params['is_pay_later'] = CRM_Utils_Array::value('is_pay_later', $params, FALSE);
     $this->assign('is_pay_later', $params['is_pay_later']);
     if ($params['is_pay_later']) {
         $this->assign('pay_later_text', $this->_values['pay_later_text']);
         $this->assign('pay_later_receipt', $this->_values['pay_later_receipt']);
     }
     if ($this->_membershipBlock['is_separate_payment'] && !empty($params['separate_amount'])) {
         $this->set('amount', $params['separate_amount']);
     } else {
         $this->set('amount', $params['amount']);
     }
     // generate and set an invoiceID for this transaction
     $invoiceID = md5(uniqid(rand(), TRUE));
     $this->set('invoiceID', $invoiceID);
     $params['invoiceID'] = $invoiceID;
     $params['description'] = ts('Online Contribution') . ': ' . (!empty($this->_pcpInfo['title']) ? $this->_pcpInfo['title'] : $this->_values['title']);
     $params['button'] = $this->controller->getButtonName();
     // required only if is_monetary and valid positive amount
     // @todo it seems impossible for $memFee to be greater than 0 & $params['amount'] not to
     // be & by requiring $memFee down here we make it harder to do a sensible refactoring of the function
     // above (ie. extract the amount in a small function).
     if ($this->_values['is_monetary'] && !empty($this->_paymentProcessor) && ((double) $params['amount'] > 0.0 || $memFee > 0.0)) {
         // The concept of contributeMode is deprecated - as should be the 'is_monetary' setting.
         $this->setContributeMode();
         // Really this setting of $this->_params & params within it should be done earlier on in the function
         // probably the values determined here should be reused in confirm postProcess as there is no opportunity to alter anything
         // on the confirm page. However as we are dealing with a stable release we go as close to where it is used
         // as possible.
         // In general the form has a lack of clarity of the logic of why things are set on the form in some cases &
         // the logic around when $this->_params is used compared to other params arrays.
         $this->_params = array_merge($params, $this->_params);
         $this->setRecurringMembershipParams();
         if ($this->_paymentProcessor && $this->_paymentProcessor['object']->supports('preApproval')) {
             $this->handlePreApproval($this->_params);
         }
     }
 }
Ejemplo n.º 12
0
 /**
  * Calculate the tax amount based on given tax rate.
  *
  * @param float $amount
  *   Amount of field.
  * @param float $taxRate
  *   Tax rate of selected financial account for field.
  *
  * @return array
  *   array of tax amount
  *
  */
 public static function calculateTaxAmount($amount, $taxRate)
 {
     $taxAmount = array();
     $taxAmount['tax_amount'] = $taxRate / 100 * CRM_Utils_Rule::cleanMoney($amount);
     return $taxAmount;
 }
Ejemplo n.º 13
0
 /**
  * Process the form submission.
  *
  *
  * @return void
  */
 public function postProcess()
 {
     if ($this->_action & CRM_Core_Action::DELETE) {
         try {
             CRM_Member_BAO_MembershipType::del($this->_id);
         } catch (CRM_Core_Exception $e) {
             CRM_Core_Error::statusBounce($e->getMessage(), NULL, ts('Membership Type Not Deleted'));
         }
         CRM_Core_Session::setStatus(ts('Selected membership type has been deleted.'), ts('Record Deleted'), 'success');
     } else {
         $buttonName = $this->controller->getButtonName();
         $submitted = $this->controller->exportValues($this->_name);
         $fields = array('name', 'weight', 'is_active', 'member_of_contact_id', 'visibility', 'period_type', 'minimum_fee', 'description', 'auto_renew', 'duration_unit', 'duration_interval', 'financial_type_id', 'fixed_period_start_day', 'fixed_period_rollover_day', 'month_fixed_period_rollover_day', 'max_related');
         $params = $ids = array();
         foreach ($fields as $fld) {
             $params[$fld] = CRM_Utils_Array::value($fld, $submitted, 'NULL');
         }
         //clean money.
         if ($params['minimum_fee']) {
             $params['minimum_fee'] = CRM_Utils_Rule::cleanMoney($params['minimum_fee']);
         }
         $hasRelTypeVal = FALSE;
         if (!CRM_Utils_System::isNull($submitted['relationship_type_id'])) {
             // To insert relation ids and directions with value separator
             $relTypeDirs = $submitted['relationship_type_id'];
             $relIds = $relDirection = array();
             foreach ($relTypeDirs as $key => $value) {
                 $relationId = explode('_', $value);
                 if (count($relationId) == 3 && is_numeric($relationId[0])) {
                     $relIds[] = $relationId[0];
                     $relDirection[] = $relationId[1] . '_' . $relationId[2];
                 }
             }
             if (!empty($relIds)) {
                 $hasRelTypeVal = TRUE;
                 $params['relationship_type_id'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, $relIds);
                 $params['relationship_direction'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, $relDirection);
             }
         }
         if (!$hasRelTypeVal) {
             $params['relationship_type_id'] = $params['relationship_direction'] = $params['max_related'] = 'NULL';
         }
         if ($params['duration_unit'] == 'lifetime' && empty($params['duration_interval'])) {
             $params['duration_interval'] = 1;
         }
         $periods = array('fixed_period_start_day', 'fixed_period_rollover_day');
         foreach ($periods as $per) {
             if (!empty($params[$per]['M']) && !empty($params[$per]['d'])) {
                 $mon = $params[$per]['M'];
                 $dat = $params[$per]['d'];
                 $mon = $mon < 10 ? '0' . $mon : $mon;
                 $dat = $dat < 10 ? '0' . $dat : $dat;
                 $params[$per] = $mon . $dat;
             } elseif ($per == 'fixed_period_rollover_day' && !empty($params['month_fixed_period_rollover_day'])) {
                 $params['fixed_period_rollover_day'] = $params['month_fixed_period_rollover_day']['d'];
                 unset($params['month_fixed_period_rollover_day']);
             } else {
                 $params[$per] = 'NULL';
             }
         }
         $oldWeight = NULL;
         if ($this->_id) {
             $oldWeight = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $this->_id, 'weight', 'id');
         }
         $params['weight'] = CRM_Utils_Weight::updateOtherWeights('CRM_Member_DAO_MembershipType', $oldWeight, $params['weight']);
         if ($this->_action & CRM_Core_Action::UPDATE) {
             $ids['membershipType'] = $this->_id;
         }
         $membershipType = CRM_Member_BAO_MembershipType::add($params, $ids);
         CRM_Core_Session::setStatus(ts('The membership type \'%1\' has been saved.', array(1 => $membershipType->name)), ts('Saved'), 'success');
         $session = CRM_Core_Session::singleton();
         if ($buttonName == $this->getButtonName('upload', 'new')) {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/admin/member/membershipType/add', 'action=add&reset=1'));
         }
     }
 }
Ejemplo n.º 14
0
 /**
  * Process the form submission.
  */
 public function postProcess()
 {
     $sendReceipt = $pId = $contribution = $isRelatedId = FALSE;
     $softParams = $softIDs = array();
     if ($this->_action & CRM_Core_Action::DELETE) {
         CRM_Contribute_BAO_Contribution::deleteContribution($this->_id);
         CRM_Core_Session::singleton()->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$this->_contactID}&selectedChild=contribute"));
         return;
     }
     // Get the submitted form values.
     $submittedValues = $this->controller->exportValues($this->_name);
     if (!empty($submittedValues['price_set_id']) && $this->_action & CRM_Core_Action::UPDATE) {
         $line = CRM_Price_BAO_LineItem::getLineItems($this->_id, 'contribution');
         $lineID = key($line);
         $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', CRM_Utils_Array::value('price_field_id', $line[$lineID]), 'price_set_id');
         $quickConfig = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
         if ($quickConfig) {
             CRM_Price_BAO_LineItem::deleteLineItems($this->_id, 'civicrm_contribution');
         }
     }
     // Process price set and get total amount and line items.
     $lineItem = array();
     $priceSetId = CRM_Utils_Array::value('price_set_id', $submittedValues);
     if (empty($priceSetId) && !$this->_id) {
         $this->_priceSetId = $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', 'default_contribution_amount', 'id', 'name');
         $this->_priceSet = current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId));
         $fieldID = key($this->_priceSet['fields']);
         $fieldValueId = key($this->_priceSet['fields'][$fieldID]['options']);
         $this->_priceSet['fields'][$fieldID]['options'][$fieldValueId]['amount'] = $submittedValues['total_amount'];
         $submittedValues['price_' . $fieldID] = 1;
     }
     if ($priceSetId) {
         CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'], $submittedValues, $lineItem[$priceSetId]);
         // Unset tax amount for offline 'is_quick_config' contribution.
         if ($this->_priceSet['is_quick_config'] && !array_key_exists($submittedValues['financial_type_id'], CRM_Core_PseudoConstant::getTaxRates())) {
             unset($submittedValues['tax_amount']);
         }
         $submittedValues['total_amount'] = CRM_Utils_Array::value('amount', $submittedValues);
     }
     if ($this->_id) {
         if ($this->_compId) {
             if ($this->_context == 'participant') {
                 $pId = $this->_compId;
             } elseif ($this->_context == 'membership') {
                 $isRelatedId = TRUE;
             } else {
                 $pId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id, 'participant_id', 'contribution_id');
             }
         } else {
             $contributionDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
             if (array_key_exists('membership', $contributionDetails)) {
                 $isRelatedId = TRUE;
             } elseif (array_key_exists('participant', $contributionDetails)) {
                 $pId = $contributionDetails['participant'];
             }
         }
     }
     if (!$priceSetId && !empty($submittedValues['total_amount']) && $this->_id) {
         // CRM-10117 update the line items for participants.
         if ($pId) {
             $entityTable = 'participant';
             $entityID = $pId;
             $isRelatedId = FALSE;
             $participantParams = array('fee_amount' => $submittedValues['total_amount'], 'id' => $entityID);
             CRM_Event_BAO_Participant::add($participantParams);
             if (empty($this->_lineItems)) {
                 $this->_lineItems[] = CRM_Price_BAO_LineItem::getLineItems($entityID, 'participant', 1);
             }
         } else {
             $entityTable = 'contribution';
             $entityID = $this->_id;
         }
         $lineItems = CRM_Price_BAO_LineItem::getLineItems($entityID, $entityTable, NULL, TRUE, $isRelatedId);
         foreach (array_keys($lineItems) as $id) {
             $lineItems[$id]['id'] = $id;
         }
         $itemId = key($lineItems);
         if ($itemId && !empty($lineItems[$itemId]['price_field_id'])) {
             $this->_priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id');
         }
         if ($this->_priceSetId && CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) {
             $lineItems[$itemId]['unit_price'] = $lineItems[$itemId]['line_total'] = CRM_Utils_Rule::cleanMoney(CRM_Utils_Array::value('total_amount', $submittedValues));
             // Update line total and total amount with tax on edit.
             $financialItemsId = CRM_Core_PseudoConstant::getTaxRates();
             if (array_key_exists($submittedValues['financial_type_id'], $financialItemsId)) {
                 $lineItems[$itemId]['tax_rate'] = $financialItemsId[$submittedValues['financial_type_id']];
             } else {
                 $lineItems[$itemId]['tax_rate'] = $lineItems[$itemId]['tax_amount'] = "";
                 $submittedValues['tax_amount'] = 'null';
             }
             if ($lineItems[$itemId]['tax_rate']) {
                 $lineItems[$itemId]['tax_amount'] = $lineItems[$itemId]['tax_rate'] / 100 * $lineItems[$itemId]['line_total'];
                 $submittedValues['total_amount'] = $lineItems[$itemId]['line_total'] + $lineItems[$itemId]['tax_amount'];
                 $submittedValues['tax_amount'] = $lineItems[$itemId]['tax_amount'];
             }
         }
         // CRM-10117 update the line items for participants.
         if (!empty($lineItems[$itemId]['price_field_id'])) {
             $lineItem[$this->_priceSetId] = $lineItems;
         }
     }
     $isQuickConfig = 0;
     if ($this->_priceSetId && CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) {
         $isQuickConfig = 1;
     }
     //CRM-11529 for quick config back office transactions
     //when financial_type_id is passed in form, update the
     //line items with the financial type selected in form
     if ($isQuickConfig && !empty($submittedValues['financial_type_id']) && CRM_Utils_Array::value($this->_priceSetId, $lineItem)) {
         foreach ($lineItem[$this->_priceSetId] as &$values) {
             $values['financial_type_id'] = $submittedValues['financial_type_id'];
         }
     }
     if (!isset($submittedValues['total_amount'])) {
         $submittedValues['total_amount'] = CRM_Utils_Array::value('total_amount', $this->_values);
     }
     $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ? $lineItem : FALSE);
     if (!empty($submittedValues['pcp_made_through_id'])) {
         $pcp = array();
         $fields = array('pcp_made_through_id', 'pcp_display_in_roll', 'pcp_roll_nickname', 'pcp_personal_note');
         foreach ($fields as $f) {
             $pcp[$f] = CRM_Utils_Array::value($f, $submittedValues);
         }
     }
     $isEmpty = array_keys(array_flip($submittedValues['soft_credit_contact_id']));
     if ($this->_id && count($isEmpty) == 1 && key($isEmpty) == NULL) {
         //Delete existing soft credit records if soft credit list is empty on update
         CRM_Contribute_BAO_ContributionSoft::del(array('contribution_id' => $this->_id));
     } else {
         //build soft credit params
         foreach ($submittedValues['soft_credit_contact_id'] as $key => $val) {
             if ($val && $submittedValues['soft_credit_amount'][$key]) {
                 $softParams[$key]['contact_id'] = $val;
                 $softParams[$key]['amount'] = CRM_Utils_Rule::cleanMoney($submittedValues['soft_credit_amount'][$key]);
                 $softParams[$key]['soft_credit_type_id'] = $submittedValues['soft_credit_type'][$key];
                 if (!empty($submittedValues['soft_credit_id'][$key])) {
                     $softIDs[] = $softParams[$key]['id'] = $submittedValues['soft_credit_id'][$key];
                 }
             }
         }
     }
     // set the contact, when contact is selected
     if (!empty($submittedValues['contact_id'])) {
         $this->_contactID = $submittedValues['contact_id'];
     }
     // Credit Card Contribution.
     if ($this->_mode) {
         $this->processCreditCard($submittedValues, $lineItem);
     } else {
         // Offline Contribution.
         $submittedValues = $this->unsetCreditCardFields($submittedValues);
         // get the required field value only.
         $formValues = $submittedValues;
         $params = $ids = array();
         $params['contact_id'] = $this->_contactID;
         $params['currency'] = $this->getCurrency($submittedValues);
         $fields = array('financial_type_id', 'contribution_status_id', 'payment_instrument_id', 'cancel_reason', 'source', 'check_number');
         foreach ($fields as $f) {
             $params[$f] = CRM_Utils_Array::value($f, $formValues);
         }
         if (!empty($pcp)) {
             $params['pcp'] = $pcp;
         }
         if (!empty($softParams)) {
             $params['soft_credit'] = $softParams;
             $params['soft_credit_ids'] = $softIDs;
         }
         // CRM-5740 if priceset is used, no need to cleanup money.
         if ($priceSetId) {
             $params['skipCleanMoney'] = 1;
         }
         $dates = array('receive_date', 'receipt_date', 'cancel_date');
         foreach ($dates as $d) {
             $params[$d] = CRM_Utils_Date::processDate($formValues[$d], $formValues[$d . '_time'], TRUE);
         }
         if (!empty($formValues['is_email_receipt'])) {
             $params['receipt_date'] = date("Y-m-d");
         }
         if ($params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Cancelled', 'name') || $params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Refunded', 'name')) {
             if (CRM_Utils_System::isNull(CRM_Utils_Array::value('cancel_date', $params))) {
                 $params['cancel_date'] = date('Y-m-d');
             }
         } else {
             $params['cancel_date'] = $params['cancel_reason'] = 'null';
         }
         // Set is_pay_later flag for back-office offline Pending status contributions CRM-8996
         // else if contribution_status is changed to Completed is_pay_later flag is changed to 0, CRM-15041
         if ($params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Pending', 'name')) {
             $params['is_pay_later'] = 1;
         } elseif ($params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name')) {
             $params['is_pay_later'] = 0;
         }
         $ids['contribution'] = $params['id'] = $this->_id;
         // Add Additional common information to formatted params.
         CRM_Contribute_Form_AdditionalInfo::postProcessCommon($formValues, $params, $this);
         if ($pId) {
             $params['contribution_mode'] = 'participant';
             $params['participant_id'] = $pId;
             $params['skipLineItem'] = 1;
         } elseif ($isRelatedId) {
             $params['contribution_mode'] = 'membership';
         }
         $params['line_item'] = $lineItem;
         $params['payment_processor_id'] = $params['payment_processor'] = CRM_Utils_Array::value('id', $this->_paymentProcessor);
         if (isset($submittedValues['tax_amount'])) {
             $params['tax_amount'] = $submittedValues['tax_amount'];
         }
         //create contribution.
         if ($isQuickConfig) {
             $params['is_quick_config'] = 1;
         }
         // CRM-11956
         // if non_deductible_amount exists i.e. Additional Details field set was opened [and staff typed something] -
         // if non_deductible_amount does NOT exist - then calculate it depending on:
         // $ContributionType->is_deductible and whether there is a product (premium).
         if (empty($params['non_deductible_amount'])) {
             $contributionType = new CRM_Financial_DAO_FinancialType();
             $contributionType->id = $params['financial_type_id'];
             if (!$contributionType->find(TRUE)) {
                 CRM_Core_Error::fatal('Could not find a system table');
             }
             if ($contributionType->is_deductible) {
                 if (isset($formValues['product_name'][0])) {
                     $selectProduct = $formValues['product_name'][0];
                 }
                 // if there is a product - compare the value to the contribution amount
                 if (isset($selectProduct)) {
                     $productDAO = new CRM_Contribute_DAO_Product();
                     $productDAO->id = $selectProduct;
                     $productDAO->find(TRUE);
                     // product value exceeds contribution amount
                     if ($params['total_amount'] < $productDAO->price) {
                         $params['non_deductible_amount'] = $params['total_amount'];
                     } else {
                         $params['non_deductible_amount'] = $productDAO->price;
                     }
                 } else {
                     $params['non_deductible_amount'] = '0.00';
                 }
             } else {
                 $params['non_deductible_amount'] = $params['total_amount'];
             }
         }
         $contribution = CRM_Contribute_BAO_Contribution::create($params, $ids);
         // process associated membership / participant, CRM-4395
         $relatedComponentStatusMsg = NULL;
         if ($contribution->id && $this->_action & CRM_Core_Action::UPDATE) {
             $relatedComponentStatusMsg = $this->updateRelatedComponent($contribution->id, $contribution->contribution_status_id, CRM_Utils_Array::value('contribution_status_id', $this->_values), $contribution->receive_date);
         }
         //process  note
         if ($contribution->id && isset($formValues['note'])) {
             CRM_Contribute_Form_AdditionalInfo::processNote($formValues, $this->_contactID, $contribution->id, $this->_noteID);
         }
         //process premium
         if ($contribution->id && isset($formValues['product_name'][0])) {
             CRM_Contribute_Form_AdditionalInfo::processPremium($formValues, $contribution->id, $this->_premiumID, $this->_options);
         }
         // assign tax calculation for contribution receipts
         $taxRate = array();
         $getTaxDetails = FALSE;
         $invoiceSettings = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings');
         $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
         if ($invoicing) {
             if ($this->_action & CRM_Core_Action::ADD) {
                 $line = $lineItem;
             } elseif ($this->_action & CRM_Core_Action::UPDATE) {
                 $line = $this->_lineItems;
             }
             foreach ($line as $key => $value) {
                 foreach ($value as $v) {
                     if (isset($taxRate[(string) CRM_Utils_Array::value('tax_rate', $v)])) {
                         $taxRate[(string) $v['tax_rate']] = $taxRate[(string) $v['tax_rate']] + CRM_Utils_Array::value('tax_amount', $v);
                     } else {
                         if (isset($v['tax_rate'])) {
                             $taxRate[(string) $v['tax_rate']] = CRM_Utils_Array::value('tax_amount', $v);
                             $getTaxDetails = TRUE;
                         }
                     }
                 }
             }
         }
         if ($invoicing) {
             if ($this->_action & CRM_Core_Action::UPDATE) {
                 if (isset($submittedValues['tax_amount'])) {
                     $totalTaxAmount = $submittedValues['tax_amount'];
                 } else {
                     $totalTaxAmount = $this->_values['tax_amount'];
                 }
                 $this->assign('totalTaxAmount', $totalTaxAmount);
                 $this->assign('dataArray', $taxRate);
             } else {
                 if (!empty($submittedValues['price_set_id'])) {
                     $this->assign('totalTaxAmount', $submittedValues['tax_amount']);
                     $this->assign('getTaxDetails', $getTaxDetails);
                     $this->assign('dataArray', $taxRate);
                     $this->assign('taxTerm', CRM_Utils_Array::value('tax_term', $invoiceSettings));
                 } else {
                     $this->assign('totalTaxAmount', CRM_Utils_Array::value('tax_amount', $submittedValues));
                 }
             }
         }
         //send receipt mail.
         if ($contribution->id && !empty($formValues['is_email_receipt'])) {
             $formValues['contact_id'] = $this->_contactID;
             $formValues['contribution_id'] = $contribution->id;
             $formValues += CRM_Contribute_BAO_ContributionSoft::getSoftContribution($contribution->id);
             // to get 'from email id' for send receipt
             $this->fromEmailId = $formValues['from_email_address'];
             $sendReceipt = CRM_Contribute_Form_AdditionalInfo::emailReceipt($this, $formValues);
         }
         $pledgePaymentId = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', $contribution->id, 'id', 'contribution_id');
         //update pledge payment status.
         if ($this->_ppID && $contribution->id && $this->_action & CRM_Core_Action::ADD || $pledgePaymentId && $this->_action & CRM_Core_Action::UPDATE) {
             if ($this->_ppID) {
                 //store contribution id in payment record.
                 CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment', $this->_ppID, 'contribution_id', $contribution->id);
             } else {
                 $this->_ppID = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', $contribution->id, 'id', 'contribution_id');
                 $this->_pledgeID = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', $contribution->id, 'pledge_id', 'contribution_id');
             }
             $adjustTotalAmount = FALSE;
             if (CRM_Utils_Array::value('option_type', $formValues) == 2) {
                 $adjustTotalAmount = TRUE;
             }
             $updatePledgePaymentStatus = FALSE;
             //do only if either the status or the amount has changed
             if ($this->_action & CRM_Core_Action::ADD) {
                 $updatePledgePaymentStatus = TRUE;
             } elseif ($this->_action & CRM_Core_Action::UPDATE && ($this->_defaults['contribution_status_id'] != $formValues['contribution_status_id'] || $this->_defaults['total_amount'] != $formValues['total_amount'])) {
                 $updatePledgePaymentStatus = TRUE;
             }
             if ($updatePledgePaymentStatus) {
                 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($this->_pledgeID, array($this->_ppID), $contribution->contribution_status_id, NULL, $contribution->total_amount, $adjustTotalAmount);
             }
         }
         $statusMsg = ts('The contribution record has been saved.');
         if (!empty($formValues['is_email_receipt']) && $sendReceipt) {
             $statusMsg .= ' ' . ts('A receipt has been emailed to the contributor.');
         }
         if ($relatedComponentStatusMsg) {
             $statusMsg .= ' ' . $relatedComponentStatusMsg;
         }
         CRM_Core_Session::setStatus($statusMsg, ts('Saved'), 'success');
         //Offline Contribution ends.
     }
     $session = CRM_Core_Session::singleton();
     $buttonName = $this->controller->getButtonName();
     if ($this->_context == 'standalone') {
         if ($buttonName == $this->getButtonName('upload', 'new')) {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/contribute/add', 'reset=1&action=add&context=standalone'));
         } else {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$this->_contactID}&selectedChild=contribute"));
         }
     } elseif ($this->_context == 'contribution' && $this->_mode && $buttonName == $this->getButtonName('upload', 'new')) {
         $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/contribution', "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}&mode={$this->_mode}"));
     } elseif ($buttonName == $this->getButtonName('upload', 'new')) {
         $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/contribution', "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}"));
     }
     //store contribution ID if not yet set (on create)
     if (empty($this->_id) && !empty($contribution->id)) {
         $this->_id = $contribution->id;
     }
 }
/**
 * Calculate either a monetary or percentage discount.
 */
function _cividiscount_calc_discount($amount, $label, $discount, $autodiscount, $currency = 'USD')
{
    $title = $autodiscount ? 'Member Discount' : "Discount {$discount['code']}";
    if ($discount['amount_type'] == '2') {
        $newamount = CRM_Utils_Rule::cleanMoney($amount) - CRM_Utils_Rule::cleanMoney($discount['amount']);
        $fmt_discount = CRM_Utils_Money::format($discount['amount'], $currency);
        $newlabel = $label . " ({$title}: {$fmt_discount} {$discount['description']})";
    } else {
        $newamount = $amount - $amount * ($discount['amount'] / 100);
        $newlabel = $label . " ({$title}: {$discount['amount']}% {$discount['description']})";
    }
    $newamount = round($newamount, 2);
    // Return a formatted string for zero amount.
    // @see http://issues.civicrm.org/jira/browse/CRM-12278
    if ($newamount <= 0) {
        $newamount = '0.00';
    }
    return array($newamount, $newlabel);
}
Ejemplo n.º 16
0
 /**
  * Process the form submission.
  */
 public function postProcess()
 {
     if ($this->_action & CRM_Core_Action::DELETE) {
         CRM_Pledge_BAO_Pledge::deletePledge($this->_id);
         return;
     }
     // get the submitted form values.
     $formValues = $this->controller->exportValues($this->_name);
     // set the contact, when contact is selected
     if (!empty($formValues['contact_id'])) {
         $this->_contactID = $formValues['contact_id'];
     }
     $session = CRM_Core_Session::singleton();
     // get All Payments status types.
     $paymentStatusTypes = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
     $fields = array('frequency_unit', 'frequency_interval', 'frequency_day', 'installments', 'financial_type_id', 'initial_reminder_day', 'max_reminders', 'additional_reminder_day', 'contribution_page_id', 'campaign_id');
     foreach ($fields as $f) {
         $params[$f] = CRM_Utils_Array::value($f, $formValues);
     }
     // defaults status is "Pending".
     // if update get status.
     if ($this->_id) {
         $params['pledge_status_id'] = $params['status_id'] = $this->_values['status_id'];
     } else {
         $params['pledge_status_id'] = $params['status_id'] = array_search('Pending', $paymentStatusTypes);
     }
     // format amount
     $params['amount'] = CRM_Utils_Rule::cleanMoney(CRM_Utils_Array::value('amount', $formValues));
     $params['currency'] = CRM_Utils_Array::value('currency', $formValues);
     $params['original_installment_amount'] = $params['amount'] / $params['installments'];
     $dates = array('create_date', 'start_date', 'acknowledge_date', 'cancel_date');
     foreach ($dates as $d) {
         if ($this->_id && !$this->_isPending && !empty($this->_values[$d])) {
             if ($d == 'start_date') {
                 $params['scheduled_date'] = CRM_Utils_Date::processDate($this->_values[$d]);
             }
             $params[$d] = CRM_Utils_Date::processDate($this->_values[$d]);
         } elseif (!empty($formValues[$d]) && !CRM_Utils_System::isNull($formValues[$d])) {
             if ($d == 'start_date') {
                 $params['scheduled_date'] = CRM_Utils_Date::processDate($formValues[$d]);
             }
             $params[$d] = CRM_Utils_Date::processDate($formValues[$d]);
         } else {
             $params[$d] = 'null';
         }
     }
     if (!empty($formValues['is_acknowledge'])) {
         $params['acknowledge_date'] = date('Y-m-d');
     }
     // assign id only in update mode
     if ($this->_action & CRM_Core_Action::UPDATE) {
         $params['id'] = $this->_id;
     }
     $params['contact_id'] = $this->_contactID;
     // format custom data
     if (!empty($formValues['hidden_custom'])) {
         $params['hidden_custom'] = 1;
         $customFields = CRM_Core_BAO_CustomField::getFields('Pledge');
         $params['custom'] = CRM_Core_BAO_CustomField::postProcess($formValues, $this->_id, 'Pledge');
     }
     // handle pending pledge.
     $params['is_pledge_pending'] = $this->_isPending;
     // create pledge record.
     $pledge = CRM_Pledge_BAO_Pledge::create($params);
     $statusMsg = NULL;
     if ($pledge->id) {
         // set the status msg.
         if ($this->_action & CRM_Core_Action::ADD) {
             $statusMsg = ts('Pledge has been recorded and the payment schedule has been created.<br />');
         } elseif ($this->_action & CRM_Core_Action::UPDATE) {
             $statusMsg = ts('Pledge has been updated.<br />');
         }
     }
     // handle Acknowledgment.
     if (!empty($formValues['is_acknowledge']) && $pledge->id) {
         // calculate scheduled amount.
         $params['scheduled_amount'] = round($params['amount'] / $params['installments']);
         $params['total_pledge_amount'] = $params['amount'];
         // get some required pledge values in params.
         $params['id'] = $pledge->id;
         $params['acknowledge_date'] = $pledge->acknowledge_date;
         $params['is_test'] = $pledge->is_test;
         $params['currency'] = $pledge->currency;
         // retrieve 'from email id' for acknowledgement
         $params['from_email_id'] = $formValues['from_email_address'];
         $this->paymentId = NULL;
         // send Acknowledgment mail.
         CRM_Pledge_BAO_Pledge::sendAcknowledgment($this, $params);
         if (!isset($this->userEmail)) {
             list($this->userDisplayName, $this->userEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactID);
         }
         $statusMsg .= ' ' . ts("An acknowledgment email has been sent to %1.<br />", array(1 => $this->userEmail));
         // build the payment urls.
         if ($this->paymentId) {
             $urlParams = "reset=1&action=add&cid={$this->_contactID}&ppid={$this->paymentId}&context=pledge";
             $contribURL = CRM_Utils_System::url('civicrm/contact/view/contribution', $urlParams);
             $urlParams .= "&mode=live";
             $creditURL = CRM_Utils_System::url('civicrm/contact/view/contribution', $urlParams);
             // check if we can process credit card payment.
             $processors = CRM_Core_PseudoConstant::paymentProcessor(FALSE, FALSE, "billing_mode IN ( 1, 3 )");
             if (count($processors) > 0) {
                 $statusMsg .= ' ' . ts("If a payment is due now, you can record <a href='%1'>a check, EFT, or cash payment for this pledge</a> OR <a href='%2'>submit a credit card payment</a>.", array(1 => $contribURL, 2 => $creditURL));
             } else {
                 $statusMsg .= ' ' . ts("If a payment is due now, you can record <a href='%1'>a check, EFT, or cash payment for this pledge</a>.", array(1 => $contribURL));
             }
         }
     }
     CRM_Core_Session::setStatus($statusMsg, ts('Payment Due'), 'info');
     $buttonName = $this->controller->getButtonName();
     if ($this->_context == 'standalone') {
         if ($buttonName == $this->getButtonName('upload', 'new')) {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/pledge/add', 'reset=1&action=add&context=standalone'));
         } else {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$this->_contactID}&selectedChild=pledge"));
         }
     } elseif ($buttonName == $this->getButtonName('upload', 'new')) {
         $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/pledge', "reset=1&action=add&context=pledge&cid={$this->_contactID}"));
     }
 }
Ejemplo n.º 17
0
 /**
  * Takes an associative array and creates a contribution object.
  *
  * the function extract all the params it needs to initialize the create a
  * contribution object. the params array could contain additional unused name/value
  * pairs
  *
  * @param array $params
  *   (reference ) an assoc array of name/value pairs.
  * @param array $ids
  *   The array that holds all the db ids.
  *
  * @return CRM_Contribute_BAO_Contribution|void
  */
 public static function add(&$params, $ids = array())
 {
     if (empty($params)) {
         return NULL;
     }
     //per http://wiki.civicrm.org/confluence/display/CRM/Database+layer we are moving away from $ids array
     $contributionID = CRM_Utils_Array::value('contribution', $ids, CRM_Utils_Array::value('id', $params));
     $duplicates = array();
     if (self::checkDuplicate($params, $duplicates, $contributionID)) {
         $error = CRM_Core_Error::singleton();
         $d = implode(', ', $duplicates);
         $error->push(CRM_Core_Error::DUPLICATE_CONTRIBUTION, 'Fatal', array($d), "Duplicate error - existing contribution record(s) have a matching Transaction ID or Invoice ID. Contribution record ID(s) are: {$d}");
         return $error;
     }
     // first clean up all the money fields
     $moneyFields = array('total_amount', 'net_amount', 'fee_amount', 'non_deductible_amount');
     //if priceset is used, no need to cleanup money
     if (!empty($params['skipCleanMoney'])) {
         unset($moneyFields[0]);
     }
     foreach ($moneyFields as $field) {
         if (isset($params[$field])) {
             $params[$field] = CRM_Utils_Rule::cleanMoney($params[$field]);
         }
     }
     //set defaults in create mode
     if (!$contributionID) {
         CRM_Core_DAO::setCreateDefaults($params, self::getDefaults());
     }
     self::calculateMissingAmountParams($params, $contributionID);
     if (!empty($params['payment_instrument_id'])) {
         $paymentInstruments = CRM_Contribute_PseudoConstant::paymentInstrument('name');
         if ($params['payment_instrument_id'] != array_search('Check', $paymentInstruments)) {
             $params['check_number'] = 'null';
         }
     }
     $setPrevContribution = TRUE;
     // CRM-13964 partial payment
     if (!empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])) {
         $partialAmtTotal = $params['partial_payment_total'];
         $partialAmtPay = $params['partial_amount_pay'];
         $params['total_amount'] = $partialAmtTotal;
         if ($partialAmtPay < $partialAmtTotal) {
             $params['contribution_status_id'] = CRM_Core_OptionGroup::getValue('contribution_status', 'Partially paid', 'name');
             $params['is_pay_later'] = 0;
             $setPrevContribution = FALSE;
         }
     }
     if ($contributionID) {
         CRM_Utils_Hook::pre('edit', 'Contribution', $contributionID, $params);
     } else {
         CRM_Utils_Hook::pre('create', 'Contribution', NULL, $params);
     }
     $contribution = new CRM_Contribute_BAO_Contribution();
     $contribution->copyValues($params);
     $contribution->id = $contributionID;
     if (empty($contribution->id)) {
         // (only) on 'create', make sure that a valid currency is set (CRM-16845)
         if (!CRM_Utils_Rule::currencyCode($contribution->currency)) {
             $config = CRM_Core_Config::singleton();
             $contribution->currency = $config->defaultCurrency;
         }
     }
     if ($contributionID && $setPrevContribution) {
         $params['prevContribution'] = self::getValues(array('id' => $contributionID), CRM_Core_DAO::$_nullArray, CRM_Core_DAO::$_nullArray);
     }
     $result = $contribution->save();
     // Add financial_trxn details as part of fix for CRM-4724
     $contribution->trxn_result_code = CRM_Utils_Array::value('trxn_result_code', $params);
     $contribution->payment_processor = CRM_Utils_Array::value('payment_processor', $params);
     //add Account details
     $params['contribution'] = $contribution;
     self::recordFinancialAccounts($params);
     // reset the group contact cache for this group
     CRM_Contact_BAO_GroupContactCache::remove();
     if ($contributionID) {
         CRM_Utils_Hook::post('edit', 'Contribution', $contribution->id, $contribution);
     } else {
         CRM_Utils_Hook::post('create', 'Contribution', $contribution->id, $contribution);
     }
     return $result;
 }
Ejemplo n.º 18
0
 /**
  * This method will create the lineItem array required for
  * processAmount method
  *
  * @param int $fid
  *   Price set field id.
  * @param array $params
  *   Reference to form values.
  * @param array $fields
  *   Reference to array of fields belonging.
  *                          to the price set used for particular event
  * @param array $values
  *   Reference to the values array(.
  *   this is
  *                          lineItem array)
  *
  * @return void
  */
 public static function format($fid, &$params, &$fields, &$values)
 {
     if (empty($params["price_{$fid}"])) {
         return;
     }
     $optionIDs = implode(',', array_keys($params["price_{$fid}"]));
     //lets first check in fun parameter,
     //since user might modified w/ hooks.
     $options = array();
     if (array_key_exists('options', $fields)) {
         $options = $fields['options'];
     } else {
         CRM_Price_BAO_PriceFieldValue::getValues($fid, $options, 'weight', TRUE);
     }
     $fieldTitle = CRM_Utils_Array::value('label', $fields);
     if (!$fieldTitle) {
         $fieldTitle = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $fid, 'label');
     }
     foreach ($params["price_{$fid}"] as $oid => $qty) {
         $price = $options[$oid]['amount'];
         // lets clean the price in case it is not yet cleant
         // CRM-10974
         $price = CRM_Utils_Rule::cleanMoney($price);
         $participantsPerField = CRM_Utils_Array::value('count', $options[$oid], 0);
         $values[$oid] = array('price_field_id' => $fid, 'price_field_value_id' => $oid, 'label' => CRM_Utils_Array::value('label', $options[$oid]), 'field_title' => $fieldTitle, 'description' => CRM_Utils_Array::value('description', $options[$oid]), 'qty' => $qty, 'unit_price' => $price, 'line_total' => $qty * $price, 'participant_count' => $qty * $participantsPerField, 'max_value' => CRM_Utils_Array::value('max_value', $options[$oid]), 'membership_type_id' => CRM_Utils_Array::value('membership_type_id', $options[$oid]), 'membership_num_terms' => CRM_Utils_Array::value('membership_num_terms', $options[$oid]), 'auto_renew' => CRM_Utils_Array::value('auto_renew', $options[$oid]), 'html_type' => $fields['html_type'], 'financial_type_id' => CRM_Utils_Array::value('financial_type_id', $options[$oid]), 'tax_amount' => CRM_Utils_Array::value('tax_amount', $options[$oid]));
         if ($values[$oid]['membership_type_id'] && empty($values[$oid]['auto_renew'])) {
             $values[$oid]['auto_renew'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $values[$oid]['membership_type_id'], 'auto_renew');
         }
     }
 }
Ejemplo n.º 19
0
 /**
  * @param array $submittedValues
  *
  * @param int $action
  *   Action constant
  *    - CRM_Core_Action::UPDATE
  *
  * @param $pledgePaymentID
  *
  * @return array
  * @throws \Exception
  */
 protected function submit($submittedValues, $action, $pledgePaymentID)
 {
     $softParams = $softIDs = array();
     $pId = $contribution = $isRelatedId = FALSE;
     $this->_params = $submittedValues;
     $this->beginPostProcess();
     if (!empty($submittedValues['price_set_id']) && $action & CRM_Core_Action::UPDATE) {
         $line = CRM_Price_BAO_LineItem::getLineItems($this->_id, 'contribution');
         $lineID = key($line);
         $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', CRM_Utils_Array::value('price_field_id', $line[$lineID]), 'price_set_id');
         $quickConfig = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
         // Why do we do this? Seems like a like a wrapper for old functionality - but single line price sets & quick
         // config should be treated the same.
         if ($quickConfig) {
             CRM_Price_BAO_LineItem::deleteLineItems($this->_id, 'civicrm_contribution');
         }
     }
     // Process price set and get total amount and line items.
     $lineItem = array();
     $priceSetId = CRM_Utils_Array::value('price_set_id', $submittedValues);
     if (empty($priceSetId) && !$this->_id) {
         $this->_priceSetId = $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', 'default_contribution_amount', 'id', 'name');
         $this->_priceSet = current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId));
         $fieldID = key($this->_priceSet['fields']);
         $fieldValueId = key($this->_priceSet['fields'][$fieldID]['options']);
         $this->_priceSet['fields'][$fieldID]['options'][$fieldValueId]['amount'] = $submittedValues['total_amount'];
         $submittedValues['price_' . $fieldID] = 1;
     }
     // Every contribution has a price-set - the only reason it shouldn't be set is if we are dealing with
     // quick config (very very arguably) & yet we see that this could still be quick config so this should be understood
     // as a point of fragility rather than a logical 'if' clause.
     if ($priceSetId) {
         CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'], $submittedValues, $lineItem[$priceSetId]);
         // Unset tax amount for offline 'is_quick_config' contribution.
         // @todo WHY  - quick config was conceived as a quick way to configure contribution forms.
         // this is an example of 'other' functionality being hung off it.
         if ($this->_priceSet['is_quick_config'] && !array_key_exists($submittedValues['financial_type_id'], CRM_Core_PseudoConstant::getTaxRates())) {
             unset($submittedValues['tax_amount']);
         }
         $submittedValues['total_amount'] = CRM_Utils_Array::value('amount', $submittedValues);
     }
     if ($this->_id) {
         if ($this->_compId) {
             if ($this->_context == 'participant') {
                 $pId = $this->_compId;
             } elseif ($this->_context == 'membership') {
                 $isRelatedId = TRUE;
             } else {
                 $pId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id, 'participant_id', 'contribution_id');
             }
         } else {
             $contributionDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
             if (array_key_exists('membership', $contributionDetails)) {
                 $isRelatedId = TRUE;
             } elseif (array_key_exists('participant', $contributionDetails)) {
                 $pId = $contributionDetails['participant'];
             }
         }
     }
     if (!$priceSetId && !empty($submittedValues['total_amount']) && $this->_id) {
         // CRM-10117 update the line items for participants.
         // @todo - if we are completing a contribution then the api call
         // civicrm_api3('Contribution', 'completetransaction') should take care of
         // all associated updates rather than replicating them on the form layer.
         if ($pId) {
             $entityTable = 'participant';
             $entityID = $pId;
             $isRelatedId = FALSE;
             $participantParams = array('fee_amount' => $submittedValues['total_amount'], 'id' => $entityID);
             CRM_Event_BAO_Participant::add($participantParams);
             if (empty($this->_lineItems)) {
                 $this->_lineItems[] = CRM_Price_BAO_LineItem::getLineItems($entityID, 'participant', 1);
             }
         } else {
             $entityTable = 'contribution';
             $entityID = $this->_id;
         }
         $lineItems = CRM_Price_BAO_LineItem::getLineItems($entityID, $entityTable, NULL, TRUE, $isRelatedId);
         foreach (array_keys($lineItems) as $id) {
             $lineItems[$id]['id'] = $id;
         }
         $itemId = key($lineItems);
         if ($itemId && !empty($lineItems[$itemId]['price_field_id'])) {
             $this->_priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id');
         }
         // @todo see above - new functionality has been inappropriately added to the quick config concept
         // and new functionality has been added onto the form layer rather than the BAO :-(
         if ($this->_priceSetId && CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) {
             //CRM-16833: Ensure tax is applied only once for membership conribution, when status changed.(e.g Pending to Completed).
             $componentDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
             if (!(CRM_Utils_Array::value('membership', $componentDetails) || CRM_Utils_Array::value('participant', $componentDetails))) {
                 if (!($this->_action & CRM_Core_Action::UPDATE && $this->_defaults['contribution_status_id'] != $submittedValues['contribution_status_id'])) {
                     $lineItems[$itemId]['unit_price'] = $lineItems[$itemId]['line_total'] = CRM_Utils_Rule::cleanMoney(CRM_Utils_Array::value('total_amount', $submittedValues));
                 }
             }
             // Update line total and total amount with tax on edit.
             $financialItemsId = CRM_Core_PseudoConstant::getTaxRates();
             if (array_key_exists($submittedValues['financial_type_id'], $financialItemsId)) {
                 $lineItems[$itemId]['tax_rate'] = $financialItemsId[$submittedValues['financial_type_id']];
             } else {
                 $lineItems[$itemId]['tax_rate'] = $lineItems[$itemId]['tax_amount'] = "";
                 $submittedValues['tax_amount'] = 'null';
             }
             if ($lineItems[$itemId]['tax_rate']) {
                 $lineItems[$itemId]['tax_amount'] = $lineItems[$itemId]['tax_rate'] / 100 * $lineItems[$itemId]['line_total'];
                 $submittedValues['total_amount'] = $lineItems[$itemId]['line_total'] + $lineItems[$itemId]['tax_amount'];
                 $submittedValues['tax_amount'] = $lineItems[$itemId]['tax_amount'];
             }
         }
         // CRM-10117 update the line items for participants.
         if (!empty($lineItems[$itemId]['price_field_id'])) {
             $lineItem[$this->_priceSetId] = $lineItems;
         }
     }
     $isQuickConfig = 0;
     if ($this->_priceSetId && CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) {
         $isQuickConfig = 1;
     }
     //CRM-11529 for quick config back office transactions
     //when financial_type_id is passed in form, update the
     //line items with the financial type selected in form
     // NOTE that this IS still a legitimate use of 'quick-config' for contributions under the current DB but
     // we should look at having a price field per contribution type & then there would be little reason
     // for the back-office contribution form postProcess to know if it is a quick-config form.
     if ($isQuickConfig && !empty($submittedValues['financial_type_id']) && CRM_Utils_Array::value($this->_priceSetId, $lineItem)) {
         foreach ($lineItem[$this->_priceSetId] as &$values) {
             $values['financial_type_id'] = $submittedValues['financial_type_id'];
         }
     }
     if (!isset($submittedValues['total_amount'])) {
         $submittedValues['total_amount'] = CRM_Utils_Array::value('total_amount', $this->_values);
     }
     $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ? $lineItem : FALSE);
     $isEmpty = array_keys(array_flip($submittedValues['soft_credit_contact_id']));
     if ($this->_id && count($isEmpty) == 1 && key($isEmpty) == NULL) {
         //Delete existing soft credit records if soft credit list is empty on update
         CRM_Contribute_BAO_ContributionSoft::del(array('contribution_id' => $this->_id, 'pcp_id' => 0));
     }
     // set the contact, when contact is selected
     if (!empty($submittedValues['contact_id'])) {
         $this->_contactID = $submittedValues['contact_id'];
     }
     $formValues = $submittedValues;
     // Credit Card Contribution.
     if ($this->_mode) {
         $paramsSetByPaymentProcessingSubsystem = array('trxn_id', 'payment_instrument_id', 'contribution_status_id', 'cancel_date', 'cancel_reason');
         foreach ($paramsSetByPaymentProcessingSubsystem as $key) {
             if (isset($formValues[$key])) {
                 unset($formValues[$key]);
             }
         }
         $contribution = $this->processCreditCard($formValues, $lineItem, $this->_contactID);
         foreach ($paramsSetByPaymentProcessingSubsystem as $key) {
             $formValues[$key] = $contribution->{$key};
         }
     } else {
         // Offline Contribution.
         $submittedValues = $this->unsetCreditCardFields($submittedValues);
         // get the required field value only.
         $params = $ids = array();
         $params['contact_id'] = $this->_contactID;
         $params['currency'] = $this->getCurrency($submittedValues);
         //format soft-credit/pcp param first
         CRM_Contribute_BAO_ContributionSoft::formatSoftCreditParams($submittedValues, $this);
         $params = array_merge($params, $submittedValues);
         $fields = array('financial_type_id', 'contribution_status_id', 'payment_instrument_id', 'cancel_reason', 'source', 'check_number');
         foreach ($fields as $f) {
             $params[$f] = CRM_Utils_Array::value($f, $formValues);
         }
         // CRM-5740 if priceset is used, no need to cleanup money.
         if ($priceSetId) {
             $params['skipCleanMoney'] = 1;
         }
         $dates = array('receive_date', 'receipt_date', 'cancel_date');
         foreach ($dates as $d) {
             $params[$d] = CRM_Utils_Date::processDate($formValues[$d], $formValues[$d . '_time'], TRUE);
         }
         if (!empty($formValues['is_email_receipt'])) {
             $params['receipt_date'] = date("Y-m-d");
         }
         if ($params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Cancelled', 'name') || $params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Refunded', 'name')) {
             if (CRM_Utils_System::isNull(CRM_Utils_Array::value('cancel_date', $params))) {
                 $params['cancel_date'] = date('YmdHis');
             }
         } else {
             $params['cancel_date'] = $params['cancel_reason'] = 'null';
         }
         // Set is_pay_later flag for back-office offline Pending status contributions CRM-8996
         // else if contribution_status is changed to Completed is_pay_later flag is changed to 0, CRM-15041
         if ($params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Pending', 'name')) {
             $params['is_pay_later'] = 1;
         } elseif ($params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name')) {
             $params['is_pay_later'] = 0;
         }
         $ids['contribution'] = $params['id'] = $this->_id;
         // Add Additional common information to formatted params.
         CRM_Contribute_Form_AdditionalInfo::postProcessCommon($formValues, $params, $this);
         if ($pId) {
             $params['contribution_mode'] = 'participant';
             $params['participant_id'] = $pId;
             $params['skipLineItem'] = 1;
         } elseif ($isRelatedId) {
             $params['contribution_mode'] = 'membership';
         }
         $params['line_item'] = $lineItem;
         $params['payment_processor_id'] = $params['payment_processor'] = CRM_Utils_Array::value('id', $this->_paymentProcessor);
         if (isset($submittedValues['tax_amount'])) {
             $params['tax_amount'] = $submittedValues['tax_amount'];
         }
         //create contribution.
         if ($isQuickConfig) {
             $params['is_quick_config'] = 1;
         }
         $params['non_deductible_amount'] = $this->calculateNonDeductibleAmount($params, $formValues);
         // we are already handling note below, so to avoid duplicate notes against $contribution
         if (!empty($params['note']) && !empty($submittedValues['note'])) {
             unset($params['note']);
         }
         $contribution = CRM_Contribute_BAO_Contribution::create($params, $ids);
         // process associated membership / participant, CRM-4395
         if ($contribution->id && $action & CRM_Core_Action::UPDATE) {
             $this->statusMessage[] = $this->updateRelatedComponent($contribution->id, $contribution->contribution_status_id, CRM_Utils_Array::value('contribution_status_id', $this->_values), $contribution->receive_date);
         }
         array_unshift($this->statusMessage, ts('The contribution record has been saved.'));
         $this->invoicingPostProcessHook($submittedValues, $action, $lineItem);
         //send receipt mail.
         if ($contribution->id && !empty($formValues['is_email_receipt'])) {
             $formValues['contact_id'] = $this->_contactID;
             $formValues['contribution_id'] = $contribution->id;
             $formValues += CRM_Contribute_BAO_ContributionSoft::getSoftContribution($contribution->id);
             // to get 'from email id' for send receipt
             $this->fromEmailId = $formValues['from_email_address'];
             if (CRM_Contribute_Form_AdditionalInfo::emailReceipt($this, $formValues)) {
                 $this->statusMessage[] = ts('A receipt has been emailed to the contributor.');
             }
         }
         $this->statusMessageTitle = ts('Saved');
     }
     if ($contribution->id && isset($formValues['product_name'][0])) {
         CRM_Contribute_Form_AdditionalInfo::processPremium($submittedValues, $contribution->id, $this->_premiumID, $this->_options);
     }
     if ($contribution->id && !empty($submittedValues['note'])) {
         CRM_Contribute_Form_AdditionalInfo::processNote($submittedValues, $this->_contactID, $contribution->id, $this->_noteID);
     }
     CRM_Core_Session::setStatus(implode(' ', $this->statusMessage), $this->statusMessageTitle, 'success');
     CRM_Contribute_BAO_Contribution::updateRelatedPledge($action, $pledgePaymentID, $contribution->id, CRM_Utils_Array::value('option_type', $formValues) == 2 ? TRUE : FALSE, $formValues['total_amount'], CRM_Utils_Array::value('total_amount', $this->_defaults), $formValues['contribution_status_id'], CRM_Utils_Array::value('contribution_status_id', $this->_defaults));
     return $contribution;
 }
Ejemplo n.º 20
0
 /**
  * The post processing of the form gets done here.
  *
  * Key things done during post processing are
  *      - check for reset or next request. if present, skip post procesing.
  *      - now check if user requested running a saved search, if so, then
  *        the form values associated with the saved search are used for searching.
  *      - if user has done a submit with new values the regular post submissing is
  *        done.
  * The processing consists of using a Selector / Controller framework for getting the
  * search results.
  *
  * @param
  *
  * @return void
  * @access public
  */
 function postProcess()
 {
     $this->set('isAdvanced', '1');
     // get user submitted values
     // get it from controller only if form has been submitted, else preProcess has set this
     if (!empty($_POST)) {
         $this->_formValues = $this->controller->exportValues($this->_name);
         $this->normalizeFormValues();
         // FIXME: couldn't figure out a good place to do this,
         // FIXME: so leaving this as a dependency for now
         if (array_key_exists('contribution_amount_low', $this->_formValues)) {
             foreach (array('contribution_amount_low', 'contribution_amount_high') as $f) {
                 $this->_formValues[$f] = CRM_Utils_Rule::cleanMoney($this->_formValues[$f]);
             }
         }
         // set the group if group is submitted
         if (!empty($this->_formValues['uf_group_id'])) {
             $this->set('id', $this->_formValues['uf_group_id']);
         } else {
             $this->set('id', '');
         }
     }
     // retrieve ssID values only if formValues is null, i.e. form has never been posted
     if (empty($this->_formValues) && isset($this->_ssID)) {
         $this->_formValues = CRM_Contact_BAO_SavedSearch::getFormValues($this->_ssID);
     }
     if (isset($this->_groupID) && !CRM_Utils_Array::value('group', $this->_formValues)) {
         $this->_formValues['group'] = array($this->_groupID => 1);
     }
     //search for civicase
     if (is_array($this->_formValues)) {
         $allCases = FALSE;
         if (array_key_exists('case_owner', $this->_formValues) && !$this->_formValues['case_owner'] && !$this->_force) {
             foreach (array('case_type_id', 'case_status_id', 'case_deleted', 'case_tags') as $caseCriteria) {
                 if (CRM_Utils_Array::value($caseCriteria, $this->_formValues)) {
                     $allCases = TRUE;
                     $this->_formValues['case_owner'] = 1;
                     continue;
                 }
             }
             if ($allCases) {
                 if (CRM_Core_Permission::check('access all cases and activities')) {
                     $this->_formValues['case_owner'] = 1;
                 } else {
                     $this->_formValues['case_owner'] = 2;
                 }
             } else {
                 $this->_formValues['case_owner'] = 0;
             }
         }
     }
     // we dont want to store the sortByCharacter in the formValue, it is more like
     // a filter on the result set
     // this filter is reset if we click on the search button
     if ($this->_sortByCharacter !== NULL && empty($_POST)) {
         if (strtolower($this->_sortByCharacter) == 'all') {
             $this->_formValues['sortByCharacter'] = NULL;
         } else {
             $this->_formValues['sortByCharacter'] = $this->_sortByCharacter;
         }
     } else {
         $this->_sortByCharacter = NULL;
     }
     CRM_Core_BAO_CustomValue::fixFieldValueOfTypeMemo($this->_formValues);
     $this->_params = CRM_Contact_BAO_Query::convertFormValues($this->_formValues);
     $this->_returnProperties =& $this->returnProperties();
     parent::postProcess();
 }
Ejemplo n.º 21
0
 function having($includeContactIDs = FALSE)
 {
     $clauses = array();
     $min = CRM_Utils_Array::value('min_amount', $this->_formValues);
     if ($min) {
         $min = CRM_Utils_Rule::cleanMoney($min);
         $clauses[] = "sum(contrib.total_amount) >= {$min}";
     }
     $max = CRM_Utils_Array::value('max_amount', $this->_formValues);
     if ($max) {
         $max = CRM_Utils_Rule::cleanMoney($max);
         $clauses[] = "sum(contrib.total_amount) <= {$max}";
     }
     return implode(' AND ', $clauses);
 }
Ejemplo n.º 22
0
 /**
  * Format custom fields before inserting
  *
  * @param int    $customFieldId       custom field id
  * @param array  $customFormatted     formatted array
  * @param mix    $value               value of custom field
  * @param string $customFieldExtend   custom field extends
  * @param int    $customValueId custom option value id
  * @param int    $entityId            entity id (contribution, membership...)
  *
  * @return array $customFormatted formatted custom field array
  * @static
  */
 static function formatCustomField($customFieldId, &$customFormatted, $value, $customFieldExtend, $customValueId = null, $entityId = null, $inline = false)
 {
     //get the custom fields for the entity
     //subtype and basic type
     $customDataSubType = null;
     if (in_array($customFieldExtend, CRM_Contact_BAO_ContactType::subTypes())) {
         // This is the case when getFieldsForImport() requires fields
         // of subtype and its parent.CRM-5143
         $customDataSubType = $customFieldExtend;
         $customFieldExtend = CRM_Contact_BAO_ContactType::getBasicType($customDataSubType);
     }
     $customFields = CRM_Core_BAO_CustomField::getFields($customFieldExtend, false, $inline, $customDataSubType);
     if (!array_key_exists($customFieldId, $customFields)) {
         return;
     }
     // return if field is a 'code' field
     if (CRM_Utils_Array::value('is_view', $customFields[$customFieldId])) {
         return;
     }
     list($tableName, $columnName, $groupID) = self::getTableColumnGroup($customFieldId);
     if (is_array($customFieldExtend)) {
         $customFieldExtend = $customFieldExtend[0];
     }
     if (!$customValueId && !$customFields[$customFieldId]['is_multiple'] && $entityId) {
         //get the entity table for the custom field
         require_once "CRM/Core/BAO/CustomQuery.php";
         $entityTable = CRM_Core_BAO_CustomQuery::$extendsMap[$customFieldExtend];
         $query = "\nSELECT id \n  FROM {$tableName}\n WHERE entity_id={$entityId}";
         $customValueId = CRM_Core_DAO::singleValueQuery($query);
     }
     //fix checkbox, now check box always submits values
     if ($customFields[$customFieldId]['html_type'] == 'CheckBox') {
         if ($value) {
             // Note that only during merge this is not an array, and you can directly use value
             if (is_array($value)) {
                 $selectedValues = null;
                 foreach ($value as $selId => $val) {
                     if ($val) {
                         $selectedValues .= $selId . CRM_Core_BAO_CustomOption::VALUE_SEPERATOR;
                     }
                 }
                 if ($selectedValues) {
                     $value = CRM_Core_BAO_CustomOption::VALUE_SEPERATOR . $selectedValues;
                 } else {
                     $value = '';
                 }
             }
         }
     }
     if ($customFields[$customFieldId]['html_type'] == 'Multi-Select' || $customFields[$customFieldId]['html_type'] == 'AdvMulti-Select') {
         if ($value) {
             // Note that only during merge this is not an array,
             // and you can directly use value, CRM-4385
             if (is_array($value)) {
                 $value = CRM_Core_BAO_CustomOption::VALUE_SEPERATOR . implode(CRM_Core_BAO_CustomOption::VALUE_SEPERATOR, array_values($value)) . CRM_Core_BAO_CustomOption::VALUE_SEPERATOR;
             }
         } else {
             $value = '';
         }
     }
     $date = null;
     if ($customFields[$customFieldId]['data_type'] == 'Date') {
         if (!CRM_Utils_System::isNull($value)) {
             $format = $customFields[$customFieldId]['date_format'];
             if (in_array($format, array('dd-mm', 'mm/dd'))) {
                 $dateTimeArray = explode(' ', $value);
                 $separator = '/';
                 if ($format == 'dd-mm') {
                     $separator = '-';
                 }
                 $value = $dateTimeArray[0] . $separator . '1902';
                 if (array_key_exists(1, $dateTimeArray)) {
                     $value .= ' ' . $dateTimeArray[1];
                 }
             }
             $date = CRM_Utils_Date::processDate($value);
         }
         $value = $date;
     }
     if ($customFields[$customFieldId]['data_type'] == 'Float' || $customFields[$customFieldId]['data_type'] == 'Money') {
         if (!$value) {
             $value = 0;
         }
         if ($customFields[$customFieldId]['data_type'] == 'Money') {
             require_once 'CRM/Utils/Rule.php';
             $value = CRM_Utils_Rule::cleanMoney($value);
         }
     }
     if (($customFields[$customFieldId]['data_type'] == 'StateProvince' || $customFields[$customFieldId]['data_type'] == 'Country') && empty($value)) {
         // CRM-3415
         $value = 0;
     }
     $fileId = null;
     if ($customFields[$customFieldId]['data_type'] == 'File') {
         if (empty($value)) {
             return;
         }
         require_once 'CRM/Core/DAO/File.php';
         $config =& CRM_Core_Config::singleton();
         $fName = $value['name'];
         $mimeType = $value['type'];
         $path = explode('/', $fName);
         $filename = $path[count($path) - 1];
         // rename this file to go into the secure directory
         if (!rename($fName, $config->customFileUploadDir . $filename)) {
             CRM_Core_Error::statusBounce(ts('Could not move custom file to custom upload directory'));
             break;
         }
         if ($customValueId) {
             $query = "\nSELECT {$columnName}\n  FROM {$tableName}\n WHERE id = %1";
             $params = array(1 => array($customValueId, 'Integer'));
             $fileId = CRM_Core_DAO::singleValueQuery($query, $params);
         }
         $fileDAO =& new CRM_Core_DAO_File();
         if ($fileId) {
             $fileDAO->id = $fileId;
         }
         $fileDAO->uri = $filename;
         $fileDAO->mime_type = $mimeType;
         $fileDAO->upload_date = date('Ymdhis');
         $fileDAO->save();
         $fileId = $fileDAO->id;
         $value = $filename;
     }
     if (!is_array($customFormatted)) {
         $customFormatted = array();
     }
     if (!array_key_exists($customFieldId, $customFormatted)) {
         $customFormatted[$customFieldId] = array();
     }
     $index = -1;
     if ($customValueId) {
         $index = $customValueId;
     }
     if (!array_key_exists($index, $customFormatted[$customFieldId])) {
         $customFormatted[$customFieldId][$index] = array();
     }
     $customFormatted[$customFieldId][$index] = array('id' => $customValueId > 0 ? $customValueId : null, 'value' => $value, 'type' => $customFields[$customFieldId]['data_type'], 'custom_field_id' => $customFieldId, 'custom_group_id' => $groupID, 'table_name' => $tableName, 'column_name' => $columnName, 'file_id' => $fileId, 'is_multiple' => $customFields[$customFieldId]['is_multiple']);
     //we need to sort so that custom fields are created in the order of entry
     krsort($customFormatted[$customFieldId]);
     return $customFormatted;
 }
Ejemplo n.º 23
0
 /**
  * takes an associative array and creates a price field object
  *
  * This function is invoked from within the web form layer and also from the api layer
  *
  * @param array $params (reference) an assoc array of name/value pairs
  *
  * @return object CRM_Price_DAO_PriceField object
  * @access public
  * @static
  */
 static function create(&$params)
 {
     if (empty($params['id']) && empty($params['name'])) {
         $params['name'] = strtolower(CRM_Utils_String::munge($params['label'], '_', 242));
     }
     $transaction = new CRM_Core_Transaction();
     $priceField = self::add($params);
     if (is_a($priceField, 'CRM_Core_Error')) {
         $transaction->rollback();
         return $priceField;
     }
     $optionsIds = array();
     $maxIndex = CRM_Price_Form_Field::NUM_OPTION;
     if ($priceField->html_type == 'Text') {
         $maxIndex = 1;
         $fieldValue = new CRM_Price_DAO_PriceFieldValue();
         $fieldValue->price_field_id = $priceField->id;
         // update previous field values( if any )
         if ($fieldValue->find(TRUE)) {
             $optionsIds['id'] = $fieldValue->id;
         }
     }
     $defaultArray = array();
     //html type would be empty in update scenario not sure what would happen ...
     if (!empty($params['html_type']) && $params['html_type'] == 'CheckBox' && isset($params['default_checkbox_option'])) {
         $tempArray = array_keys($params['default_checkbox_option']);
         foreach ($tempArray as $v) {
             if ($params['option_amount'][$v]) {
                 $defaultArray[$v] = 1;
             }
         }
     } else {
         if (!empty($params['default_option'])) {
             $defaultArray[$params['default_option']] = 1;
         }
     }
     for ($index = 1; $index <= $maxIndex; $index++) {
         if (array_key_exists('option_amount', $params) && array_key_exists($index, $params['option_amount']) && (CRM_Utils_Array::value($index, CRM_Utils_Array::value('option_label', $params)) || !empty($params['is_quick_config'])) && !CRM_Utils_System::isNull($params['option_amount'][$index])) {
             $options = array('price_field_id' => $priceField->id, 'label' => trim($params['option_label'][$index]), 'name' => CRM_Utils_String::munge($params['option_label'][$index], '_', 64), 'amount' => CRM_Utils_Rule::cleanMoney(trim($params['option_amount'][$index])), 'count' => CRM_Utils_Array::value($index, CRM_Utils_Array::value('option_count', $params), NULL), 'max_value' => CRM_Utils_Array::value($index, CRM_Utils_Array::value('option_max_value', $params), NULL), 'description' => CRM_Utils_Array::value($index, CRM_Utils_Array::value('option_description', $params), NULL), 'membership_type_id' => CRM_Utils_Array::value($index, CRM_Utils_Array::value('membership_type_id', $params), NULL), 'weight' => $params['option_weight'][$index], 'is_active' => 1, 'is_default' => CRM_Utils_Array::value($params['option_weight'][$index], $defaultArray) ? $defaultArray[$params['option_weight'][$index]] : 0, 'membership_num_terms' => NULL);
             if ($options['membership_type_id']) {
                 $options['membership_num_terms'] = CRM_Utils_Array::value($index, CRM_Utils_Array::value('membership_num_terms', $params), 1);
             }
             if (CRM_Utils_Array::value($index, CRM_Utils_Array::value('option_financial_type_id', $params))) {
                 $options['financial_type_id'] = $params['option_financial_type_id'][$index];
             } elseif (!empty($params['financial_type_id'])) {
                 $options['financial_type_id'] = $params['financial_type_id'];
             }
             if ($opIds = CRM_Utils_Array::value('option_id', $params)) {
                 if ($opId = CRM_Utils_Array::value($index, $opIds)) {
                     $optionsIds['id'] = $opId;
                 } else {
                     $optionsIds['id'] = NULL;
                 }
             }
             CRM_Price_BAO_PriceFieldValue::create($options, $optionsIds);
         }
     }
     $transaction->commit();
     return $priceField;
 }
Ejemplo n.º 24
0
 /**
  * Format custom fields before inserting.
  *
  * @param int $customFieldId
  *   Custom field id.
  * @param array $customFormatted
  *   Formatted array.
  * @param mix $value
  *   Value of custom field.
  * @param string $customFieldExtend
  *   Custom field extends.
  * @param int $customValueId
  *   Custom option value id.
  * @param int $entityId
  *   Entity id (contribution, membership...).
  * @param bool $inline
  *   Consider inline custom groups only.
  * @param bool $checkPermission
  *   If false, do not include permissioning clause.
  * @param bool $includeViewOnly
  *   If true, fields marked 'View Only' are included. Required for APIv3.
  *
  * @return array|NULL
  *   formatted custom field array
  */
 public static function formatCustomField($customFieldId, &$customFormatted, $value, $customFieldExtend, $customValueId = NULL, $entityId = NULL, $inline = FALSE, $checkPermission = TRUE, $includeViewOnly = FALSE)
 {
     //get the custom fields for the entity
     //subtype and basic type
     $customDataSubType = NULL;
     if ($customFieldExtend) {
         // This is the case when getFieldsForImport() requires fields
         // of subtype and its parent.CRM-5143
         // CRM-16065 - Custom field set data not being saved if contact has more than one contact sub type
         $customDataSubType = array_intersect(CRM_Contact_BAO_ContactType::subTypes(), (array) $customFieldExtend);
         if (!empty($customDataSubType) && is_array($customDataSubType)) {
             $customFieldExtend = CRM_Contact_BAO_ContactType::getBasicType($customDataSubType);
             if (is_array($customFieldExtend)) {
                 $customFieldExtend = array_unique(array_values($customFieldExtend));
             }
         }
     }
     $customFields = CRM_Core_BAO_CustomField::getFields($customFieldExtend, FALSE, $inline, $customDataSubType, NULL, FALSE, FALSE, $checkPermission);
     if (!array_key_exists($customFieldId, $customFields)) {
         return NULL;
     }
     // return if field is a 'code' field
     if (!$includeViewOnly && !empty($customFields[$customFieldId]['is_view'])) {
         return NULL;
     }
     list($tableName, $columnName, $groupID) = self::getTableColumnGroup($customFieldId);
     if (!$customValueId && !$customFields[$customFieldId]['is_multiple'] && $entityId) {
         $query = "\nSELECT id\n  FROM {$tableName}\n WHERE entity_id={$entityId}";
         $customValueId = CRM_Core_DAO::singleValueQuery($query);
     }
     //fix checkbox, now check box always submits values
     if ($customFields[$customFieldId]['html_type'] == 'CheckBox') {
         if ($value) {
             // Note that only during merge this is not an array, and you can directly use value
             if (is_array($value)) {
                 $selectedValues = array();
                 foreach ($value as $selId => $val) {
                     if ($val) {
                         $selectedValues[] = $selId;
                     }
                 }
                 if (!empty($selectedValues)) {
                     $value = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $selectedValues) . CRM_Core_DAO::VALUE_SEPARATOR;
                 } else {
                     $value = '';
                 }
             }
         }
     }
     if ($customFields[$customFieldId]['html_type'] == 'Multi-Select' || $customFields[$customFieldId]['html_type'] == 'AdvMulti-Select') {
         if ($value) {
             // Note that only during merge this is not an array,
             // and you can directly use value, CRM-4385
             if (is_array($value)) {
                 $value = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, array_values($value)) . CRM_Core_DAO::VALUE_SEPARATOR;
             }
         } else {
             $value = '';
         }
     }
     if (($customFields[$customFieldId]['html_type'] == 'Multi-Select' || $customFields[$customFieldId]['html_type'] == 'AdvMulti-Select' || $customFields[$customFieldId]['html_type'] == 'CheckBox') && $customFields[$customFieldId]['data_type'] == 'String' && !empty($customFields[$customFieldId]['text_length']) && !empty($value)) {
         // lets make sure that value is less than the length, else we'll
         // be losing some data, CRM-7481
         if (strlen($value) >= $customFields[$customFieldId]['text_length']) {
             // need to do a few things here
             // 1. lets find a new length
             $newLength = $customFields[$customFieldId]['text_length'];
             $minLength = strlen($value);
             while ($newLength < $minLength) {
                 $newLength = $newLength * 2;
             }
             // set the custom field meta data to have a length larger than value
             // alter the custom value table column to match this length
             CRM_Core_BAO_SchemaHandler::alterFieldLength($customFieldId, $tableName, $columnName, $newLength);
         }
     }
     $date = NULL;
     if ($customFields[$customFieldId]['data_type'] == 'Date') {
         if (!CRM_Utils_System::isNull($value)) {
             $format = $customFields[$customFieldId]['date_format'];
             $date = CRM_Utils_Date::processDate($value, NULL, FALSE, 'YmdHis', $format);
         }
         $value = $date;
     }
     if ($customFields[$customFieldId]['data_type'] == 'Float' || $customFields[$customFieldId]['data_type'] == 'Money') {
         if (!$value) {
             $value = 0;
         }
         if ($customFields[$customFieldId]['data_type'] == 'Money') {
             $value = CRM_Utils_Rule::cleanMoney($value);
         }
     }
     if (($customFields[$customFieldId]['data_type'] == 'StateProvince' || $customFields[$customFieldId]['data_type'] == 'Country') && empty($value)) {
         // CRM-3415
         $value = 0;
     }
     $fileId = NULL;
     if ($customFields[$customFieldId]['data_type'] == 'File') {
         if (empty($value)) {
             return;
         }
         $config = CRM_Core_Config::singleton();
         $fName = $value['name'];
         $mimeType = $value['type'];
         $filename = pathinfo($fName, PATHINFO_BASENAME);
         // rename this file to go into the secure directory
         if (!rename($fName, $config->customFileUploadDir . $filename)) {
             CRM_Core_Error::statusBounce(ts('Could not move custom file to custom upload directory'));
         }
         if ($customValueId) {
             $query = "\nSELECT {$columnName}\n  FROM {$tableName}\n WHERE id = %1";
             $params = array(1 => array($customValueId, 'Integer'));
             $fileId = CRM_Core_DAO::singleValueQuery($query, $params);
         }
         $fileDAO = new CRM_Core_DAO_File();
         if ($fileId) {
             $fileDAO->id = $fileId;
         }
         $fileDAO->uri = $filename;
         $fileDAO->mime_type = $mimeType;
         $fileDAO->upload_date = date('Ymdhis');
         $fileDAO->save();
         $fileId = $fileDAO->id;
         $value = $filename;
     }
     if (!is_array($customFormatted)) {
         $customFormatted = array();
     }
     if (!array_key_exists($customFieldId, $customFormatted)) {
         $customFormatted[$customFieldId] = array();
     }
     $index = -1;
     if ($customValueId) {
         $index = $customValueId;
     }
     if (!array_key_exists($index, $customFormatted[$customFieldId])) {
         $customFormatted[$customFieldId][$index] = array();
     }
     $customFormatted[$customFieldId][$index] = array('id' => $customValueId > 0 ? $customValueId : NULL, 'value' => $value, 'type' => $customFields[$customFieldId]['data_type'], 'custom_field_id' => $customFieldId, 'custom_group_id' => $groupID, 'table_name' => $tableName, 'column_name' => $columnName, 'file_id' => $fileId, 'is_multiple' => $customFields[$customFieldId]['is_multiple']);
     //we need to sort so that custom fields are created in the order of entry
     krsort($customFormatted[$customFieldId]);
     return $customFormatted;
 }
Ejemplo n.º 25
0
 /**
  * process membership records
  *
  * @param array $params associated array of submitted values
  *
  * @access public
  *
  * @return bool
  */
 private function processMembership(&$params)
 {
     $dateTypes = array('join_date' => 'joinDate', 'membership_start_date' => 'startDate', 'membership_end_date' => 'endDate');
     $dates = array('join_date', 'start_date', 'end_date', 'reminder_date');
     // get the price set associated with offline memebership
     $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', 'default_membership_type_amount', 'id', 'name');
     $this->_priceSet = $priceSets = current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId));
     if (isset($params['field'])) {
         $customFields = array();
         foreach ($params['field'] as $key => $value) {
             // if contact is not selected we should skip the row
             if (empty($params['primary_contact_id'][$key])) {
                 continue;
             }
             $value['contact_id'] = CRM_Utils_Array::value($key, $params['primary_contact_id']);
             // update contact information
             $this->updateContactInfo($value);
             $membershipTypeId = $value['membership_type_id'] = $value['membership_type'][1];
             foreach ($dateTypes as $dateField => $dateVariable) {
                 ${$dateVariable} = CRM_Utils_Date::processDate($value[$dateField]);
             }
             $calcDates = array();
             $calcDates[$membershipTypeId] = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membershipTypeId, $joinDate, $startDate, $endDate);
             foreach ($calcDates as $memType => $calcDate) {
                 foreach ($dates as $d) {
                     //first give priority to form values then calDates.
                     $date = CRM_Utils_Array::value($d, $value);
                     if (!$date) {
                         $date = CRM_Utils_Array::value($d, $calcDate);
                     }
                     $value[$d] = CRM_Utils_Date::processDate($date);
                 }
             }
             if (!empty($value['send_receipt'])) {
                 $value['receipt_date'] = date('Y-m-d His');
             }
             if (!empty($value['membership_source'])) {
                 $value['source'] = $value['membership_source'];
             }
             unset($value['membership_source']);
             //Get the membership status
             if (!empty($value['membership_status'])) {
                 $value['status_id'] = $value['membership_status'];
                 unset($value['membership_status']);
             }
             if (empty($customFields)) {
                 // membership type custom data
                 $customFields = CRM_Core_BAO_CustomField::getFields('Membership', FALSE, FALSE, $membershipTypeId);
                 $customFields = CRM_Utils_Array::crmArrayMerge($customFields, CRM_Core_BAO_CustomField::getFields('Membership', FALSE, FALSE, NULL, NULL, TRUE));
             }
             //check for custom data
             $value['custom'] = CRM_Core_BAO_CustomField::postProcess($params['field'][$key], $customFields, $key, 'Membership', $membershipTypeId);
             if (!empty($value['financial_type'])) {
                 $value['financial_type_id'] = $value['financial_type'];
             }
             if (!empty($value['payment_instrument'])) {
                 $value['payment_instrument_id'] = $value['payment_instrument'];
             }
             // handle soft credit
             if (is_array(CRM_Utils_Array::value('soft_credit_contact_id', $params)) && !empty($params['soft_credit_contact_id'][$key]) && CRM_Utils_Array::value($key, $params['soft_credit_amount'])) {
                 $value['soft_credit'][$key]['contact_id'] = $params['soft_credit_contact_id'][$key];
                 $value['soft_credit'][$key]['amount'] = CRM_Utils_Rule::cleanMoney($params['soft_credit_amount'][$key]);
             }
             if (!empty($value['receive_date'])) {
                 $value['receive_date'] = CRM_Utils_Date::processDate($value['receive_date'], $value['receive_date_time'], TRUE);
             }
             $params['actualBatchTotal'] += $value['total_amount'];
             unset($value['financial_type']);
             unset($value['payment_instrument']);
             $value['batch_id'] = $this->_batchId;
             $value['skipRecentView'] = TRUE;
             // make entry in line item for contribution
             $editedFieldParams = array('price_set_id' => $priceSetId, 'name' => $value['membership_type'][0]);
             $editedResults = array();
             CRM_Price_BAO_PriceField::retrieve($editedFieldParams, $editedResults);
             if (!empty($editedResults)) {
                 unset($this->_priceSet['fields']);
                 $this->_priceSet['fields'][$editedResults['id']] = $priceSets['fields'][$editedResults['id']];
                 unset($this->_priceSet['fields'][$editedResults['id']]['options']);
                 $fid = $editedResults['id'];
                 $editedFieldParams = array('price_field_id' => $editedResults['id'], 'membership_type_id' => $value['membership_type_id']);
                 $editedResults = array();
                 CRM_Price_BAO_PriceFieldValue::retrieve($editedFieldParams, $editedResults);
                 $this->_priceSet['fields'][$fid]['options'][$editedResults['id']] = $priceSets['fields'][$fid]['options'][$editedResults['id']];
                 if (!empty($value['total_amount'])) {
                     $this->_priceSet['fields'][$fid]['options'][$editedResults['id']]['amount'] = $value['total_amount'];
                 }
                 $fieldID = key($this->_priceSet['fields']);
                 $value['price_' . $fieldID] = $editedResults['id'];
                 $lineItem = array();
                 CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'], $value, $lineItem[$priceSetId]);
                 //CRM-11529 for backoffice transactions
                 //when financial_type_id is passed in form, update the
                 //lineitems with the financial type selected in form
                 if (!empty($value['financial_type_id']) && !empty($lineItem[$priceSetId])) {
                     foreach ($lineItem[$priceSetId] as &$values) {
                         $values['financial_type_id'] = $value['financial_type_id'];
                     }
                 }
                 $value['lineItems'] = $lineItem;
                 $value['processPriceSet'] = TRUE;
             }
             // end of contribution related section
             unset($value['membership_type']);
             unset($value['membership_start_date']);
             unset($value['membership_end_date']);
             $value['is_renew'] = false;
             if (!empty($params['member_option']) && CRM_Utils_Array::value($key, $params['member_option']) == 2) {
                 $this->_params = $params;
                 $value['is_renew'] = true;
                 $membership = CRM_Member_BAO_Membership::renewMembershipFormWrapper($value['contact_id'], $value['membership_type_id'], FALSE, $this, NULL, NULL, $value['custom']);
                 // make contribution entry
                 CRM_Member_BAO_Membership::recordMembershipContribution(array_merge($value, array('membership_id' => $membership->id)));
             } else {
                 $membership = CRM_Member_BAO_Membership::create($value, CRM_Core_DAO::$_nullArray);
             }
             //process premiums
             if (!empty($value['product_name'])) {
                 if ($value['product_name'][0] > 0) {
                     list($products, $options) = CRM_Contribute_BAO_Premium::getPremiumProductInfo();
                     $value['hidden_Premium'] = 1;
                     $value['product_option'] = CRM_Utils_Array::value($value['product_name'][1], $options[$value['product_name'][0]]);
                     $premiumParams = array('product_id' => $value['product_name'][0], 'contribution_id' => $value['contribution_id'], 'product_option' => $value['product_option'], 'quantity' => 1);
                     CRM_Contribute_BAO_Contribution::addPremium($premiumParams);
                 }
             }
             // end of premium
             //send receipt mail.
             if ($membership->id && !empty($value['send_receipt'])) {
                 // add the domain email id
                 $domainEmail = CRM_Core_BAO_Domain::getNameAndEmail();
                 $domainEmail = "{$domainEmail['0']} <{$domainEmail['1']}>";
                 $value['from_email_address'] = $domainEmail;
                 $value['membership_id'] = $membership->id;
                 CRM_Member_Form_Membership::emailReceipt($this, $value, $membership);
             }
         }
     }
     return TRUE;
 }
Ejemplo n.º 26
0
 /**
  * Process the form.
  */
 public function postProcess()
 {
     // get the submitted form values.
     $params = $this->controller->exportValues($this->_name);
     // we do this in case the user has hit the forward/back button
     if ($this->_id) {
         $params['id'] = $this->_id;
     } else {
         $session = CRM_Core_Session::singleton();
         $params['created_id'] = $session->get('userID');
         $params['created_date'] = date('YmdHis');
         $config = CRM_Core_Config::singleton();
         $params['currency'] = $config->defaultCurrency;
     }
     $params['is_confirm_enabled'] = CRM_Utils_Array::value('is_confirm_enabled', $params, FALSE);
     $params['is_share'] = CRM_Utils_Array::value('is_share', $params, FALSE);
     $params['is_active'] = CRM_Utils_Array::value('is_active', $params, FALSE);
     $params['is_credit_card_only'] = CRM_Utils_Array::value('is_credit_card_only', $params, FALSE);
     $params['honor_block_is_active'] = CRM_Utils_Array::value('honor_block_is_active', $params, FALSE);
     $params['is_for_organization'] = !empty($params['is_organization']) ? CRM_Utils_Array::value('is_for_organization', $params, FALSE) : 0;
     $params['start_date'] = CRM_Utils_Date::processDate($params['start_date'], $params['start_date_time'], TRUE);
     $params['end_date'] = CRM_Utils_Date::processDate($params['end_date'], $params['end_date_time'], TRUE);
     $params['goal_amount'] = CRM_Utils_Rule::cleanMoney($params['goal_amount']);
     if (!$params['honor_block_is_active']) {
         $params['honor_block_title'] = NULL;
         $params['honor_block_text'] = NULL;
     }
     $dao = CRM_Contribute_BAO_ContributionPage::create($params);
     $ufJoinParams = array('is_organization' => array('module' => 'on_behalf', 'entity_table' => 'civicrm_contribution_page', 'entity_id' => $dao->id), 'honor_block_is_active' => array('module' => 'soft_credit', 'entity_table' => 'civicrm_contribution_page', 'entity_id' => $dao->id));
     foreach ($ufJoinParams as $index => $ufJoinParam) {
         if (!empty($params[$index])) {
             // first delete all past entries
             CRM_Core_BAO_UFJoin::deleteAll($ufJoinParam);
             $ufJoinParam['uf_group_id'] = $params[$index];
             $ufJoinParam['weight'] = 1;
             $ufJoinParam['is_active'] = 1;
             if ($index == 'honor_block_is_active') {
                 $ufJoinParam['uf_group_id'] = $params['honoree_profile'];
                 $ufJoinParam['module_data'] = CRM_Contribute_BAO_ContributionPage::formatModuleData($params, FALSE, 'soft_credit');
             } else {
                 $ufJoinParam['uf_group_id'] = $params['onbehalf_profile_id'];
                 $ufJoinParam['module_data'] = CRM_Contribute_BAO_ContributionPage::formatModuleData($params, FALSE, 'on_behalf');
             }
             CRM_Core_BAO_UFJoin::create($ufJoinParam);
         } else {
             if ($index == 'honor_block_is_active') {
                 $params['honor_block_title'] = NULL;
                 $params['honor_block_text'] = NULL;
             } else {
                 $params['for_organization'] = NULL;
             }
             //On subsequent honor_block_is_active uncheck, disable(don't delete)
             //that particular honoree profile entry in UFjoin table, CRM-13981
             $ufId = CRM_Core_BAO_UFJoin::findJoinEntryId($ufJoinParam);
             if ($ufId) {
                 $ufJoinParam['uf_group_id'] = CRM_Core_BAO_UFJoin::findUFGroupId($ufJoinParam);
                 $ufJoinParam['is_active'] = 0;
                 CRM_Core_BAO_UFJoin::create($ufJoinParam);
             }
         }
     }
     $this->set('id', $dao->id);
     if ($this->_action & CRM_Core_Action::ADD) {
         $url = 'civicrm/admin/contribute/amount';
         $urlParams = "action=update&reset=1&id={$dao->id}";
         // special case for 'Save and Done' consistency.
         if ($this->controller->getButtonName('submit') == '_qf_Amount_upload_done') {
             $url = 'civicrm/admin/contribute';
             $urlParams = 'reset=1';
             CRM_Core_Session::setStatus(ts("'%1' information has been saved.", array(1 => $this->getTitle())), ts('Saved'), 'success');
         }
         CRM_Utils_System::redirect(CRM_Utils_System::url($url, $urlParams));
     }
     parent::endPostProcess();
 }
Ejemplo n.º 27
0
 /**
  * Process the form
  *
  * @return void
  * @access public
  */
 public function postProcess()
 {
     // get the submitted form values.
     $params = $this->controller->exportValues($this->_name);
     if (CRM_Utils_Array::value('payment_processor_id', $params) == CRM_Core_DAO::getFieldValue('CRM_Core_DAO_PaymentProcessor', 'AuthNet', 'id', 'payment_processor_type')) {
         CRM_Core_Session::setStatus(ts(' Please note that the Authorize.net payment processor only allows recurring contributions and auto-renew memberships with payment intervals from 7-365 days or 1-12 months (i.e. not greater than 1 year).'));
     }
     // check for price set.
     $priceSetID = CRM_Utils_Array::value('price_set_id', $params);
     // get required fields.
     $fields = array('id' => $this->_id, 'is_recur' => false, 'min_amount' => "null", 'max_amount' => "null", 'is_monetary' => false, 'is_pay_later' => false, 'is_recur_interval' => false, 'recur_frequency_unit' => "null", 'default_amount_id' => "null", 'is_allow_other_amount' => false, 'amount_block_is_active' => false);
     $resetFields = array();
     if ($priceSetID) {
         $resetFields = array('min_amount', 'max_amount', 'is_allow_other_amount');
     }
     if (!CRM_Utils_Array::value('is_recur', $params)) {
         $resetFields = array_merge($resetFields, array('is_recur_interval', 'recur_frequency_unit'));
     }
     foreach ($fields as $field => $defaultVal) {
         $val = CRM_Utils_Array::value($field, $params, $defaultVal);
         if (in_array($field, $resetFields)) {
             $val = $defaultVal;
         }
         if (in_array($field, array('min_amount', 'max_amount'))) {
             $val = CRM_Utils_Rule::cleanMoney($val);
         }
         $params[$field] = $val;
     }
     if ($params['is_recur']) {
         require_once 'CRM/Core/BAO/CustomOption.php';
         $params['recur_frequency_unit'] = implode(CRM_Core_BAO_CustomOption::VALUE_SEPERATOR, array_keys($params['recur_frequency_unit']));
         $params['is_recur_interval'] = CRM_Utils_Array::value('is_recur_interval', $params, false);
     }
     require_once 'CRM/Contribute/BAO/ContributionPage.php';
     $contributionPage = CRM_Contribute_BAO_ContributionPage::create($params);
     $contributionPageID = $contributionPage->id;
     // prepare for data cleanup.
     $deleteAmountBlk = $deletePledgeBlk = $deletePriceSet = false;
     if ($this->_priceSetID) {
         $deletePriceSet = true;
     }
     if ($this->_pledgeBlockID) {
         $deletePledgeBlk = true;
     }
     if (!empty($this->_amountBlock)) {
         $deleteAmountBlk = true;
     }
     if ($contributionPageID) {
         require_once 'CRM/Price/BAO/Set.php';
         require_once 'CRM/Core/OptionGroup.php';
         require_once 'CRM/Pledge/BAO/PledgeBlock.php';
         if (CRM_Utils_Array::value('amount_block_is_active', $params)) {
             // handle price set.
             if ($priceSetID) {
                 // add/update price set.
                 $deletePriceSet = false;
                 CRM_Price_BAO_Set::addTo('civicrm_contribution_page', $contributionPageID, $priceSetID);
             } else {
                 // process contribution amount block
                 $deleteAmountBlk = false;
                 $labels = CRM_Utils_Array::value('label', $params);
                 $values = CRM_Utils_Array::value('value', $params);
                 $default = CRM_Utils_Array::value('default', $params);
                 $options = array();
                 for ($i = 1; $i < self::NUM_OPTION; $i++) {
                     if (isset($values[$i]) && strlen(trim($values[$i])) > 0) {
                         $options[] = array('label' => trim($labels[$i]), 'value' => CRM_Utils_Rule::cleanMoney(trim($values[$i])), 'weight' => $i, 'is_active' => 1, 'is_default' => $default == $i);
                     }
                 }
                 CRM_Core_OptionGroup::createAssoc("civicrm_contribution_page.amount.{$contributionPageID}", $options, $params['default_amount_id']);
                 if ($params['default_amount_id']) {
                     CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_ContributionPage', $contributionPageID, 'default_amount_id', $params['default_amount_id']);
                 }
                 if (CRM_Utils_Array::value('is_pledge_active', $params)) {
                     $deletePledgeBlk = false;
                     $pledgeBlockParams = array('entity_id' => $contributionPageID, 'entity_table' => ts('civicrm_contribution_page'));
                     if ($this->_pledgeBlockID) {
                         $pledgeBlockParams['id'] = $this->_pledgeBlockID;
                     }
                     $pledgeBlock = array('pledge_frequency_unit', 'max_reminders', 'initial_reminder_day', 'additional_reminder_day');
                     foreach ($pledgeBlock as $key) {
                         $pledgeBlockParams[$key] = CRM_Utils_Array::value($key, $params);
                     }
                     $pledgeBlockParams['is_pledge_interval'] = CRM_Utils_Array::value('is_pledge_interval', $params, false);
                     // create pledge block.
                     require_once 'CRM/Pledge/BAO/PledgeBlock.php';
                     CRM_Pledge_BAO_PledgeBlock::create($pledgeBlockParams);
                 }
             }
         }
         // delete pledge block.
         if ($deletePledgeBlk) {
             CRM_Pledge_BAO_PledgeBlock::deletePledgeBlock($this->_pledgeBlockID);
         }
         // delete previous price set.
         if ($deletePriceSet) {
             CRM_Price_BAO_Set::removeFrom('civicrm_contribution_page', $contributionPageID);
         }
         // delete amount block.
         if ($deleteAmountBlk) {
             CRM_Core_OptionGroup::deleteAssoc("civicrm_contribution_page.amount.{$contributionPageID}");
         }
     }
 }
 /**
  * Function to process the form
  *
  * @access public
  *
  * @return None
  */
 public function postProcess()
 {
     if ($this->_action & CRM_Core_Action::DELETE) {
         CRM_Utils_Weight::delWeight('CRM_Member_DAO_MembershipType', $this->_id);
         CRM_Member_BAO_MembershipType::del($this->_id);
         CRM_Core_Session::setStatus(ts('Selected membership type has been deleted.'));
     } else {
         $buttonName = $this->controller->getButtonName();
         $submitted = $this->controller->exportValues($this->_name);
         $this->set('searchDone', 0);
         if ($buttonName == '_qf_MembershipType_refresh') {
             $this->search($submitted);
             $this->set('searchDone', 1);
             return;
         }
         $fields = array('name', 'weight', 'is_active', 'member_org', 'visibility', 'period_type', 'minimum_fee', 'description', 'auto_renew', 'autorenewal_msg_id', 'duration_unit', 'renewal_msg_id', 'duration_interval', 'renewal_reminder_day', 'contribution_type_id', 'fixed_period_start_day', 'fixed_period_rollover_day');
         $params = $ids = array();
         foreach ($fields as $fld) {
             $params[$fld] = CRM_Utils_Array::value($fld, $submitted, 'NULL');
         }
         //clean money.
         if ($params['minimum_fee']) {
             $params['minimum_fee'] = CRM_Utils_Rule::cleanMoney($params['minimum_fee']);
         }
         $hasRelTypeVal = FALSE;
         if (!CRM_Utils_System::isNull($submitted['relationship_type_id'])) {
             // To insert relation ids and directions with value separator
             $relTypeDirs = $submitted['relationship_type_id'];
             $relIds = $relDirection = array();
             foreach ($relTypeDirs as $key => $value) {
                 $relationId = explode('_', $value);
                 if (count($relationId) == 3 && is_numeric($relationId[0])) {
                     $relIds[] = $relationId[0];
                     $relDirection[] = $relationId[1] . '_' . $relationId[2];
                 }
             }
             if (!empty($relIds)) {
                 $hasRelTypeVal = TRUE;
                 $params['relationship_type_id'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, $relIds);
                 $params['relationship_direction'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, $relDirection);
             }
         }
         if (!$hasRelTypeVal) {
             $params['relationship_type_id'] = $params['relationship_direction'] = 'NULL';
         }
         if ($params['duration_unit'] == 'lifetime' && empty($params['duration_interval'])) {
             $params['duration_interval'] = 1;
         }
         $config = CRM_Core_Config::singleton();
         $periods = array('fixed_period_start_day', 'fixed_period_rollover_day');
         foreach ($periods as $per) {
             if (CRM_Utils_Array::value('M', $params[$per]) && CRM_Utils_Array::value('d', $params[$per])) {
                 $mon = $params[$per]['M'];
                 $dat = $params[$per]['d'];
                 $mon = $mon < 9 ? '0' . $mon : $mon;
                 $dat = $dat < 9 ? '0' . $dat : $dat;
                 $params[$per] = $mon . $dat;
             } else {
                 $params[$per] = 'NULL';
             }
         }
         $oldWeight = NULL;
         $ids['memberOfContact'] = CRM_Utils_Array::value('contact_check', $submitted);
         if ($this->_id) {
             $oldWeight = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $this->_id, 'weight', 'id');
         }
         $params['weight'] = CRM_Utils_Weight::updateOtherWeights('CRM_Member_DAO_MembershipType', $oldWeight, $params['weight']);
         if ($this->_action & CRM_Core_Action::UPDATE) {
             $ids['membershipType'] = $this->_id;
         }
         $membershipType = CRM_Member_BAO_MembershipType::add($params, $ids);
         CRM_Core_Session::setStatus(ts('The membership type \'%1\' has been saved.', array(1 => $membershipType->name)));
         $session = CRM_Core_Session::singleton();
         if ($buttonName == $this->getButtonName('upload', 'new')) {
             CRM_Core_Session::setStatus(ts(' You can add another membership type.'));
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/admin/member/membershipType', 'action=add&reset=1'));
         }
     }
 }
Ejemplo n.º 29
0
 /**
  * Process the form
  * 
  * @param null
  * 
  * @return void
  * @access public
  */
 public function postProcess()
 {
     // store the submitted values in an array
     $params = $this->controller->exportValues('Option');
     // set values for custom field properties and save
     require_once 'CRM/Core/DAO/OptionValue.php';
     require_once 'CRM/Utils/String.php';
     $customOption =& new CRM_Core_DAO_OptionValue();
     $customOption->label = $params['label'];
     $customOption->name = CRM_Utils_String::titleToVar($params['label']);
     $customOption->weight = $params['weight'];
     $customOption->value = $params['value'];
     $customOption->is_active = CRM_Utils_Array::value('is_active', $params, false);
     if ($this->_action == CRM_Core_Action::DELETE) {
         $fieldValues = array('option_group_id' => $this->_optionGroupID);
         $wt = CRM_Utils_Weight::delWeight('CRM_Core_DAO_OptionValue', $this->_id, $fieldValues);
         CRM_Core_BAO_CustomOption::del($this->_id);
         CRM_Core_Session::setStatus(ts('Your multiple choice option has been deleted', array(1 => $customOption->label)));
         return;
     }
     if ($this->_action & CRM_Core_Action::UPDATE) {
         $customOption->id = $this->_id;
         CRM_Core_BAO_CustomOption::updateCustomValues($params);
     }
     if ($this->_id) {
         $oldWeight = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionValue', $this->_id, 'weight', 'id');
     }
     $fieldValues = array('option_group_id' => $this->_optionGroupID);
     $customOption->weight = CRM_Utils_Weight::updateOtherWeights('CRM_Core_DAO_OptionValue', $oldWeight, $params['weight'], $fieldValues);
     $customOption->option_group_id = $this->_optionGroupID;
     $customField =& new CRM_Core_DAO_CustomField();
     $customField->id = $this->_fid;
     if ($customField->find(true) && ($customField->html_type == 'CheckBox' || $customField->html_type == 'AdvMulti-Select' || $customField->html_type == 'Multi-Select')) {
         $defVal = explode(CRM_Core_BAO_CustomOption::VALUE_SEPERATOR, substr($customField->default_value, 1, -1));
         if (CRM_Utils_Array::value('default_value', $params)) {
             if (!in_array($customOption->value, $defVal)) {
                 if (empty($defVal[0])) {
                     $defVal = array($customOption->value);
                 } else {
                     $defVal[] = $customOption->value;
                 }
                 $customField->default_value = CRM_Core_BAO_CustomOption::VALUE_SEPERATOR . implode(CRM_Core_BAO_CustomOption::VALUE_SEPERATOR, $defVal) . CRM_Core_BAO_CustomOption::VALUE_SEPERATOR;
                 $customField->save();
             }
         } else {
             if (in_array($customOption->value, $defVal)) {
                 $tempVal = array();
                 foreach ($defVal as $v) {
                     if ($v != $customOption->value) {
                         $tempVal[] = $v;
                     }
                 }
                 $customField->default_value = CRM_Core_BAO_CustomOption::VALUE_SEPERATOR . implode(CRM_Core_BAO_CustomOption::VALUE_SEPERATOR, $tempVal) . CRM_Core_BAO_CustomOption::VALUE_SEPERATOR;
                 $customField->save();
             }
         }
     } else {
         switch ($customField->data_type) {
             case 'Money':
                 require_once 'CRM/Utils/Rule.php';
                 $customOption->value = CRM_Utils_Rule::cleanMoney($customOption->value);
                 break;
             case 'Int':
                 $customOption->value = intval($customOption->value);
                 break;
             case 'Float':
                 $customOption->value = floatval($customOption->value);
                 break;
         }
         if (CRM_Utils_Array::value('default_value', $params)) {
             $customField->default_value = $customOption->value;
             $customField->save();
         } else {
             if ($customField->find(true) && $customField->default_value == $customOption->value) {
                 // this is the case where this option is the current default value and we have been reset
                 $customField->default_value = 'null';
                 $customField->save();
             }
         }
     }
     $customOption->save();
     CRM_Core_Session::setStatus(ts('Your multiple choice option \'%1\' has been saved', array(1 => $customOption->label)));
     $buttonName = $this->controller->getButtonName();
     $session =& CRM_Core_Session::singleton();
     if ($buttonName == $this->getButtonName('next', 'new')) {
         CRM_Core_Session::setStatus(ts(' You can add another option.'));
         $session->replaceUserContext(CRM_Utils_System::url('civicrm/admin/custom/group/field/option', 'reset=1&action=add&fid=' . $this->_fid . '&gid=' . $this->_gid));
     }
 }
Ejemplo n.º 30
0
 /**
  * Generate the where clause and also the english language.
  * equivalent
  *
  * @return void
  */
 public function where()
 {
     foreach ($this->_ids as $id => $values) {
         // Fixed for Isuue CRM 607
         if (CRM_Utils_Array::value($id, $this->_fields) === NULL || !$values) {
             continue;
         }
         $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
         foreach ($values as $tuple) {
             list($name, $op, $value, $grouping, $wildcard) = $tuple;
             $field = $this->_fields[$id];
             $fieldName = "{$field['table_name']}.{$field['column_name']}";
             // Autocomplete comes back as a string not an array
             if ($field['data_type'] == 'String' && $field['html_type'] == 'Autocomplete-Select' && $op == '=') {
                 $value = explode(',', $value);
             }
             $isSerialized = CRM_Core_BAO_CustomField::isSerialized($field);
             // fix $value here to escape sql injection attacks
             $qillValue = NULL;
             if (!is_array($value)) {
                 $value = CRM_Core_DAO::escapeString(trim($value));
                 $qillValue = CRM_Core_BAO_CustomField::getDisplayValue($value, $id, $this->_options);
             } elseif (count($value) && in_array(key($value), CRM_Core_DAO::acceptedSQLOperators(), TRUE)) {
                 $op = key($value);
                 $qillValue = CRM_Core_BAO_CustomField::getDisplayValue($value[$op], $id, $this->_options);
             } else {
                 $op = 'IN';
                 $qillValue = CRM_Core_BAO_CustomField::getDisplayValue($value, $id, $this->_options);
             }
             $qillOp = CRM_Utils_Array::value($op, CRM_Core_SelectValues::getSearchBuilderOperators(), $op);
             switch ($field['data_type']) {
                 case 'String':
                 case 'StateProvince':
                 case 'Country':
                     if ($field['is_search_range'] && is_array($value)) {
                         $this->searchRange($field['id'], $field['label'], $field['data_type'], $fieldName, $value, $grouping);
                     } else {
                         // fix $value here to escape sql injection attacks
                         if (!is_array($value)) {
                             if ($field['data_type'] == 'String') {
                                 $value = CRM_Utils_Type::escape($strtolower($value), 'String');
                             } else {
                                 $value = CRM_Utils_Type::escape($value, 'Integer');
                             }
                         } elseif ($isSerialized) {
                             if (in_array(key($value), CRM_Core_DAO::acceptedSQLOperators(), TRUE)) {
                                 $op = key($value);
                                 $value = $value[$op];
                             }
                             $value = implode(',', $value);
                         }
                         // CRM-14563,CRM-16575 : Special handling of multi-select custom fields
                         if ($isSerialized && !empty($value)) {
                             if (strstr($op, 'IN')) {
                                 $value = str_replace(",", "[[:cntrl:]]*|[[:cntrl:]]*", $value);
                                 $value = str_replace('(', '[[.left-parenthesis.]]', $value);
                                 $value = str_replace(')', '[[.right-parenthesis.]]', $value);
                             }
                             $op = strstr($op, '!') || strstr($op, 'NOT') ? 'NOT RLIKE' : 'RLIKE';
                             $value = "[[:cntrl:]]*" . $value . "[[:cntrl:]]*";
                             if (!$wildcard) {
                                 $value = str_replace("[[:cntrl:]]*|", '', $value);
                             }
                         }
                         //FIX for custom data query fired against no value(NULL/NOT NULL)
                         $this->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause($fieldName, $op, $value, 'String');
                         $this->_qill[$grouping][] = "{$field['label']} {$qillOp} {$qillValue}";
                     }
                     break;
                 case 'ContactReference':
                     $label = $value ? CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $value, 'sort_name') : '';
                     $this->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause($fieldName, $op, $value, 'String');
                     $this->_qill[$grouping][] = $field['label'] . " {$qillOp} {$label}";
                     break;
                 case 'Int':
                     if ($field['is_search_range'] && is_array($value)) {
                         $this->searchRange($field['id'], $field['label'], $field['data_type'], $fieldName, $value, $grouping);
                     } else {
                         $this->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause($fieldName, $op, $value, 'Integer');
                         $this->_qill[$grouping][] = ts("%1 %2 %3", array(1 => $field['label'], 2 => $qillOp, 3 => $qillValue));
                     }
                     break;
                 case 'Boolean':
                     if (!is_array($value)) {
                         if (strtolower($value) == 'yes' || strtolower($value) == strtolower(ts('Yes'))) {
                             $value = 1;
                         } else {
                             $value = (int) $value;
                         }
                         $value = $value == 1 ? 1 : 0;
                         $qillValue = $value ? 'Yes' : 'No';
                     }
                     $this->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause($fieldName, $op, $value, 'Integer');
                     $this->_qill[$grouping][] = ts("%1 %2 %3", array(1 => $field['label'], 2 => $qillOp, 3 => $qillValue));
                     break;
                 case 'Link':
                 case 'Memo':
                     $this->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause($fieldName, $op, $value, 'String');
                     $this->_qill[$grouping][] = ts("%1 %2 %3", array(1 => $field['label'], 2 => $qillOp, 3 => $qillValue));
                     break;
                 case 'Money':
                     if (is_array($value)) {
                         $value = CRM_Utils_Array::value($op, $value, $value);
                         foreach ($value as $key => $val) {
                             $moneyFormat = CRM_Utils_Rule::cleanMoney($value[$key]);
                             $value[$key] = $moneyFormat;
                         }
                     } else {
                         $value = CRM_Utils_Rule::cleanMoney($value);
                     }
                 case 'Float':
                     if ($field['is_search_range']) {
                         $this->searchRange($field['id'], $field['label'], $field['data_type'], $fieldName, $value, $grouping);
                     } else {
                         $this->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause($fieldName, $op, $value, 'Float');
                         $this->_qill[$grouping][] = ts("%1 %2 %3", array(1 => $field['label'], 2 => $qillOp, 3 => $qillValue));
                     }
                     break;
                 case 'Date':
                     $fromValue = CRM_Utils_Array::value('from', $value);
                     $toValue = CRM_Utils_Array::value('to', $value);
                     if (!$fromValue && !$toValue) {
                         if (!CRM_Utils_Date::processDate($value) && !in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
                             continue;
                         }
                         // hack to handle yy format during search
                         if (is_numeric($value) && strlen($value) == 4) {
                             $value = "01-01-{$value}";
                         }
                         $date = CRM_Utils_Date::processDate($value);
                         $this->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause($fieldName, $op, $date, 'String');
                         $this->_qill[$grouping][] = $field['label'] . " {$qillOp} " . CRM_Utils_Date::customFormat($date);
                     } else {
                         if (is_numeric($fromValue) && strlen($fromValue) == 4) {
                             $fromValue = "01-01-{$fromValue}";
                         }
                         if (is_numeric($toValue) && strlen($toValue) == 4) {
                             $toValue = "01-01-{$toValue}";
                         }
                         // TO DO: add / remove time based on date parts
                         $fromDate = CRM_Utils_Date::processDate($fromValue);
                         $toDate = CRM_Utils_Date::processDate($toValue);
                         if (!$fromDate && !$toDate) {
                             continue;
                         }
                         if ($fromDate) {
                             $this->_where[$grouping][] = "{$fieldName} >= {$fromDate}";
                             $this->_qill[$grouping][] = $field['label'] . ' >= ' . CRM_Utils_Date::customFormat($fromDate);
                         }
                         if ($toDate) {
                             $this->_where[$grouping][] = "{$fieldName} <= {$toDate}";
                             $this->_qill[$grouping][] = $field['label'] . ' <= ' . CRM_Utils_Date::customFormat($toDate);
                         }
                     }
                     break;
                 case 'File':
                     if ($op == 'IS NULL' || $op == 'IS NOT NULL' || $op == 'IS EMPTY' || $op == 'IS NOT EMPTY') {
                         switch ($op) {
                             case 'IS EMPTY':
                                 $op = 'IS NULL';
                                 break;
                             case 'IS NOT EMPTY':
                                 $op = 'IS NOT NULL';
                                 break;
                         }
                         $this->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause($fieldName, $op);
                         $this->_qill[$grouping][] = $field['label'] . " {$qillOp} ";
                     }
                     break;
             }
         }
     }
 }