/** * format a monetary string * * Format a monetary string basing on the amount provided, * ISO currency code provided and a format string consisting of: * * %a - the formatted amount * %C - the currency ISO code (e.g., 'USD') if provided * %c - the currency symbol (e.g., '$') if available * * @param float $amount the monetary amount to display (1234.56) * @param string $currency the three-letter ISO currency code ('USD') * @param string $format the desired currency format * * @return string formatted monetary string * * @static */ static function format($amount, $currency = null, $format = null) { if (CRM_Utils_System::isNull($amount)) { return ''; } $config =& CRM_Core_Config::singleton(); if (!self::$_currencySymbols) { require_once "CRM/Core/PseudoConstant.php"; $currencySymbolName = CRM_Core_PseudoConstant::currencySymbols('name'); $currencySymbol = CRM_Core_PseudoConstant::currencySymbols(); self::$_currencySymbols = array_combine($currencySymbolName, $currencySymbol); } if (!$currency) { $currency = $config->defaultCurrency; } if (!$format) { $format = $config->moneyformat; } // money_format() exists only in certain PHP install (CRM-650) if (is_numeric($amount) and function_exists('money_format')) { $amount = money_format($config->moneyvalueformat, $amount); } $replacements = array('%a' => $amount, '%C' => $currency, '%c' => CRM_Utils_Array::value($currency, self::$_currencySymbols, $currency)); return strtr($format, $replacements); }
/** * format a monetary string * * Format a monetary string basing on the amount provided, * ISO currency code provided and a format string consisting of: * * %a - the formatted amount * %C - the currency ISO code (e.g., 'USD') if provided * %c - the currency symbol (e.g., '$') if available * * @param float $amount the monetary amount to display (1234.56) * @param string $currency the three-letter ISO currency code ('USD') * @param string $format the desired currency format * * @return string formatted monetary string * * @static */ function format($amount, $currency = null, $format = null) { if (CRM_Utils_System::isNull($amount)) { return ''; } if (!$GLOBALS['_CRM_UTILS_MONEY']['currencySymbols']) { $GLOBALS['_CRM_UTILS_MONEY']['currencySymbols'] = array('EUR' => '€', 'GBP' => '£', 'ILS' => '₪', 'JPY' => '¥', 'KRW' => '₩', 'LAK' => '₭', 'MNT' => '₮', 'NGN' => '₦', 'PLN' => 'zł', 'THB' => '฿', 'USD' => '$', 'VND' => '₫'); } if (!$currency) { if (!$GLOBALS['_CRM_UTILS_MONEY']['config']) { $GLOBALS['_CRM_UTILS_MONEY']['config'] =& CRM_Core_Config::singleton(); } $currency = $GLOBALS['_CRM_UTILS_MONEY']['config']->defaultCurrency; } if (!$format) { if (!$GLOBALS['_CRM_UTILS_MONEY']['config']) { $GLOBALS['_CRM_UTILS_MONEY']['config'] =& CRM_Core_Config::singleton(); } $format = $GLOBALS['_CRM_UTILS_MONEY']['config']->moneyformat; } $money = $amount; // this function exists only in certain php install (CRM-650) if (function_exists('money_format')) { $money = money_format('%!i', $amount); } $replacements = array('%a' => $money, '%C' => $currency, '%c' => CRM_Utils_Array::value($currency, $GLOBALS['_CRM_UTILS_MONEY']['currencySymbols'], $currency)); return strtr($format, $replacements); }
/** * Browse all saved searches. * * @return mixed * content of the parents run method */ public function browse() { $rows = array(); $savedSearch = new CRM_Contact_DAO_SavedSearch(); $savedSearch->is_active = 1; $savedSearch->selectAdd(); $savedSearch->selectAdd('id, form_values'); $savedSearch->find(); $properties = array('id', 'name', 'description'); while ($savedSearch->fetch()) { // get name and description from group object $group = new CRM_Contact_DAO_Group(); $group->saved_search_id = $savedSearch->id; if ($group->find(TRUE)) { $permissions = CRM_Group_Page_Group::checkPermission($group->id, $group->title); if (!CRM_Utils_System::isNull($permissions)) { $row = array(); $row['name'] = $group->title; $row['description'] = $group->description; $row['id'] = $savedSearch->id; $formValues = unserialize($savedSearch->form_values); $query = new CRM_Contact_BAO_Query($formValues); $row['query_detail'] = $query->qill(); $action = array_sum(array_keys(self::links())); $action = $action & CRM_Core_Action::mask($permissions); $row['action'] = CRM_Core_Action::formLink(self::links(), $action, array('id' => $row['id']), ts('more'), FALSE, 'savedSearch.manage.action', 'SavedSearch', $row['id']); $rows[] = $row; } } } $this->assign('rows', $rows); return parent::run(); }
public function postProcess() { $params = $this->controller->exportValues($this->_name); $parent = $this->controller->getParent(); $parent->set('searchResult', 1); if (!empty($params)) { $fields = array('id', 'title', 'event_type_id', 'start_date', 'end_date', 'eventsByDates', 'campaign_id'); $sql = "SELECT f.column_name\n FROM civicrm_custom_field f\n LEFT JOIN civicrm_custom_group g ON g.id = f.custom_group_id\n WHERE g.name = 'Courses'"; $dao = CRM_Core_DAO::executeQuery($sql); while ($dao->fetch()) { $courses[] = $dao->column_name; } $fields = array_merge($fields, $courses); foreach ($fields as $field) { if (isset($params[$field]) && !CRM_Utils_System::isNull($params[$field])) { if (substr($field, -4) == 'date') { $time = $field == 'end_date' ? '235959' : NULL; $parent->set($field, CRM_Utils_Date::processDate($params[$field], $time)); } else { $parent->set($field, $params[$field]); } } else { $parent->set($field, NULL); } } } }
function validate() { if (CRM_Utils_System::isNull($this->_value)) { return true; } switch ($this->_name) { case 'contact_id': // note: we validate extistence of the contact in API, upon // insert (it would be too costlty to do a db call here) return CRM_Utils_Rule::integer($this->_value); break; case 'register_date': return CRM_Utils_Rule::date($this->_value); break; /* case 'event_id': static $events = null; if (!$events) { $events =& CRM_Event_PseudoConstant::event(); } if (in_array($this->_value, $events)) { return true; } else { return false; } break; */ /* case 'event_id': static $events = null; if (!$events) { $events =& CRM_Event_PseudoConstant::event(); } if (in_array($this->_value, $events)) { return true; } else { return false; } break; */ default: break; } // check whether that's a valid custom field id // and if so, check the contents' validity if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($this->_name)) { static $customFields = null; if (!$customFields) { $customFields =& CRM_Core_BAO_CustomField::getFields('Membership'); } if (!array_key_exists($customFieldID, $customFields)) { return false; } return CRM_Core_BAO_CustomValue::typecheck($customFields[$customFieldID]['data_type'], $this->_value); } return true; }
/** * Function to set variables up before form is built * * @return void * @access public */ public function preProcess() { require_once 'CRM/Event/BAO/Participant.php'; $values = $ids = array(); $participantID = CRM_Utils_Request::retrieve('id', 'Positive', $this, true); $contactID = CRM_Utils_Request::retrieve('cid', 'Positive', $this, true); $params = array('id' => $participantID); CRM_Event_BAO_Participant::getValues($params, $values, $ids); if (empty($values)) { require_once 'CRM/Core/Error.php'; CRM_Core_Error::statusBounce(ts('The requested participant record does not exist (possibly the record was deleted).')); } CRM_Event_BAO_Participant::resolveDefaults($values[$participantID]); if (CRM_Utils_Array::value('fee_level', $values[$participantID])) { CRM_Event_BAO_Participant::fixEventLevel($values[$participantID]['fee_level']); } if ($values[$participantID]['is_test']) { $values[$participantID]['status'] .= ' (test) '; } // Get Note $noteValue = CRM_Core_BAO_Note::getNote($participantID, 'civicrm_participant'); $values[$participantID]['note'] = array_values($noteValue); require_once 'CRM/Price/BAO/LineItem.php'; // Get Line Items $lineItem = CRM_Price_BAO_LineItem::getLineItems($participantID); if (!CRM_Utils_System::isNull($lineItem)) { $values[$participantID]['lineItem'][] = $lineItem; } $values[$participantID]['totalAmount'] = $values[$participantID]['fee_amount']; // get the option value for custom data type $roleCustomDataTypeID = CRM_Core_OptionGroup::getValue('custom_data_type', 'ParticipantRole', 'name'); $eventNameCustomDataTypeID = CRM_Core_OptionGroup::getValue('custom_data_type', 'ParticipantEventName', 'name'); $eventTypeCustomDataTypeID = CRM_Core_OptionGroup::getValue('custom_data_type', 'ParticipantEventType', 'name'); $roleGroupTree =& CRM_Core_BAO_CustomGroup::getTree('Participant', $this, $participantID, null, $values[$participantID]['role_id'], $roleCustomDataTypeID); $eventGroupTree =& CRM_Core_BAO_CustomGroup::getTree('Participant', $this, $participantID, null, $values[$participantID]['event_id'], $eventNameCustomDataTypeID); $eventTypeID = CRM_Core_DAO::getFieldValue("CRM_Event_DAO_Event", $values[$participantID]['event_id'], 'event_type_id', 'id'); $eventTypeGroupTree =& CRM_Core_BAO_CustomGroup::getTree('Participant', $this, $participantID, null, $eventTypeID, $eventTypeCustomDataTypeID); $groupTree = CRM_Utils_Array::crmArrayMerge($roleGroupTree, $eventGroupTree); $groupTree = CRM_Utils_Array::crmArrayMerge($groupTree, $eventTypeGroupTree); $groupTree = CRM_Utils_Array::crmArrayMerge($groupTree, CRM_Core_BAO_CustomGroup::getTree('Participant', $this, $participantID)); CRM_Core_BAO_CustomGroup::buildCustomDataView($this, $groupTree); $this->assign($values[$participantID]); // add viewed participant to recent items list require_once 'CRM/Utils/Recent.php'; require_once 'CRM/Contact/BAO/Contact.php'; $url = CRM_Utils_System::url('civicrm/contact/view/participant', "action=view&reset=1&id={$values[$participantID]['id']}&cid={$values[$participantID]['contact_id']}&context=home"); $participantRoles = CRM_Event_PseudoConstant::participantRole(); $eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $values[$participantID]['event_id'], 'title'); $displayName = CRM_Contact_BAO_Contact::displayName($contactID); $this->assign('displayName', $displayName); $title = $displayName . ' (' . $participantRoles[$values[$participantID]['role_id']] . ' - ' . $eventTitle . ')'; // add Participant to Recent Items CRM_Utils_Recent::add($title, $url, $values[$participantID]['id'], 'Participant', $values[$participantID]['contact_id'], null); }
/** * Determine whether a schedule based on this mapping is sufficiently * complete. * * @param \CRM_Core_DAO_ActionSchedule $schedule * @return array * Array (string $code => string $message). * List of error messages. */ public function validateSchedule($schedule) { $errors = array(); if (CRM_Utils_System::isNull($schedule->entity_value) || $schedule->entity_value === '0') { $errors['entity'] = ts('Please select a specific date field.'); } elseif (count(CRM_Utils_Array::explodePadded($schedule->entity_value)) > 1) { $errors['entity'] = ts('You may only select one contact field per reminder'); } elseif (CRM_Utils_System::isNull($schedule->entity_status) || $schedule->entity_status === '0') { $errors['entity'] = ts('Please select whether the reminder is sent each year.'); } return $errors; }
function validate() { if (CRM_Utils_System::isNull($this->_value)) { return TRUE; } switch ($this->_name) { case 'contact_id': // note: we validate extistence of the contact in API, upon // insert (it would be too costlty to do a db call here) return CRM_Utils_Rule::integer($this->_value); default: break; } }
public function postProcess() { $params = $this->controller->exportValues($this->_name); $parent = $this->controller->getParent(); if (!empty($params)) { $fields = array('title', 'created_by', 'group_type', 'visibility', 'active_status', 'inactive_status'); foreach ($fields as $field) { if (isset($params[$field]) && !CRM_Utils_System::isNull($params[$field])) { $parent->set($field, $params[$field]); } else { $parent->set($field, NULL); } } } }
function postProcess() { $params = $this->controller->exportValues($this->_name); $parent = $this->controller->getParent(); $parent->set('searchResult', 1); if (!empty($params)) { $fields = array('title', 'event_type_id', 'start_date', 'end_date', 'auctionsByDates'); foreach ($fields as $field) { if (isset($params[$field]) && !CRM_Utils_System::isNull($params[$field])) { $parent->set($field, $params[$field]); } else { $parent->set($field, null); } } } }
public function postProcess() { $params = $this->controller->exportValues($this->_name); $parent = $this->controller->getParent(); $parent->set('searchResult', 1); if (!empty($params)) { $fields = array('title', 'financial_type_id', 'campaign_id'); foreach ($fields as $field) { if (isset($params[$field]) && !CRM_Utils_System::isNull($params[$field])) { $parent->set($field, $params[$field]); } else { $parent->set($field, NULL); } } } }
/** * format a monetary string * * Format a monetary string basing on the amount provided, * ISO currency code provided and a format string consisting of: * * %a - the formatted amount * %C - the currency ISO code (e.g., 'USD') if provided * %c - the currency symbol (e.g., '$') if available * * @param float $amount the monetary amount to display (1234.56) * @param string $currency the three-letter ISO currency code ('USD') * @param string $format the desired currency format * * @return string formatted monetary string * * @static */ static function format($amount, $currency = NULL, $format = NULL, $onlyNumber = FALSE) { if (CRM_Utils_System::isNull($amount)) { return ''; } $config = CRM_Core_Config::singleton(); if (!$format) { $format = $config->moneyformat; } if ($onlyNumber) { // money_format() exists only in certain PHP install (CRM-650) if (is_numeric($amount) and function_exists('money_format')) { $amount = money_format($config->moneyvalueformat, $amount); } return $amount; } if (!self::$_currencySymbols) { $currencySymbolName = CRM_Core_PseudoConstant::currencySymbols('name'); $currencySymbol = CRM_Core_PseudoConstant::currencySymbols(); self::$_currencySymbols = array_combine($currencySymbolName, $currencySymbol); } if (!$currency) { $currency = $config->defaultCurrency; } if (!$format) { $format = $config->moneyformat; } // money_format() exists only in certain PHP install (CRM-650) // setlocale() affects native gettext (CRM-11054, CRM-9976) if (is_numeric($amount) && function_exists('money_format')) { $lc = setlocale(LC_MONETARY, 0); setlocale(LC_MONETARY, 'en_US.utf8', 'en_US', 'en_US.utf8', 'en_US', 'C'); $amount = money_format($config->moneyvalueformat, $amount); setlocale(LC_MONETARY, $lc); } $rep = array(',' => $config->monetaryThousandSeparator, '.' => $config->monetaryDecimalPoint); // If it contains tags, means that HTML was passed and the // amount is already converted properly, // so don't mess with it again. if (strip_tags($amount) === $amount) { $money = strtr($amount, $rep); } else { $money = $amount; } $replacements = array('%a' => $money, '%C' => $currency, '%c' => CRM_Utils_Array::value($currency, self::$_currencySymbols, $currency)); return strtr($format, $replacements); }
function postProcess() { $params = $this->controller->exportValues($this->_name); $parent = $this->controller->getParent(); if (!empty($params)) { $fields = array('mailing_name', 'mailing_from', 'mailing_to', 'sort_name'); foreach ($fields as $field) { if (isset($params[$field]) && !CRM_Utils_System::isNull($params[$field])) { if (substr($field, 7) != 'name') { $parent->set($field, CRM_Utils_Date::unformat(CRM_Utils_Date::processDate($params[$field]), '')); } else { $parent->set($field, $params[$field]); } } else { $parent->set($field, null); } } } }
function postProcess() { $params = $this->controller->exportValues($this->_name); $parent = $this->controller->getParent(); $parent->set('searchResult', 1); if (!empty($params)) { $fields = array('title', 'event_type_id', 'start_date', 'end_date', 'eventsByDates', 'campaign_id'); foreach ($fields as $field) { if (isset($params[$field]) && !CRM_Utils_System::isNull($params[$field])) { if (substr($field, -4) == 'date') { $time = $field == 'end_date' ? '235959' : NULL; $parent->set($field, CRM_Utils_Date::processDate($params[$field], $time)); } else { $parent->set($field, $params[$field]); } } else { $parent->set($field, NULL); } } } }
function postProcess() { $params = $this->controller->exportValues($this->_name); CRM_Contact_BAO_Query::fixDateValues($params["mailing_relative"], $params['mailing_from'], $params['mailing_to']); $parent = $this->controller->getParent(); if (!empty($params)) { $fields = array('mailing_name', 'mailing_from', 'mailing_to', 'sort_name', 'campaign_id', 'mailing_status', 'sms'); foreach ($fields as $field) { if (isset($params[$field]) && !CRM_Utils_System::isNull($params[$field])) { if (in_array($field, array('mailing_from', 'mailing_to')) && !$params["mailing_relative"]) { $time = $field == 'mailing_to' ? '235959' : NULL; $parent->set($field, CRM_Utils_Date::processDate($params[$field], $time)); } else { $parent->set($field, $params[$field]); } } else { $parent->set($field, NULL); } } } }
/** * Function to actually build the form * * @return void * @access public */ public function buildQuickForm() { require_once 'CRM/Utils/Money.php'; // do u want to allow a free form text field for amount $this->addElement('checkbox', 'is_allow_other_amount', ts('Allow other amounts'), null, array('onclick' => "minMax(this);showHideAmountBlock( this, 'is_allow_other_amount' );")); $this->add('text', 'min_amount', ts('Minimum Amount'), array('size' => 8, 'maxlength' => 8)); $this->addRule('min_amount', ts('Please enter a valid money value (e.g. %1).', array(1 => CRM_Utils_Money::format('9.99', ' '))), 'money'); $this->add('text', 'max_amount', ts('Maximum Amount'), array('size' => 8, 'maxlength' => 8)); $this->addRule('max_amount', ts('Please enter a valid money value (e.g. %1).', array(1 => CRM_Utils_Money::format('99.99', ' '))), 'money'); $default = array(); for ($i = 1; $i <= self::NUM_OPTION; $i++) { // label $this->add('text', "label[{$i}]", ts('Label'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_OptionValue', 'label')); // value $this->add('text', "value[{$i}]", ts('Value'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_OptionValue', 'value')); $this->addRule("value[{$i}]", ts('Please enter a valid money value (e.g. %1).', array(1 => CRM_Utils_Money::format('99.99', ' '))), 'money'); // default $default[] = $this->createElement('radio', null, null, null, $i); } $this->addGroup($default, 'default'); $this->addElement('checkbox', 'amount_block_is_active', ts('Contribution Amounts section enabled'), null, array('onclick' => "showHideAmountBlock( this, 'amount_block_is_active' );")); $this->addElement('checkbox', 'is_monetary', ts('Execute real-time monetary transactions')); $paymentProcessor =& CRM_Core_PseudoConstant::paymentProcessor(); $recurringPaymentProcessor = array(); if (!empty($paymentProcessor)) { $paymentProcessorIds = implode(',', array_keys($paymentProcessor)); $query = "\nSELECT id\n FROM civicrm_payment_processor\n WHERE id IN ({$paymentProcessorIds})\n AND is_recur = 1"; $dao =& CRM_Core_DAO::executeQuery($query); while ($dao->fetch()) { $recurringPaymentProcessor[] = $dao->id; } } $this->assign('recurringPaymentProcessor', $recurringPaymentProcessor); if (count($paymentProcessor)) { $this->assign('paymentProcessor', $paymentProcessor); } $this->add('select', 'payment_processor_id', ts('Payment Processor'), array('' => ts('- select -')) + $paymentProcessor, null, array('onchange' => "showRecurring( this.value );")); require_once "CRM/Contribute/BAO/ContributionPage.php"; //check if selected payment processor supports recurring payment if (!empty($recurringPaymentProcessor)) { $this->addElement('checkbox', 'is_recur', ts('Recurring contributions'), null, array('onclick' => "showHideByValue('is_recur',true,'recurFields','table-row','radio',false); showRecurInterval( );")); require_once 'CRM/Core/OptionGroup.php'; $this->addCheckBox('recur_frequency_unit', ts('Supported recurring units'), CRM_Core_OptionGroup::values('recur_frequency_units', false, false, false, null, 'name'), null, null, null, null, array(' ', ' ', ' ', '<br/>')); $this->addElement('checkbox', 'is_recur_interval', ts('Support recurring intervals')); } // add pay later options $this->addElement('checkbox', 'is_pay_later', ts('Pay later option'), null, array('onclick' => "payLater(this);")); $this->addElement('textarea', 'pay_later_text', ts('Pay later label'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_ContributionPage', 'pay_later_text'), false); $this->addElement('textarea', 'pay_later_receipt', ts('Pay later instructions'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_ContributionPage', 'pay_later_receipt'), false); // add price set fields require_once 'CRM/Price/BAO/Set.php'; $price = CRM_Price_BAO_Set::getAssoc(false, 'CiviContribute'); if (CRM_Utils_System::isNull($price)) { $this->assign('price', false); } else { $this->assign('price', true); } $this->add('select', 'price_set_id', ts('Price Set'), array('' => ts('- none -')) + $price, null, array('onchange' => "showHideAmountBlock( this.value, 'price_set_id' );")); //CiviPledge fields. $config = CRM_Core_Config::singleton(); if (in_array('CiviPledge', $config->enableComponents)) { $this->assign('civiPledge', true); require_once 'CRM/Core/OptionGroup.php'; $this->addElement('checkbox', 'is_pledge_active', ts('Pledges'), null, array('onclick' => "showHideAmountBlock( this, 'is_pledge_active' ); return showHideByValue('is_pledge_active',true,'pledgeFields','table-row','radio',false);")); $this->addCheckBox('pledge_frequency_unit', ts('Supported pledge frequencies'), CRM_Core_OptionGroup::values("recur_frequency_units", false, false, false, null, 'name'), null, null, null, null, array(' ', ' ', ' ', '<br/>')); $this->addElement('checkbox', 'is_pledge_interval', ts('Allow frequency intervals')); $this->addElement('text', 'initial_reminder_day', ts('Send payment reminder'), array('size' => 3)); $this->addElement('text', 'max_reminders', ts('Send up to'), array('size' => 3)); $this->addElement('text', 'additional_reminder_day', ts('Send additional reminders'), array('size' => 3)); } //add currency element. $this->addCurrency('currency', ts('Currency')); $this->addFormRule(array('CRM_Contribute_Form_ContributionPage_Amount', 'formRule'), $this); parent::buildQuickForm(); }
/** * Get all cases with no end dates * * @param array $params * @param array $excludeCaseIds * @param bool $excludeDeleted * * @return array of case and related data keyed on case id */ static function getUnclosedCases($params = array(), $excludeCaseIds = array(), $excludeDeleted = TRUE, $includeClosed = FALSE) { //params from ajax call. $where = array($includeClosed ? '(1)' : '(ca.end_date is null)'); if ($caseType = CRM_Utils_Array::value('case_type', $params)) { $where[] = "( civicrm_case_type.title LIKE '%{$caseType}%' )"; } if ($sortName = CRM_Utils_Array::value('sort_name', $params)) { $config = CRM_Core_Config::singleton(); $search = $config->includeWildCardInName ? "%{$sortName}%" : "{$sortName}%"; $where[] = "( sort_name LIKE '{$search}' )"; } if ($cid = CRM_Utils_Array::value('contact_id', $params)) { $where[] = " c.id = {$cid} "; } if (is_array($excludeCaseIds) && !CRM_Utils_System::isNull($excludeCaseIds)) { $where[] = ' ( ca.id NOT IN ( ' . implode(',', $excludeCaseIds) . ' ) ) '; } if ($excludeDeleted) { $where[] = ' ( ca.is_deleted = 0 OR ca.is_deleted IS NULL ) '; } //filter for permissioned cases. $filterCases = array(); $doFilterCases = FALSE; if (!CRM_Core_Permission::check('access all cases and activities')) { $doFilterCases = TRUE; $session = CRM_Core_Session::singleton(); $filterCases = CRM_Case_BAO_Case::getCases(FALSE, $session->get('userID')); } $whereClause = implode(' AND ', $where); $limitClause = ''; if ($limit = CRM_Utils_Array::value('limit', $params)) { $limitClause = "LIMIT 0, {$limit}"; } $query = "\n SELECT c.id as contact_id,\n c.sort_name,\n ca.id,\n ca.subject as case_subject,\n civicrm_case_type.title as case_type,\n ca.start_date as start_date,\n ca.end_date as end_date,\n ca.status_id\n FROM civicrm_case ca INNER JOIN civicrm_case_contact cc ON ca.id=cc.case_id\n INNER JOIN civicrm_contact c ON cc.contact_id=c.id\n INNER JOIN civicrm_case_type ON ca.case_type_id = civicrm_case_type.id\n WHERE {$whereClause}\n ORDER BY c.sort_name, ca.end_date\n {$limitClause}\n"; $dao = CRM_Core_DAO::executeQuery($query); $statuses = CRM_Case_BAO_Case::buildOptions('status_id', 'create'); $unclosedCases = array(); while ($dao->fetch()) { if ($doFilterCases && !array_key_exists($dao->id, $filterCases)) { continue; } $unclosedCases[$dao->id] = array('sort_name' => $dao->sort_name, 'case_type' => $dao->case_type, 'contact_id' => $dao->contact_id, 'start_date' => $dao->start_date, 'end_date' => $dao->end_date, 'case_subject' => $dao->case_subject, 'case_status' => $statuses[$dao->status_id]); } $dao->free(); return $unclosedCases; }
/** * @param string $fileName * @param string $seperator * @param $mapper * @param bool $skipColumnHeader * @param int $mode * @param int $contactType * @param int $onDuplicate * * @return mixed * @throws Exception */ public function run($fileName, $seperator = ',', &$mapper, $skipColumnHeader = FALSE, $mode = self::MODE_PREVIEW, $contactType = self::CONTACT_INDIVIDUAL, $onDuplicate = self::DUPLICATE_SKIP) { if (!is_array($fileName)) { CRM_Core_Error::fatal(); } $fileName = $fileName['name']; switch ($contactType) { case self::CONTACT_INDIVIDUAL: $this->_contactType = 'Individual'; break; case self::CONTACT_HOUSEHOLD: $this->_contactType = 'Household'; break; case self::CONTACT_ORGANIZATION: $this->_contactType = 'Organization'; } $this->init(); $this->_haveColumnHeader = $skipColumnHeader; $this->_seperator = $seperator; $fd = fopen($fileName, "r"); if (!$fd) { return FALSE; } $this->_lineCount = $this->_warningCount = 0; $this->_invalidRowCount = $this->_validCount = 0; $this->_totalCount = $this->_conflictCount = 0; $this->_errors = array(); $this->_warnings = array(); $this->_conflicts = array(); $this->_fileSize = number_format(filesize($fileName) / 1024.0, 2); if ($mode == self::MODE_MAPFIELD) { $this->_rows = array(); } else { $this->_activeFieldCount = count($this->_activeFields); } while (!feof($fd)) { $this->_lineCount++; $values = fgetcsv($fd, 8192, $seperator); if (!$values) { continue; } self::encloseScrub($values); // skip column header if we're not in mapfield mode if ($mode != self::MODE_MAPFIELD && $skipColumnHeader) { $skipColumnHeader = FALSE; continue; } /* trim whitespace around the values */ $empty = TRUE; foreach ($values as $k => $v) { $values[$k] = trim($v, " \t\r\n"); } if (CRM_Utils_System::isNull($values)) { continue; } $this->_totalCount++; if ($mode == self::MODE_MAPFIELD) { $returnCode = $this->mapField($values); } elseif ($mode == self::MODE_PREVIEW) { $returnCode = $this->preview($values); } elseif ($mode == self::MODE_SUMMARY) { $returnCode = $this->summary($values); } elseif ($mode == self::MODE_IMPORT) { $returnCode = $this->import($onDuplicate, $values); } else { $returnCode = self::ERROR; } // note that a line could be valid but still produce a warning if ($returnCode & self::VALID) { $this->_validCount++; if ($mode == self::MODE_MAPFIELD) { $this->_rows[] = $values; $this->_activeFieldCount = max($this->_activeFieldCount, count($values)); } } if ($returnCode & self::WARNING) { $this->_warningCount++; if ($this->_warningCount < $this->_maxWarningCount) { $this->_warningCount[] = $line; } } if ($returnCode & self::ERROR) { $this->_invalidRowCount++; if ($this->_invalidRowCount < $this->_maxErrorCount) { $recordNumber = $this->_lineCount; array_unshift($values, $recordNumber); $this->_errors[] = $values; } } if ($returnCode & self::CONFLICT) { $this->_conflictCount++; $recordNumber = $this->_lineCount; array_unshift($values, $recordNumber); $this->_conflicts[] = $values; } if ($returnCode & self::DUPLICATE) { if ($returnCode & self::MULTIPLE_DUPE) { /* TODO: multi-dupes should be counted apart from singles * on non-skip action */ } $this->_duplicateCount++; $recordNumber = $this->_lineCount; array_unshift($values, $recordNumber); $this->_duplicates[] = $values; if ($onDuplicate != self::DUPLICATE_SKIP) { $this->_validCount++; } } // we give the derived class a way of aborting the process // note that the return code could be multiple code or'ed together if ($returnCode & self::STOP) { break; } // if we are done processing the maxNumber of lines, break if ($this->_maxLinesToProcess > 0 && $this->_validCount >= $this->_maxLinesToProcess) { break; } } fclose($fd); if ($mode == self::MODE_PREVIEW || $mode == self::MODE_IMPORT) { $customHeaders = $mapper; $customfields = CRM_Core_BAO_CustomField::getFields('Membership'); foreach ($customHeaders as $key => $value) { if ($id = CRM_Core_BAO_CustomField::getKeyID($value)) { $customHeaders[$key] = $customfields[$id][0]; } } if ($this->_invalidRowCount) { // removed view url for invlaid contacts $headers = array_merge(array(ts('Line Number'), ts('Reason')), $customHeaders); $this->_errorFileName = self::errorFileName(self::ERROR); self::exportCSV($this->_errorFileName, $headers, $this->_errors); } if ($this->_conflictCount) { $headers = array_merge(array(ts('Line Number'), ts('Reason')), $customHeaders); $this->_conflictFileName = self::errorFileName(self::CONFLICT); self::exportCSV($this->_conflictFileName, $headers, $this->_conflicts); } if ($this->_duplicateCount) { $headers = array_merge(array(ts('Line Number'), ts('View Membership URL')), $customHeaders); $this->_duplicateFileName = self::errorFileName(self::DUPLICATE); self::exportCSV($this->_duplicateFileName, $headers, $this->_duplicates); } } return $this->fini(); }
/** * Build the form * * @access public * * @return void */ function buildQuickForm() { $ufGroupId = $this->get('ufGroupId'); if (!$ufGroupId) { CRM_Core_Error::fatal('ufGroupId is missing'); } $this->_title = ts('Batch Update for Activities') . ' - ' . CRM_Core_BAO_UFGroup::getTitle($ufGroupId); CRM_Utils_System::setTitle($this->_title); $this->addDefaultButtons(ts('Save')); $this->_fields = array(); $this->_fields = CRM_Core_BAO_UFGroup::getFields($ufGroupId, FALSE, CRM_Core_Action::VIEW); // remove file type field and then limit fields $suppressFields = FALSE; $removehtmlTypes = array('File', 'Autocomplete-Select'); foreach ($this->_fields as $name => $field) { if ($cfID = CRM_Core_BAO_CustomField::getKeyID($name) && in_array($this->_fields[$name]['html_type'], $removehtmlTypes)) { $suppressFields = TRUE; unset($this->_fields[$name]); } //fix to reduce size as we are using this field in grid if (is_array($field['attributes']) && $this->_fields[$name]['attributes']['size'] > 19) { //shrink class to "form-text-medium" $this->_fields[$name]['attributes']['size'] = 19; } } $this->_fields = array_slice($this->_fields, 0, $this->_maxFields); $this->addButtons(array(array('type' => 'submit', 'name' => ts('Update Activities'), 'isDefault' => TRUE), array('type' => 'cancel', 'name' => ts('Cancel')))); $this->assign('profileTitle', $this->_title); $this->assign('componentIds', $this->_activityHolderIds); $fileFieldExists = FALSE; //load all campaigns. if (array_key_exists('activity_campaign_id', $this->_fields)) { $this->_componentCampaigns = array(); CRM_Core_PseudoConstant::populate($this->_componentCampaigns, 'CRM_Activity_DAO_Activity', TRUE, 'campaign_id', 'id', ' id IN (' . implode(' , ', array_values($this->_activityHolderIds)) . ' ) '); } $customFields = CRM_Core_BAO_CustomField::getFields('Activity'); foreach ($this->_activityHolderIds as $activityId) { $typeId = CRM_Core_DAO::getFieldValue("CRM_Activity_DAO_Activity", $activityId, 'activity_type_id'); foreach ($this->_fields as $name => $field) { if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($name)) { $customValue = CRM_Utils_Array::value($customFieldID, $customFields); if (!empty($customValue['extends_entity_column_value'])) { $entityColumnValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, $customValue['extends_entity_column_value']); } if (!empty($entityColumnValue[$typeId]) || CRM_Utils_System::isNull($entityColumnValue[$typeId])) { CRM_Core_BAO_UFGroup::buildProfile($this, $field, NULL, $activityId); } } else { // handle non custom fields CRM_Core_BAO_UFGroup::buildProfile($this, $field, NULL, $activityId); } } } $this->assign('fields', $this->_fields); // don't set the status message when form is submitted. // $buttonName = $this->controller->getButtonName('submit'); if ($suppressFields) { CRM_Core_Session::setStatus(ts("FILE or Autocomplete Select type field(s) in the selected profile are not supported for Batch Update."), ts("Some fields have been excluded"), "info"); } $this->addDefaultButtons(ts('Update Activities')); }
/** * 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(); CRM_Contact_BAO_GroupContactCache::opportunisticCacheFlush(); 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; }
/** * Function to process the form * * @access public * * @return void */ public function postProcess() { if ($this->_action & CRM_Core_Action::DELETE) { // delete reminder CRM_Core_BAO_ActionSchedule::del($this->_id); CRM_Core_Session::setStatus(ts('Selected Reminder has been deleted.'), ts('Record Deleted'), 'success'); return; } $values = $this->controller->exportValues($this->getName()); $keys = array('title', 'subject', 'absolute_date', 'group_id', 'record_activity', 'limit_to'); foreach ($keys as $key) { $params[$key] = CRM_Utils_Array::value($key, $values); } $moreKeys = array('start_action_offset', 'start_action_unit', 'start_action_condition', 'start_action_date', 'repetition_frequency_unit', 'repetition_frequency_interval', 'end_frequency_unit', 'end_frequency_interval', 'end_action', 'end_date'); if ($absoluteDate = CRM_Utils_Array::value('absolute_date', $params)) { $params['absolute_date'] = CRM_Utils_Date::processDate($absoluteDate); foreach ($moreKeys as $mkey) { $params[$mkey] = 'null'; } } else { $params['absolute_date'] = 'null'; foreach ($moreKeys as $mkey) { $params[$mkey] = CRM_Utils_Array::value($mkey, $values); } } $params['body_text'] = CRM_Utils_Array::value('text_message', $values); $params['body_html'] = CRM_Utils_Array::value('html_message', $values); if (CRM_Utils_Array::value('recipient', $values) == 'manual') { $params['recipient_manual'] = CRM_Utils_Array::value('recipient_manual_id', $values); $params['group_id'] = $params['recipient'] = $params['recipient_listing'] = 'null'; } elseif (CRM_Utils_Array::value('recipient', $values) == 'group') { $params['group_id'] = $values['group_id']; $params['recipient_manual'] = $params['recipient'] = $params['recipient_listing'] = 'null'; } elseif (!CRM_Utils_System::isNull($values['recipient_listing'])) { $params['recipient'] = CRM_Utils_Array::value('recipient', $values); $params['recipient_listing'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, CRM_Utils_Array::value('recipient_listing', $values)); $params['group_id'] = $params['recipient_manual'] = 'null'; } else { $params['recipient'] = CRM_Utils_Array::value('recipient', $values); $params['group_id'] = $params['recipient_manual'] = $params['recipient_listing'] = 'null'; } $params['mapping_id'] = $this->_mappingID; $params['entity_value'] = $this->_id; $params['entity_status'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, $values['entity']); $params['is_active'] = CRM_Utils_Array::value('is_active', $values, 0); $params['is_repeat'] = CRM_Utils_Array::value('is_repeat', $values, 0); if (CRM_Utils_Array::value('is_repeat', $values) == 0) { $params['repetition_frequency_unit'] = 'null'; $params['repetition_frequency_interval'] = 'null'; $params['end_frequency_unit'] = 'null'; $params['end_frequency_interval'] = 'null'; $params['end_action'] = 'null'; $params['end_date'] = 'null'; } $params['name'] = CRM_Utils_String::munge($params['title'], '_', 64); $composeFields = array('template', 'saveTemplate', 'updateTemplate', 'saveTemplateName'); $msgTemplate = NULL; //mail template is composed $composeParams = array(); foreach ($composeFields as $key) { if (!empty($values[$key])) { $composeParams[$key] = $values[$key]; } } if (!empty($composeParams['updateTemplate'])) { $templateParams = array('msg_text' => $params['body_text'], 'msg_html' => $params['body_html'], 'msg_subject' => $params['subject'], 'is_active' => TRUE); $templateParams['id'] = $values['template']; $msgTemplate = CRM_Core_BAO_MessageTemplate::add($templateParams); } if (!empty($composeParams['saveTemplate'])) { $templateParams = array('msg_text' => $params['body_text'], 'msg_html' => $params['body_html'], 'msg_subject' => $params['subject'], 'is_active' => TRUE); $templateParams['msg_title'] = $composeParams['saveTemplateName']; $msgTemplate = CRM_Core_BAO_MessageTemplate::add($templateParams); } if (isset($msgTemplate->id)) { $params['msg_template_id'] = $msgTemplate->id; } else { $params['msg_template_id'] = CRM_Utils_Array::value('template', $values); } CRM_Core_BAO_ActionSchedule::add($params, $ids); $status = ts("Your new Reminder titled %1 has been saved.", array(1 => "<strong>{$values['title']}</strong>")); CRM_Core_Session::setStatus($status, ts('Saved'), 'success'); parent::endPostProcess(); }
/** * @deprecated - this function formats params according to v2 standards but * need to be sure about the impact of not calling it so retaining on the import class * take the input parameter list as specified in the data model and * convert it into the same format that we use in QF and BAO object * * @param array $params Associative array of property name/value * pairs to insert in new contact. * @param array $values The reformatted properties that we can use internally * * @param array $create Is the formatted Values array going to * be used for CRM_Member_BAO_Membership:create() * * @return array|error * @access public */ function membership_format_params($params, &$values, $create = FALSE) { require_once 'api/v3/utils.php'; $fields = CRM_Member_DAO_Membership::fields(); _civicrm_api3_store_values($fields, $params, $values); $customFields = CRM_Core_BAO_CustomField::getFields('Membership'); foreach ($params as $key => $value) { // ignore empty values or empty arrays etc if (CRM_Utils_System::isNull($value)) { continue; } //Handling Custom Data if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) { $values[$key] = $value; $type = $customFields[$customFieldID]['html_type']; if ($type == 'CheckBox' || $type == 'Multi-Select' || $type == 'AdvMulti-Select') { $mulValues = explode(',', $value); $customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldID, true); $values[$key] = array(); foreach ($mulValues as $v1) { foreach ($customOption as $customValueID => $customLabel) { $customValue = $customLabel['value']; if (strtolower($customLabel['label']) == strtolower(trim($v1)) || strtolower($customValue) == strtolower(trim($v1))) { if ($type == 'CheckBox') { $values[$key][$customValue] = 1; } else { $values[$key][] = $customValue; } } } } } } switch ($key) { case 'membership_contact_id': if (!CRM_Utils_Rule::integer($value)) { throw new Exception("contact_id not valid: {$value}"); } $dao = new CRM_Core_DAO(); $qParams = array(); $svq = $dao->singleValueQuery("SELECT id FROM civicrm_contact WHERE id = {$value}", $qParams); if (!$svq) { throw new Exception("Invalid Contact ID: There is no contact record with contact_id = {$value}."); } $values['contact_id'] = $values['membership_contact_id']; unset($values['membership_contact_id']); break; case 'membership_type_id': if (!CRM_Utils_Array::value($value, CRM_Member_PseudoConstant::membershipType())) { throw new Exception('Invalid Membership Type Id'); } $values[$key] = $value; break; case 'membership_type': $membershipTypeId = CRM_Utils_Array::key(ucfirst($value), CRM_Member_PseudoConstant::membershipType()); if ($membershipTypeId) { if (CRM_Utils_Array::value('membership_type_id', $values) && $membershipTypeId != $values['membership_type_id']) { throw new Exception('Mismatched membership Type and Membership Type Id'); } } else { throw new Exception('Invalid Membership Type'); } $values['membership_type_id'] = $membershipTypeId; break; case 'status_id': if (!CRM_Utils_Array::value($value, CRM_Member_PseudoConstant::membershipStatus())) { throw new Exception('Invalid Membership Status Id'); } $values[$key] = $value; break; case 'membership_status': $membershipStatusId = CRM_Utils_Array::key(ucfirst($value), CRM_Member_PseudoConstant::membershipStatus()); if ($membershipStatusId) { if (CRM_Utils_Array::value('status_id', $values) && $membershipStatusId != $values['status_id']) { throw new Exception('Mismatched membership Status and Membership Status Id'); } } else { throw new Exception('Invalid Membership Status'); } $values['status_id'] = $membershipStatusId; break; default: break; } } _civicrm_api3_custom_format_params($params, $values, 'Membership'); if ($create) { // CRM_Member_BAO_Membership::create() handles membership_start_date, // membership_end_date and membership_source. So, if $values contains // membership_start_date, membership_end_date or membership_source, // convert it to start_date, end_date or source $changes = array('membership_start_date' => 'start_date', 'membership_end_date' => 'end_date', 'membership_source' => 'source'); foreach ($changes as $orgVal => $changeVal) { if (isset($values[$orgVal])) { $values[$changeVal] = $values[$orgVal]; unset($values[$orgVal]); } } } return NULL; }
/** * Process price set and line items. * * @param int $membershipId * @param array $lineItem */ public function processPriceSet($membershipId, $lineItem) { //FIXME : need to move this too if (!$membershipId || !is_array($lineItem) || CRM_Utils_System::isNull($lineItem)) { return; } foreach ($lineItem as $priceSetId => $values) { if (!$priceSetId) { continue; } foreach ($values as $line) { $line['entity_table'] = 'civicrm_membership'; $line['entity_id'] = $membershipId; CRM_Price_BAO_LineItem::create($line); } } }
/** * 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(); }
/** * Parse all address blocks present in given params * and return parse result for all address blocks, * This function either parse street address in to child * elements or build street address from child elements. * * @param array $params * of key value consist of address blocks. * * @return array * as array of success/fails for each address block */ public function parseAddress(&$params) { $parseSuccess = $parsedFields = array(); if (!is_array($params['address']) || CRM_Utils_System::isNull($params['address'])) { return $parseSuccess; } foreach ($params['address'] as $instance => &$address) { $buildStreetAddress = FALSE; $parseFieldName = 'street_address'; foreach (array('street_number', 'street_name', 'street_unit') as $fld) { if (!empty($address[$fld])) { $parseFieldName = 'street_number'; $buildStreetAddress = TRUE; break; } } // main parse string. $parseString = CRM_Utils_Array::value($parseFieldName, $address); // parse address field. $parsedFields = CRM_Core_BAO_Address::parseStreetAddress($parseString); if ($buildStreetAddress) { //hack to ignore spaces between number and suffix. //here user gives input as street_number so it has to //be street_number and street_number_suffix, but //due to spaces though preg detect string as street_name //consider it as 'street_number_suffix'. $suffix = $parsedFields['street_number_suffix']; if (!$suffix) { $suffix = $parsedFields['street_name']; } $address['street_number_suffix'] = $suffix; $address['street_number'] = $parsedFields['street_number']; $streetAddress = NULL; foreach (array('street_number', 'street_number_suffix', 'street_name', 'street_unit') as $fld) { if (in_array($fld, array('street_name', 'street_unit'))) { $streetAddress .= ' '; } $streetAddress .= CRM_Utils_Array::value($fld, $address); } $address['street_address'] = trim($streetAddress); $parseSuccess[$instance] = TRUE; } else { $success = TRUE; // consider address is automatically parseable, // when we should found street_number and street_name if (empty($parsedFields['street_name']) || empty($parsedFields['street_number'])) { $success = FALSE; } // check for original street address string. if (empty($parseString)) { $success = TRUE; } $parseSuccess[$instance] = $success; // we do not reset element values, but keep what we've parsed // in case of partial matches: CRM-8378 // merge parse address in to main address block. $address = array_merge($address, $parsedFields); } } return $parseSuccess; }
function blockSetDefaults(&$defaults) { $locationTypeKeys = array_filter(array_keys(CRM_Core_PseudoConstant::locationType()), 'is_int'); sort($locationTypeKeys); // get the default location type require_once 'CRM/Core/BAO/LocationType.php'; $locationType = CRM_Core_BAO_LocationType::getDefault(); // unset primary location type $primaryLocationTypeIdKey = CRM_Utils_Array::key($locationType->id, $locationTypeKeys); unset($locationTypeKeys[$primaryLocationTypeIdKey]); // reset the array sequence $locationTypeKeys = array_values($locationTypeKeys); // get default phone and im provider id. require_once 'CRM/Core/OptionGroup.php'; $defPhoneTypeId = key(CRM_Core_OptionGroup::values('phone_type', false, false, false, ' AND is_default = 1')); $defIMProviderId = key(CRM_Core_OptionGroup::values('instant_messenger_service', false, false, false, ' AND is_default = 1')); $allBlocks = $this->_blocks; if (array_key_exists('Address', $this->_editOptions)) { $allBlocks['Address'] = $this->_editOptions['Address']; } $config =& CRM_Core_Config::singleton(); foreach ($allBlocks as $blockName => $label) { $name = strtolower($blockName); if (array_key_exists($name, $defaults) && !CRM_Utils_System::isNull($defaults[$name])) { continue; } for ($instance = 1; $instance <= $this->get($blockName . "_Block_Count"); $instance++) { //set location to primary for first one. if ($instance == 1) { $defaults[$name][$instance]['is_primary'] = true; $defaults[$name][$instance]['location_type_id'] = $locationType->id; } else { $locTypeId = isset($locationTypeKeys[$instance - 1]) ? $locationTypeKeys[$instance - 1] : $locationType->id; $defaults[$name][$instance]['location_type_id'] = $locTypeId; } //set default country if ($name == 'address' && $config->defaultContactCountry) { $defaults[$name][$instance]['country_id'] = $config->defaultContactCountry; } //set default phone type. if ($name == 'phone' && $defPhoneTypeId) { $defaults[$name][$instance]['phone_type_id'] = $defPhoneTypeId; } //set default im provider. if ($name == 'im' && $defIMProviderId) { $defaults[$name][$instance]['provider_id'] = $defIMProviderId; } } } // set defaults for country-state widget if (CRM_Utils_Array::value('address', $defaults) && is_array($defaults['address'])) { require_once 'CRM/Contact/Form/Edit/Address.php'; foreach ($defaults['address'] as $blockId => $values) { CRM_Contact_Form_Edit_Address::fixStateSelect($this, "address[{$blockId}][country_id]", "address[{$blockId}][state_province_id]", CRM_Utils_Array::value('country_id', $values, $config->defaultContactCountry)); } } }
/** * Function to set variables up before form is built * * @return void * @access public */ public function preProcess() { $config = CRM_Core_Config::singleton(); $session = CRM_Core_Session::singleton(); // current contribution page id $this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this); if (!$this->_id) { // seems like the session is corrupted and/or we lost the id trail // lets just bump this to a regular session error and redirect user to main page $this->controller->invalidKeyRedirect(); } // this was used prior to the cleverer this_>getContactID - unsure now $this->_userID = $session->get('userID'); $this->_contactID = $this->_membershipContactID = $this->getContactID(); $this->_mid = NULL; if ($this->_contactID) { $this->_mid = CRM_Utils_Request::retrieve('mid', 'Positive', $this); if ($this->_mid) { $membership = new CRM_Member_DAO_Membership(); $membership->id = $this->_mid; if ($membership->find(TRUE)) { $this->_defaultMemTypeId = $membership->membership_type_id; if ($membership->contact_id != $this->_contactID) { $validMembership = FALSE; $employers = CRM_Contact_BAO_Relationship::getPermissionedEmployer($this->_userID); if (!empty($employers) && array_key_exists($membership->contact_id, $employers)) { $this->_membershipContactID = $membership->contact_id; $this->assign('membershipContactID', $this->_membershipContactID); $this->assign('membershipContactName', $employers[$this->_membershipContactID]['name']); $validMembership = TRUE; } else { $membershipType = new CRM_Member_BAO_MembershipType(); $membershipType->id = $membership->membership_type_id; if ($membershipType->find(TRUE)) { // CRM-14051 - membership_type.relationship_type_id is a CTRL-A padded string w one or more ID values. // Convert to commma separated list. $inheritedRelTypes = implode(CRM_Utils_Array::explodePadded($membershipType->relationship_type_id), ','); $permContacts = CRM_Contact_BAO_Relationship::getPermissionedContacts($this->_userID, $membershipType->relationship_type_id); if (array_key_exists($membership->contact_id, $permContacts)) { $this->_membershipContactID = $membership->contact_id; $validMembership = TRUE; } } } if (!$validMembership) { CRM_Core_Session::setStatus(ts("Oops. The membership you're trying to renew appears to be invalid. Contact your site administrator if you need assistance. If you continue, you will be issued a new membership."), ts('Membership Invalid'), 'alert'); } } } else { CRM_Core_Session::setStatus(ts("Oops. The membership you're trying to renew appears to be invalid. Contact your site administrator if you need assistance. If you continue, you will be issued a new membership."), ts('Membership Invalid'), 'alert'); } unset($membership); } } // we do not want to display recently viewed items, so turn off $this->assign('displayRecent', FALSE); // Contribution page values are cleared from session, so can't use normal Printer Friendly view. // Use Browser Print instead. $this->assign('browserPrint', TRUE); // action $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'add'); $this->assign('action', $this->_action); // current mode $this->_mode = $this->_action == 1024 ? 'test' : 'live'; $this->_values = $this->get('values'); $this->_fields = $this->get('fields'); $this->_bltID = $this->get('bltID'); $this->_paymentProcessor = $this->get('paymentProcessor'); $this->_priceSetId = $this->get('priceSetId'); $this->_priceSet = $this->get('priceSet'); if (!$this->_values) { // get all the values from the dao object $this->_values = array(); $this->_fields = array(); CRM_Contribute_BAO_ContributionPage::setValues($this->_id, $this->_values); // check if form is active if (!CRM_Utils_Array::value('is_active', $this->_values)) { // form is inactive, die a fatal death CRM_Core_Error::fatal(ts('The page you requested is currently unavailable.')); } // also check for billing informatin // get the billing location type $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id', array(), 'validate'); // CRM-8108 remove ts around Billing location type //$this->_bltID = array_search( ts('Billing'), $locationTypes ); $this->_bltID = array_search('Billing', $locationTypes); if (!$this->_bltID) { CRM_Core_Error::fatal(ts('Please set a location type of %1', array(1 => 'Billing'))); } $this->set('bltID', $this->_bltID); // check for is_monetary status $isMonetary = CRM_Utils_Array::value('is_monetary', $this->_values); $isPayLater = CRM_Utils_Array::value('is_pay_later', $this->_values); //FIXME: to support multiple payment processors if ($isMonetary && (!$isPayLater || CRM_Utils_Array::value('payment_processor', $this->_values))) { $ppID = CRM_Utils_Array::value('payment_processor', $this->_values); if (!$ppID) { CRM_Core_Error::fatal(ts('A payment processor must be selected for this contribution page (contact the site administrator for assistance).')); } $ppIds = explode(CRM_Core_DAO::VALUE_SEPARATOR, $ppID); $this->_paymentProcessors = CRM_Financial_BAO_PaymentProcessor::getPayments($ppIds, $this->_mode); $this->set('paymentProcessors', $this->_paymentProcessors); //set default payment processor if (!empty($this->_paymentProcessors) && empty($this->_paymentProcessor)) { foreach ($this->_paymentProcessors as $ppId => $values) { if ($values['is_default'] == 1 || count($this->_paymentProcessors) == 1) { $defaultProcessorId = $ppId; break; } } } if (isset($defaultProcessorId)) { $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($defaultProcessorId, $this->_mode); $this->assign_by_ref('paymentProcessor', $this->_paymentProcessor); } if (!CRM_Utils_System::isNull($this->_paymentProcessors)) { foreach ($this->_paymentProcessors as $eachPaymentProcessor) { // check selected payment processor is active if (empty($eachPaymentProcessor)) { CRM_Core_Error::fatal(ts('A payment processor configured for this page might be disabled (contact the site administrator for assistance).')); } // ensure that processor has a valid config $this->_paymentObject =& CRM_Core_Payment::singleton($this->_mode, $eachPaymentProcessor, $this); $error = $this->_paymentObject->checkConfig(); if (!empty($error)) { CRM_Core_Error::fatal($error); } } } } // get price info // CRM-5095 CRM_Price_BAO_PriceSet::initSet($this, $this->_id, 'civicrm_contribution_page'); // this avoids getting E_NOTICE errors in php $setNullFields = array('amount_block_is_active', 'honor_block_is_active', 'is_allow_other_amount', 'footer_text'); foreach ($setNullFields as $f) { if (!isset($this->_values[$f])) { $this->_values[$f] = NULL; } } //check if Membership Block is enabled, if Membership Fields are included in profile //get membership section for this contribution page $this->_membershipBlock = CRM_Member_BAO_Membership::getMembershipBlock($this->_id); $this->set('membershipBlock', $this->_membershipBlock); if ($this->_values['custom_pre_id']) { $preProfileType = CRM_Core_BAO_UFField::getProfileType($this->_values['custom_pre_id']); } if ($this->_values['custom_post_id']) { $postProfileType = CRM_Core_BAO_UFField::getProfileType($this->_values['custom_post_id']); } if ((isset($postProfileType) && $postProfileType == 'Membership' || isset($preProfileType) && $preProfileType == 'Membership') && !$this->_membershipBlock['is_active']) { CRM_Core_Error::fatal(ts('This page includes a Profile with Membership fields - but the Membership Block is NOT enabled. Please notify the site administrator.')); } $pledgeBlock = CRM_Pledge_BAO_PledgeBlock::getPledgeBlock($this->_id); if ($pledgeBlock) { $this->_values['pledge_block_id'] = CRM_Utils_Array::value('id', $pledgeBlock); $this->_values['max_reminders'] = CRM_Utils_Array::value('max_reminders', $pledgeBlock); $this->_values['initial_reminder_day'] = CRM_Utils_Array::value('initial_reminder_day', $pledgeBlock); $this->_values['additional_reminder_day'] = CRM_Utils_Array::value('additional_reminder_day', $pledgeBlock); //set pledge id in values $pledgeId = CRM_Utils_Request::retrieve('pledgeId', 'Positive', $this); //authenticate pledge user for pledge payment. if ($pledgeId) { $this->_values['pledge_id'] = $pledgeId; //lets override w/ pledge campaign. $this->_values['campaign_id'] = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_Pledge', $pledgeId, 'campaign_id'); self::authenticatePledgeUser(); } } $this->set('values', $this->_values); $this->set('fields', $this->_fields); } // Handle PCP $pcpId = CRM_Utils_Request::retrieve('pcpId', 'Positive', $this); if ($pcpId) { $pcp = CRM_PCP_BAO_PCP::handlePcp($pcpId, 'contribute', $this->_values); $this->_pcpId = $pcp['pcpId']; $this->_pcpBlock = $pcp['pcpBlock']; $this->_pcpInfo = $pcp['pcpInfo']; } // Link (button) for users to create their own Personal Campaign page if ($linkText = CRM_PCP_BAO_PCP::getPcpBlockStatus($this->_id, 'contribute')) { $linkTextUrl = CRM_Utils_System::url('civicrm/contribute/campaign', "action=add&reset=1&pageId={$this->_id}&component=contribute", FALSE, NULL, TRUE); $this->assign('linkTextUrl', $linkTextUrl); $this->assign('linkText', $linkText); } //set pledge block if block id is set if (CRM_Utils_Array::value('pledge_block_id', $this->_values)) { $this->assign('pledgeBlock', TRUE); } // check if one of the (amount , membership) bloks is active or not $this->_membershipBlock = $this->get('membershipBlock'); if (!$this->_values['amount_block_is_active'] && !$this->_membershipBlock['is_active'] && !$this->_priceSetId) { CRM_Core_Error::fatal(ts('The requested online contribution page is missing a required Contribution Amount section or Membership section or Price Set. Please check with the site administrator for assistance.')); } if ($this->_values['amount_block_is_active']) { $this->set('amount_block_is_active', $this->_values['amount_block_is_active']); } $this->_contributeMode = $this->get('contributeMode'); $this->assign('contributeMode', $this->_contributeMode); //assigning is_monetary and is_email_receipt to template $this->assign('is_monetary', $this->_values['is_monetary']); $this->assign('is_email_receipt', $this->_values['is_email_receipt']); $this->assign('bltID', $this->_bltID); //assign cancelSubscription URL to templates $this->assign('cancelSubscriptionUrl', CRM_Utils_Array::value('cancelSubscriptionUrl', $this->_values)); // assigning title to template in case someone wants to use it, also setting CMS page title if ($this->_pcpId) { $this->assign('title', $this->_pcpInfo['title']); CRM_Utils_System::setTitle($this->_pcpInfo['title']); } else { $this->assign('title', $this->_values['title']); CRM_Utils_System::setTitle($this->_values['title']); } $this->_defaults = array(); $this->_amount = $this->get('amount'); //CRM-6907 $config = CRM_Core_Config::singleton(); $config->defaultCurrency = CRM_Utils_Array::value('currency', $this->_values, $config->defaultCurrency); //lets allow user to override campaign. $campID = CRM_Utils_Request::retrieve('campID', 'Positive', $this); if ($campID && CRM_Core_DAO::getFieldValue('CRM_Campaign_DAO_Campaign', $campID)) { $this->_values['campaign_id'] = $campID; } //do check for cancel recurring and clean db, CRM-7696 if (CRM_Utils_Request::retrieve('cancel', 'Boolean', CRM_Core_DAO::$_nullObject)) { self::cancelRecurring(); } }
/** * Set variables up before form is built. * * @return void */ public function preProcess() { $values = $ids = array(); $participantID = CRM_Utils_Request::retrieve('id', 'Positive', $this, TRUE); $contactID = CRM_Utils_Request::retrieve('cid', 'Positive', $this, TRUE); $params = array('id' => $participantID); CRM_Event_BAO_Participant::getValues($params, $values, $ids); if (empty($values)) { CRM_Core_Error::statusBounce(ts('The requested participant record does not exist (possibly the record was deleted).')); } CRM_Event_BAO_Participant::resolveDefaults($values[$participantID]); if (!empty($values[$participantID]['fee_level'])) { CRM_Event_BAO_Participant::fixEventLevel($values[$participantID]['fee_level']); } $this->assign('contactId', $contactID); $this->assign('participantId', $participantID); $paymentId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $participantID, 'id', 'participant_id'); $this->assign('hasPayment', $paymentId); if ($parentParticipantId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $participantID, 'registered_by_id')) { $parentHasPayment = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $parentParticipantId, 'id', 'participant_id'); $this->assign('parentHasPayment', $parentHasPayment); } $statusId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_Participant', $participantID, 'status_id', 'id'); $status = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_ParticipantStatusType', $statusId, 'name', 'id'); $status = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_ParticipantStatusType', $statusId, 'name', 'id'); if ($status == 'Transferred') { $transferId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_Participant', $participantID, 'transferred_to_contact_id', 'id'); $pid = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_Participant', $transferId, 'id', 'contact_id'); $transferName = current(CRM_Contact_BAO_Contact::getContactDetails($transferId)); $this->assign('pid', $pid); $this->assign('transferId', $transferId); $this->assign('transferName', $transferName); } $participantStatuses = CRM_Event_PseudoConstant::participantStatus(); if ($values[$participantID]['is_test']) { $values[$participantID]['status'] .= ' (test) '; } // Get Note $noteValue = CRM_Core_BAO_Note::getNote($participantID, 'civicrm_participant'); $values[$participantID]['note'] = array_values($noteValue); // Get Line Items $lineItem = CRM_Price_BAO_LineItem::getLineItems($participantID); if (!CRM_Utils_System::isNull($lineItem)) { $values[$participantID]['lineItem'][] = $lineItem; } $values[$participantID]['totalAmount'] = CRM_Utils_Array::value('fee_amount', $values[$participantID]); // Get registered_by contact ID and display_name if participant was registered by someone else (CRM-4859) if (!empty($values[$participantID]['participant_registered_by_id'])) { $values[$participantID]['registered_by_contact_id'] = CRM_Core_DAO::getFieldValue("CRM_Event_DAO_Participant", $values[$participantID]['participant_registered_by_id'], 'contact_id', 'id'); $values[$participantID]['registered_by_display_name'] = CRM_Contact_BAO_Contact::displayName($values[$participantID]['registered_by_contact_id']); } // Check if this is a primaryParticipant (registered for others) and retrieve additional participants if true (CRM-4859) if (CRM_Event_BAO_Participant::isPrimaryParticipant($participantID)) { $values[$participantID]['additionalParticipants'] = CRM_Event_BAO_Participant::getAdditionalParticipants($participantID); } // get the option value for custom data type $roleCustomDataTypeID = CRM_Core_OptionGroup::getValue('custom_data_type', 'ParticipantRole', 'name'); $eventNameCustomDataTypeID = CRM_Core_OptionGroup::getValue('custom_data_type', 'ParticipantEventName', 'name'); $eventTypeCustomDataTypeID = CRM_Core_OptionGroup::getValue('custom_data_type', 'ParticipantEventType', 'name'); $allRoleIDs = explode(CRM_Core_DAO::VALUE_SEPARATOR, $values[$participantID]['role_id']); $groupTree = array(); $finalTree = array(); foreach ($allRoleIDs as $k => $v) { $roleGroupTree = CRM_Core_BAO_CustomGroup::getTree('Participant', $this, $participantID, NULL, $v, $roleCustomDataTypeID); $eventGroupTree = CRM_Core_BAO_CustomGroup::getTree('Participant', $this, $participantID, NULL, $values[$participantID]['event_id'], $eventNameCustomDataTypeID); $eventTypeID = CRM_Core_DAO::getFieldValue("CRM_Event_DAO_Event", $values[$participantID]['event_id'], 'event_type_id', 'id'); $eventTypeGroupTree = CRM_Core_BAO_CustomGroup::getTree('Participant', $this, $participantID, NULL, $eventTypeID, $eventTypeCustomDataTypeID); $groupTree = CRM_Utils_Array::crmArrayMerge($roleGroupTree, $eventGroupTree); $groupTree = CRM_Utils_Array::crmArrayMerge($groupTree, $eventTypeGroupTree); $groupTree = CRM_Utils_Array::crmArrayMerge($groupTree, CRM_Core_BAO_CustomGroup::getTree('Participant', $this, $participantID)); foreach ($groupTree as $treeId => $trees) { $finalTree[$treeId] = $trees; } } CRM_Core_BAO_CustomGroup::buildCustomDataView($this, $finalTree, FALSE, NULL, NULL, NULL, $participantID); $eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $values[$participantID]['event_id'], 'title'); //CRM-7150, show event name on participant view even if the event is disabled if (empty($values[$participantID]['event'])) { $values[$participantID]['event'] = $eventTitle; } //do check for campaigns if ($campaignId = CRM_Utils_Array::value('campaign_id', $values[$participantID])) { $campaigns = CRM_Campaign_BAO_Campaign::getCampaigns($campaignId); $values[$participantID]['campaign'] = $campaigns[$campaignId]; } $this->assign($values[$participantID]); // add viewed participant to recent items list $url = CRM_Utils_System::url('civicrm/contact/view/participant', "action=view&reset=1&id={$values[$participantID]['id']}&cid={$values[$participantID]['contact_id']}&context=home"); $recentOther = array(); if (CRM_Core_Permission::check('edit event participants')) { $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/participant', "action=update&reset=1&id={$values[$participantID]['id']}&cid={$values[$participantID]['contact_id']}&context=home"); } if (CRM_Core_Permission::check('delete in CiviEvent')) { $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/participant', "action=delete&reset=1&id={$values[$participantID]['id']}&cid={$values[$participantID]['contact_id']}&context=home"); } $participantRoles = CRM_Event_PseudoConstant::participantRole(); $displayName = CRM_Contact_BAO_Contact::displayName($values[$participantID]['contact_id']); $participantCount = array(); $invoiceSettings = Civi::settings()->get('contribution_invoice_settings'); $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings); $totalTaxAmount = 0; foreach ($lineItem as $k => $v) { if (CRM_Utils_Array::value('participant_count', $lineItem[$k]) > 0) { $participantCount[] = $lineItem[$k]['participant_count']; } $totalTaxAmount = $v['tax_amount'] + $totalTaxAmount; } if ($invoicing) { $this->assign('totalTaxAmount', $totalTaxAmount); } if ($participantCount) { $this->assign('pricesetFieldsCount', $participantCount); } $this->assign('displayName', $displayName); // omitting contactImage from title for now since the summary overlay css doesn't work outside of our crm-container CRM_Utils_System::setTitle(ts('View Event Registration for') . ' ' . $displayName); $roleId = CRM_Utils_Array::value('role_id', $values[$participantID]); $title = $displayName . ' (' . CRM_Utils_Array::value($roleId, $participantRoles) . ' - ' . $eventTitle . ')'; $sep = CRM_Core_DAO::VALUE_SEPARATOR; $viewRoles = array(); foreach (explode($sep, $values[$participantID]['role_id']) as $k => $v) { $viewRoles[] = $participantRoles[$v]; } $values[$participantID]['role_id'] = implode(', ', $viewRoles); $this->assign('role', $values[$participantID]['role_id']); // add Participant to Recent Items CRM_Utils_Recent::add($title, $url, $values[$participantID]['id'], 'Participant', $values[$participantID]['contact_id'], NULL, $recentOther); }
static function createIndexes(&$tables, $createIndexPrefix = 'index', $substrLenghts = array()) { $queries = array(); require_once 'CRM/Core/DAO/Domain.php'; $domain = new CRM_Core_DAO_Domain(); $domain->find(TRUE); $locales = explode(CRM_Core_DAO::VALUE_SEPARATOR, $domain->locales); // if we're multilingual, cache the information on internationalised fields static $columns = NULL; if (!CRM_Utils_System::isNull($locales) and $columns === NULL) { $columns = CRM_Core_I18n_SchemaStructure::columns(); } foreach ($tables as $table => $fields) { $query = "SHOW INDEX FROM {$table}"; $dao = CRM_Core_DAO::executeQuery($query); $currentIndexes = array(); while ($dao->fetch()) { $currentIndexes[] = $dao->Key_name; } // now check for all fields if the index exists foreach ($fields as $field) { // handle indices over substrings, CRM-6245 // $lengthName is appended to index name, $lengthSize is the field size modifier $lengthName = isset($substrLenghts[$table][$field]) ? "_{$substrLenghts[$table][$field]}" : ''; $lengthSize = isset($substrLenghts[$table][$field]) ? "({$substrLenghts[$table][$field]})" : ''; $names = array("index_{$field}{$lengthName}", "FK_{$table}_{$field}{$lengthName}", "UI_{$field}{$lengthName}", "{$createIndexPrefix}_{$field}{$lengthName}"); // skip to the next $field if one of the above $names exists; handle multilingual for CRM-4126 foreach ($names as $name) { $regex = '/^' . preg_quote($name) . '(_[a-z][a-z]_[A-Z][A-Z])?$/'; if (preg_grep($regex, $currentIndexes)) { continue 2; } } // the index doesn't exist, so create it // if we're multilingual and the field is internationalised, do it for every locale if (!CRM_Utils_System::isNull($locales) and isset($columns[$table][$field])) { foreach ($locales as $locale) { $queries[] = "CREATE INDEX {$createIndexPrefix}_{$field}{$lengthName}_{$locale} ON {$table} ({$field}_{$locale}{$lengthSize})"; } } else { $queries[] = "CREATE INDEX {$createIndexPrefix}_{$field}{$lengthName} ON {$table} ({$field}{$lengthSize})"; } } } // run the queries without i18n-rewriting $dao = new CRM_Core_DAO(); foreach ($queries as $query) { $dao->query($query, FALSE); } }
/** * Send email receipt. * * @param CRM_Core_Form $form * Form object. * @param array $formValues * @param object $membership * Object. * * @return bool * true if mail was sent successfully */ public static function emailReceipt(&$form, &$formValues, &$membership) { // retrieve 'from email id' for acknowledgement $receiptFrom = $formValues['from_email_address']; if (!empty($formValues['payment_instrument_id'])) { $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument(); $formValues['paidBy'] = $paymentInstrument[$formValues['payment_instrument_id']]; } // retrieve custom data $customFields = $customValues = array(); if (property_exists($form, '_groupTree') && !empty($form->_groupTree)) { foreach ($form->_groupTree as $groupID => $group) { if ($groupID == 'info') { continue; } foreach ($group['fields'] as $k => $field) { $field['title'] = $field['label']; $customFields["custom_{$k}"] = $field; } } } $members = array(array('member_id', '=', $membership->id, 0, 0)); // check whether its a test drive if ($form->_mode == 'test') { $members[] = array('member_test', '=', 1, 0, 0); } CRM_Core_BAO_UFGroup::getValues($formValues['contact_id'], $customFields, $customValues, FALSE, $members); if ($form->_mode) { if (!empty($form->_params['billing_first_name'])) { $name = $form->_params['billing_first_name']; } if (!empty($form->_params['billing_middle_name'])) { $name .= " {$form->_params['billing_middle_name']}"; } if (!empty($form->_params['billing_last_name'])) { $name .= " {$form->_params['billing_last_name']}"; } $form->assign('billingName', $name); // assign the address formatted up for display $addressParts = array("street_address-{$form->_bltID}", "city-{$form->_bltID}", "postal_code-{$form->_bltID}", "state_province-{$form->_bltID}", "country-{$form->_bltID}"); $addressFields = array(); foreach ($addressParts as $part) { list($n, $id) = explode('-', $part); if (isset($form->_params['billing_' . $part])) { $addressFields[$n] = $form->_params['billing_' . $part]; } } $form->assign('address', CRM_Utils_Address::format($addressFields)); $date = CRM_Utils_Date::format($form->_params['credit_card_exp_date']); $date = CRM_Utils_Date::mysqlToIso($date); $form->assign('credit_card_exp_date', $date); $form->assign('credit_card_number', CRM_Utils_System::mungeCreditCard($form->_params['credit_card_number'])); $form->assign('credit_card_type', $form->_params['credit_card_type']); $form->assign('contributeMode', 'direct'); $form->assign('isAmountzero', 0); $form->assign('is_pay_later', 0); $form->assign('isPrimary', 1); } $form->assign('module', 'Membership'); $form->assign('contactID', $formValues['contact_id']); $form->assign('membershipID', CRM_Utils_Array::value('membership_id', $form->_params, CRM_Utils_Array::value('membership_id', $form->_defaultValues))); if (!empty($formValues['contribution_id'])) { $form->assign('contributionID', $formValues['contribution_id']); } elseif (isset($form->_onlinePendingContributionId)) { $form->assign('contributionID', $form->_onlinePendingContributionId); } if (!empty($formValues['contribution_status_id'])) { $form->assign('contributionStatusID', $formValues['contribution_status_id']); $form->assign('contributionStatus', CRM_Contribute_PseudoConstant::contributionStatus($formValues['contribution_status_id'], 'name')); } if (!empty($formValues['is_renew'])) { $form->assign('receiptType', 'membership renewal'); } else { $form->assign('receiptType', 'membership signup'); } $form->assign('receive_date', CRM_Utils_Date::processDate(CRM_Utils_Array::value('receive_date', $formValues))); $form->assign('formValues', $formValues); if (empty($lineItem)) { $form->assign('mem_start_date', CRM_Utils_Date::customFormat($membership->start_date, '%B %E%f, %Y')); if (!CRM_Utils_System::isNull($membership->end_date)) { $form->assign('mem_end_date', CRM_Utils_Date::customFormat($membership->end_date, '%B %E%f, %Y')); } $form->assign('membership_name', CRM_Member_PseudoConstant::membershipType($membership->membership_type_id)); } $form->assign('customValues', $customValues); $isBatchProcess = is_a($form, 'CRM_Batch_Form_Entry'); if (empty($form->_contributorDisplayName) || empty($form->_contributorEmail) || $isBatchProcess) { // in this case the form is being called statically from the batch editing screen // having one class in the form layer call another statically is not greate // & we should aim to move this function to the BAO layer in future. // however, we can assume that the contact_id passed in by the batch // function will be the recipient list($form->_contributorDisplayName, $form->_contributorEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($formValues['contact_id']); if (empty($form->_receiptContactId) || $isBatchProcess) { $form->_receiptContactId = $formValues['contact_id']; } } $template = CRM_Core_Smarty::singleton(); $taxAmt = $template->get_template_vars('dataArray'); $eventTaxAmt = $template->get_template_vars('totalTaxAmount'); $prefixValue = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings'); $invoicing = CRM_Utils_Array::value('invoicing', $prefixValue); if ((!empty($taxAmt) || isset($eventTaxAmt)) && (isset($invoicing) && isset($prefixValue['is_email_pdf']))) { $isEmailPdf = TRUE; } else { $isEmailPdf = FALSE; } list($mailSend, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate(array('groupName' => 'msg_tpl_workflow_membership', 'valueName' => 'membership_offline_receipt', 'contactId' => $form->_receiptContactId, 'from' => $receiptFrom, 'toName' => $form->_contributorDisplayName, 'toEmail' => $form->_contributorEmail, 'PDFFilename' => ts('receipt') . '.pdf', 'isEmailPdf' => $isEmailPdf, 'contributionId' => $formValues['contribution_id'], 'isTest' => (bool) ($form->_action & CRM_Core_Action::PREVIEW))); return TRUE; }