function add_participant_to_cart() { require 'CRM/Core/Transaction.php'; $transaction = new CRM_Core_Transaction(); $cart_id = $_GET['cart_id']; $event_id = $_GET['event_id']; $cart = CRM_Event_Cart_BAO_Cart::find_by_id($_GET['cart_id']); $params_array = array('cart_id' => $cart->id, 'contact_id' => CRM_Event_Cart_Form_Cart::find_or_create_contact(), 'event_id' => $event_id); //XXX security? $participant = CRM_Event_Cart_BAO_MerParticipant::create($params_array); $participant->save(); $form = new CRM_Core_Form(); $pform = new CRM_Event_Cart_Form_MerParticipant($participant); $pform->appendQuickForm($form); $renderer = $form->getRenderer(); $config = CRM_Core_Config::singleton(); $templateDir = $config->templateDir; if (is_array($templateDir)) { $templateDir = array_pop($templateDir); } $requiredTemplate = file_get_contents($templateDir . '/CRM/Form/label.tpl'); $renderer->setRequiredTemplate($requiredTemplate); $form->accept($renderer); $template = CRM_Core_Smarty::singleton(); $template->assign('form', $renderer->toArray()); $template->assign('participant', $participant); $output = $template->fetch("CRM/Event/Cart/Form/Checkout/Participant.tpl"); $transaction->commit(); echo $output; CRM_Utils_System::civiExit(); }
/** * Add or update a link between contribution and membership * * @param array $params (reference ) input parameters * * @return array (reference ) membership_payment_id of created or updated record * @static void * @access public */ function &civicrm_membershipcontributionlink_create(&$params) { _civicrm_initialize(); if (empty($params)) { return civicrm_create_error(ts('No input parameters present')); } if (!is_array($params)) { return civicrm_create_error(ts('Input parameters is not an array')); } if (!isset($params['contribution_id']) || !isset($params['membership_id'])) { return civicrm_create_error(ts('Required parameters missing')); } require_once 'CRM/Core/Transaction.php'; $transaction = new CRM_Core_Transaction(); require_once 'CRM/Member/DAO/MembershipPayment.php'; $mpDAO =& new CRM_Member_DAO_MembershipPayment(); $mpDAO->copyValues($params); $result = $mpDAO->save(); if (is_a($result, 'CRM_Core_Error')) { $transaction->rollback(); return civicrm_create_error($result->_errors[0]['message']); } $transaction->commit(); _civicrm_object_to_array($mpDAO, $mpArray); return $mpArray; }
function postProcess() { $values = $this->exportValues(); $title = str_replace("'", "''", $values['title']); $params = array(1 => array($title, 'String'), 2 => array($values['widget'], 'Integer')); if (isset($this->_id)) { $params += array(3 => array($this->_id, 'Integer')); $sql = "UPDATE civicrm_wci_embed_code SET name = %1, widget_id = %2 where id = %3"; } else { $sql = "INSERT INTO civicrm_wci_embed_code (name, widget_id)VALUES (%1, %2)"; } $errorScope = CRM_Core_TemporaryErrorScope::useException(); try { $transaction = new CRM_Core_Transaction(); CRM_Core_DAO::executeQuery($sql, $params); $transaction->commit(); CRM_Core_Session::setStatus(ts('Embed code created successfully'), '', 'success'); if (isset($_REQUEST['_qf_NewEmbedCode_next'])) { isset($this->_id) ? $embed_id = $this->_id : ($embed_id = CRM_Core_DAO::singleValueQuery('SELECT LAST_INSERT_ID()')); CRM_Utils_System::redirect('?action=update&reset=1&id=' . $embed_id); } else { CRM_Utils_System::redirect('embed-code?reset=1'); } } catch (Exception $e) { CRM_Core_Session::setStatus(ts('Failed to create embed code'), '', 'error'); $transaction->rollback(); } parent::postProcess(); }
/** * Create a new domain - with a domain group. * * This is not fully developed & need to work on creating admin menus etc * * @param array $params * * @return array * @example DomainCreate.php * {@getfields domain_create} */ function civicrm_api3_multisite_domain_create($params) { $transaction = new CRM_Core_Transaction(); if (empty($params['contact_id'])) { $params['contact_id'] = _civicrm_api3_multisite_domain_create_if_not_exists('Contact', array('organization_name' => $params['name'], 'contact_type' => 'organization')); } $domain = civicrm_api('domain', 'getsingle', array('version' => 3, 'current_domain' => TRUE)); $fullParams = array_merge($domain, $params); $fullParams['domain_version'] = $domain['version']; $fullParams['version'] = 3; unset($fullParams['id']); if (empty($params['group_id'])) { $groupParams = array('title' => !empty($params['group_name']) ? $params['group_name'] : $params['name']); $group = civicrm_api3('Group', 'get', array_merge($groupParams, array('options' => array('limit' => 1)))); if (empty($group['id'])) { // Ideally would fix the api to be more consistent & not assume default but... $groupParams['group_type'] = array(1 => 1); $group = civicrm_api3('Group', 'create', $groupParams); } $domainGroupID = $group['id']; } else { $domainGroupID = $params['group_id']; } _civicrm_api3_multisite_domain_create_if_not_exists('GroupOrganization', array('group_id' => $domainGroupID, 'organization_id' => $params['contact_id'])); $domainID = _civicrm_api3_multisite_domain_create_if_not_exists('domain', $fullParams); if (!$domainID || $domainID != civicrm_api3('Domain', 'getvalue', array('name' => $params['name'], 'return' => 'id'))) { throw new CiviCRM_API3_Exception('Failed to create domain', 'unknown'); } $transaction->commit(); if (!civicrm_api3('Navigation', 'getcount', array('domain_id' => $domainID))) { _civicrm_load_navigation($params['name'], $domainID); } civicrm_api3('Setting', 'create', array('is_enabled' => TRUE, 'domain_group_id' => $domainGroupID, 'domain_id' => $domainID)); return civicrm_api3_create_success(array($domainID => array('id' => $domainID))); }
/** * PriceSet.FetchSection API * * @param array $params * @return array API result descriptor * @see civicrm_api3_create_success * @see civicrm_api3_create_error * @throws API_Exception */ function civicrm_api3_workflow_save($params) { if (!array_key_exists("data", $params) || !$params['data']) { throw new API_Exception('Missing parameter: data', 170); } if (!array_key_exists("wid", $params) || !$params['wid']) { throw new API_Exception('Missing parameter: wid', 170); } $wid = $params['wid']; $d = urldecode($params['data']); $data = parse_str($d); //I don't know why this is important, but it made things work. $try2 = parse_str($params['data']); //Hook in case someone wants to alter the data CRM_Workflow_hook::beforeSave($wid, $data); $transaction = new CRM_Core_Transaction(); $dsql = "DELETE FROM civicrm_workflow_detail WHERE workflow_id = {$wid}"; $dao =& CRM_Core_DAO::executeQuery($dsql); if (!empty($data)) { $sql = "INSERT INTO civicrm_workflow_detail ( workflow_id, entity_table, entity_id, `order`, breadcrumb, `next`, title) VALUES "; $i = 1; $vals = array(); foreach ($data as $key => $d) { //$did = (strpos($id, ":")) ? 0 : $id; $eid = $d['entity_id']; $e_type = $d['entity_table']; $order = $d['order']; $breadcrumb = $d['breadcrumb']; $next = $d['next']; $title = $d['title']; $sql = $sql . "( %" . ($i + 0) . ", %" . ($i + 1) . ", %" . ($i + 2) . ", %" . ($i + 3) . ", %" . ($i + 4) . ", %" . ($i + 5) . ", %" . ($i + 6) . "),"; //$vals[$i++] = array($did, 'Integer'); $vals[$i++] = array($wid, 'Integer'); $vals[$i++] = array($e_type, 'String'); $vals[$i++] = array($eid, 'String'); $vals[$i++] = array($order, 'Integer'); $vals[$i++] = array($breadcrumb, 'String'); $vals[$i++] = array($next, 'String'); $vals[$i++] = array($title, 'String'); } $sql = substr($sql, 0, -1); try { $dao =& CRM_Core_DAO::executeQuery($sql, $vals); } catch (Exception $e) { $transaction->rollback(); return civicrm_api3_create_error($e . message); } //TODO: Better error checking? if ($dao->_lastError) { $transaction->rollback(); } else { $transaction->commit(); CRM_Workflow_hook::afterSave($wid, $data); } } $returnValues = array(); return civicrm_api3_create_success($returnValues, $params, 'PriceSet', 'FetchSection'); }
function run() { // get the requested action $action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'browse'); // assign vars to templates $this->assign('action', $action); $id = CRM_Utils_Request::retrieve('id', 'Positive', $this, FALSE, 0); if ($action & CRM_Core_Action::UPDATE) { $controller = new CRM_Core_Controller_Simple('CRM_Wci_Form_ProgressBar', 'Edit Progressbar', CRM_Core_Action::UPDATE); $controller->set('id', $id); $controller->process(); return $controller->run(); } elseif ($action & CRM_Core_Action::COPY) { try { $sql = "INSERT INTO civicrm_wci_progress_bar (name, starting_amount, goal_amount)\n SELECT concat(name, '-', (SELECT MAX(id) FROM civicrm_wci_progress_bar)),\n starting_amount, goal_amount FROM civicrm_wci_progress_bar\n WHERE id=%1"; CRM_Core_DAO::executeQuery($sql, array(1 => array($id, 'Integer'))); $new_pb_id = CRM_Core_DAO::singleValueQuery('SELECT LAST_INSERT_ID()'); $sql = "INSERT INTO civicrm_wci_progress_bar_formula\n (contribution_page_id, financial_type_id, progress_bar_id, start_date, end_date, percentage)\n SELECT contribution_page_id, financial_type_id, %1, start_date,\n end_date, percentage FROM civicrm_wci_progress_bar_formula WHERE progress_bar_id=%2"; CRM_Core_DAO::executeQuery($sql, array(1 => array($new_pb_id, 'Integer'), 2 => array($id, 'Integer'))); } catch (Exception $e) { CRM_Core_Session::setStatus(ts('Failed to create Progress bar. ') . $e->getMessage(), '', 'error'); $transaction->rollback(); } } elseif ($action & CRM_Core_Action::DELETE) { $errorScope = CRM_Core_TemporaryErrorScope::useException(); try { $transaction = new CRM_Core_Transaction(); $sql = "DELETE FROM civicrm_wci_progress_bar_formula where progress_bar_id = %1"; $params = array(1 => array($id, 'Integer')); CRM_Core_DAO::executeQuery($sql, $params); $sql = "DELETE FROM civicrm_wci_progress_bar where id = %1"; $params = array(1 => array($id, 'Integer')); CRM_Core_DAO::executeQuery($sql, $params); $transaction->commit(); } catch (Exception $e) { $errmgs = $e->getMessage() . ts('. Check whether progressbar is used by any widget or not'); CRM_Core_Session::setStatus($errmgs, '', 'error'); $transaction->rollback(); } } // Example: Set the page-title dynamically; alternatively, declare a static title in xml/Menu/*.xml CRM_Utils_System::setTitle(ts('Progress Bar List')); $query = "SELECT * FROM civicrm_wci_progress_bar"; $params = array(); $dao = CRM_Core_DAO::executeQuery($query, $params, TRUE, 'CRM_Wci_DAO_ProgressBar'); while ($dao->fetch()) { $con_page[$dao->id] = array(); CRM_Core_DAO::storeValues($dao, $con_page[$dao->id]); $action = array_sum(array_keys($this->actionLinks())); //build the normal action links. $con_page[$dao->id]['action'] = CRM_Core_Action::formLink(self::actionLinks(), $action, array('id' => $dao->id)); } if (isset($con_page)) { $this->assign('rows', $con_page); } return parent::run(); }
function run() { $transaction = new CRM_Core_Transaction(); $cart = CRM_Event_Cart_BAO_Cart::find_or_create_for_current_session(); $cart->load_associations(); $this->assign_by_ref('events_in_carts', $cart->get_main_events_in_carts()); $this->assign('events_count', count($cart->get_main_events_in_carts())); $transaction->commit(); return parent::run(); }
/** * @param array $params * * @return $this * @throws Exception */ public static function create($params) { $transaction = new CRM_Core_Transaction(); $cart = self::add($params); if (is_a($cart, 'CRM_Core_Error')) { $transaction->rollback(); CRM_Core_Error::fatal(ts('There was an error creating an event cart')); } $transaction->commit(); return $cart; }
/** * Construct a new mailingab object. * * @params array $params * Form values. * * @param array $params * @param array $ids * * @return object * $mailingab The new mailingab object */ public static function create(&$params, $ids = array()) { $transaction = new CRM_Core_Transaction(); $mailingab = self::add($params, $ids); if (is_a($mailingab, 'CRM_Core_Error')) { $transaction->rollback(); return $mailingab; } $transaction->commit(); return $mailingab; }
/** * Confirm a pending subscription * * @param int $contact_id The id of the contact * @param int $subscribe_id The id of the subscription event * @param string $hash The hash * * @return boolean True on success * @access public * @static */ public static function confirm($contact_id, $subscribe_id, $hash) { $se =& CRM_Mailing_Event_BAO_Subscribe::verify($contact_id, $subscribe_id, $hash); if (!$se) { return FALSE; } // before we proceed lets just check if this contact is already 'Added' // if so, we should ignore this request and hence avoid sending multiple // emails - CRM-11157 $details = CRM_Contact_BAO_GroupContact::getMembershipDetail($contact_id, $se->group_id); if ($details && $details->status == 'Added') { // This contact is already subscribed // lets return the group title return CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Group', $se->group_id, 'title'); } $transaction = new CRM_Core_Transaction(); $ce = new CRM_Mailing_Event_BAO_Confirm(); $ce->event_subscribe_id = $se->id; $ce->time_stamp = date('YmdHis'); $ce->save(); CRM_Contact_BAO_GroupContact::addContactsToGroup(array($contact_id), $se->group_id, 'Email', 'Added', $ce->id); $transaction->commit(); $config = CRM_Core_Config::singleton(); $domain = CRM_Core_BAO_Domain::getDomain(); list($domainEmailName, $_) = CRM_Core_BAO_Domain::getNameAndEmail(); list($display_name, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($se->contact_id); $group = new CRM_Contact_DAO_Group(); $group->id = $se->group_id; $group->find(TRUE); $component = new CRM_Mailing_BAO_Component(); $component->is_default = 1; $component->is_active = 1; $component->component_type = 'Welcome'; $component->find(TRUE); $emailDomain = CRM_Core_BAO_MailSettings::defaultDomain(); $html = $component->body_html; if ($component->body_text) { $text = $component->body_text; } else { $text = CRM_Utils_String::htmlToText($component->body_html); } $bao = new CRM_Mailing_BAO_Mailing(); $bao->body_text = $text; $bao->body_html = $html; $tokens = $bao->getTokens(); $html = CRM_Utils_Token::replaceDomainTokens($html, $domain, TRUE, $tokens['html']); $html = CRM_Utils_Token::replaceWelcomeTokens($html, $group->title, TRUE); $text = CRM_Utils_Token::replaceDomainTokens($text, $domain, FALSE, $tokens['text']); $text = CRM_Utils_Token::replaceWelcomeTokens($text, $group->title, FALSE); $mailParams = array('groupName' => 'Mailing Event ' . $component->component_type, 'subject' => $component->subject, 'from' => "\"{$domainEmailName}\" <do-not-reply@{$emailDomain}>", 'toEmail' => $email, 'toName' => $display_name, 'replyTo' => "do-not-reply@{$emailDomain}", 'returnPath' => "do-not-reply@{$emailDomain}", 'html' => $html, 'text' => $text); // send - ignore errors because the desired status change has already been successful $unused_result = CRM_Utils_Mail::send($mailParams); return $group->title; }
static function &create(&$params) { require_once 'CRM/Core/Transaction.php'; $transaction = new CRM_Core_Transaction(); $statusType = self::add($params); if (is_a($statusType, 'CRM_Core_Error')) { $transaction->rollback(); return $statusType; } $transaction->commit(); return $statusType; }
function run() { // get the requested action $action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'browse'); // assign vars to templates $this->assign('action', $action); $id = CRM_Utils_Request::retrieve('id', 'Positive', $this, FALSE, 0); if ($action & CRM_Core_Action::UPDATE) { $controller = new CRM_Core_Controller_Simple('CRM_Wci_Form_CreateWidget', 'Edit Widget', CRM_Core_Action::UPDATE); $controller->set('id', $id); $controller->process(); return $controller->run(); } elseif ($action & CRM_Core_Action::COPY) { try { $sql = "INSERT INTO civicrm_wci_widget (title, logo_image, image,\n button_title, button_link_to, progress_bar_id, description,\n email_signup_group_id, size_variant, color_title, color_title_bg,\n color_progress_bar, color_progress_bar_bg, color_widget_bg, color_description, color_border,\n color_button, color_button_bg, hide_title, hide_border, hide_pbcap,\n color_btn_newsletter, color_btn_newsletter_bg, newsletter_text,\n color_newsletter_text, style_rules, override, custom_template, show_pb_perc)\n SELECT concat(title, '-', (SELECT MAX(id) FROM civicrm_wci_widget)), logo_image, image,\n button_title, button_link_to, progress_bar_id, description,\n email_signup_group_id, size_variant, color_title, color_title_bg,\n color_progress_bar, color_progress_bar_bg, color_widget_bg, color_description, color_border,\n color_button, color_button_bg, hide_title, hide_border, hide_pbcap,\n color_btn_newsletter, color_btn_newsletter_bg, newsletter_text,\n color_newsletter_text, style_rules, override, custom_template, show_pb_perc FROM civicrm_wci_widget WHERE id=%1"; CRM_Core_DAO::executeQuery("SET foreign_key_checks = 0;"); CRM_Core_DAO::executeQuery($sql, array(1 => array($id, 'Integer'))); CRM_Core_DAO::executeQuery("SET foreign_key_checks = 1;"); } catch (Exception $e) { CRM_Core_Session::setStatus(ts('Failed to create widget. ') . $e->getMessage(), '', 'error'); $transaction->rollback(); } } elseif ($action & CRM_Core_Action::DELETE) { try { $transaction = new CRM_Core_Transaction(); $sql = "DELETE FROM civicrm_wci_widget where id = %1"; $params = array(1 => array($id, 'Integer')); CRM_Core_DAO::executeQuery($sql, $params); $transaction->commit(); } catch (Exception $e) { CRM_Core_Session::setStatus(ts('Failed to delete widget. ') . $e->getMessage(), '', 'error'); $transaction->rollback(); } } CRM_Utils_System::setTitle(ts('Widget List')); $query = "SELECT * FROM civicrm_wci_widget"; $params = array(); $dao = CRM_Core_DAO::executeQuery($query, $params, TRUE, 'CRM_Wci_DAO_Widget'); while ($dao->fetch()) { $wid_page[$dao->id] = array(); CRM_Core_DAO::storeValues($dao, $wid_page[$dao->id]); $wid_page[$dao->id]['title'] = $wid_page[$dao->id]['title']; $description = $wid_page[$dao->id]['description']; $wid_page[$dao->id]['description'] = strip_tags($description); $action = array_sum(array_keys($this->actionLinks())); //build the normal action links. $wid_page[$dao->id]['action'] = CRM_Core_Action::formLink(self::actionLinks(), $action, array('id' => $dao->id)); } if (isset($wid_page)) { $this->assign('rows', $wid_page); } parent::run(); }
function stub_out_and_inherit() { $transaction = new CRM_Core_Transaction(); foreach ($this->cart->get_main_events_in_carts() as $event_in_cart) { if (empty($event_in_cart->participants)) { $participant = CRM_Event_Cart_BAO_MerParticipant::create(array('cart_id' => $this->cart->id, 'event_id' => $event_in_cart->event_id, 'contact_id' => self::find_or_create_contact($this->getContactID()))); $participant->save(); $event_in_cart->add_participant($participant); } $event_in_cart->save(); } $transaction->commit(); }
/** * This function takes care of all the things common to all pages. * * This typically involves assigning the appropriate smarty variables :) */ public function run() { $transaction = new CRM_Core_Transaction(); $this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this, TRUE); $cart = CRM_Event_Cart_BAO_Cart::find_or_create_for_current_session(); $cart->load_associations(); $event_in_cart = $cart->get_event_in_cart_by_event_id($this->_id); $removed_event = $cart->remove_event_in_cart($event_in_cart->id); $removed_event_title = $removed_event->event->title; CRM_Core_Session::setStatus(ts("<b>%1</b> has been removed from your cart.", array(1 => $removed_event_title)), '', 'success'); $transaction->commit(); return CRM_Utils_System::redirect($_SERVER['HTTP_REFERER']); }
/** * @param array $params * * @return object $this|CRM_Event_Cart_BAO_EventInCart * @throws Exception */ public static function create(&$params) { $transaction = new CRM_Core_Transaction(); $event_in_cart = new CRM_Event_Cart_BAO_EventInCart(); $event_in_cart->copyValues($params); $event_in_cart = $event_in_cart->save(); if (is_a($event_in_cart, 'CRM_Core_Error')) { $transaction->rollback(); CRM_Core_Error::fatal(ts('There was an error creating an event_in_cart')); } $transaction->commit(); return $event_in_cart; }
/** * This function takes care of all the things common to all pages. * * This typically involves assigning the appropriate smarty variables :) */ public function run() { $transaction = new CRM_Core_Transaction(); $this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this, TRUE); if (!CRM_Core_Permission::event(CRM_Core_Permission::VIEW, $this->_id, 'register for events')) { CRM_Core_Error::fatal(ts('You do not have permission to register for this event')); } $cart = CRM_Event_Cart_BAO_Cart::find_or_create_for_current_session(); $event_in_cart = $cart->add_event($this->_id); $url = CRM_Utils_System::url('civicrm/event/view_cart'); CRM_Utils_System::setUFMessage(ts("<b>%1</b> has been added to your cart. <a href='%2'>View your cart.</a>", array(1 => $event_in_cart->event->title, 2 => $url))); $transaction->commit(); return CRM_Utils_System::redirect($_SERVER['HTTP_REFERER']); }
/** * Add or update a link between contribution and membership * * @param array $params (reference ) input parameters * * @return array (reference ) membership_payment_id of created or updated record * {@getfields MembershipPayment_create} * @example MembershipPaymentCreate.php * @access public */ function civicrm_api3_membership_payment_create($params) { require_once 'CRM/Core/Transaction.php'; $transaction = new CRM_Core_Transaction(); $mpDAO = new CRM_Member_DAO_MembershipPayment(); $mpDAO->copyValues($params); $result = $mpDAO->save(); if (is_a($result, 'CRM_Core_Error')) { $transaction->rollback(); return civicrm_api3_create_error($result->_errors[0]['message']); } $transaction->commit(); _civicrm_api3_object_to_array($mpDAO, $mpArray[$mpDAO->id]); return civicrm_api3_create_success($mpArray, $params); }
public static function UpgradeFromQueue(CRM_Queue_TaskContext $ctx, $mid, $params) { $today = new DateTime(); $membership = civicrm_api3('Membership', 'getsingle', array('id' => $mid)); $oldMembershipStatus = $params['rood_mstatus']; $migratie_lidmaatschappen_cg = civicrm_api3('CustomGroup', 'getvalue', array('return' => 'id', 'name' => 'Migratie_Lidmaatschappen')); $reason_fid = civicrm_api3('CustomField', 'getvalue', array('return' => 'id', 'name' => 'Reden', 'custom_group_id' => $migratie_lidmaatschappen_cg)); unset($membership['id']); $dao = CRM_Core_DAO::executeQuery("\n SELECT `c`.`id` AS `contribution_id`\nFROM `civicrm_membership`\nINNER JOIN `civicrm_membership_payment` `mp` ON `civicrm_membership`.`id` = `mp`.`membership_id`\nINNER JOIN `civicrm_contribution` `c` ON `mp`.`contribution_id` = `c`.`id` AND c.receive_date <= civicrm_membership.end_date\nWHERE civicrm_membership.id = %1\nORDER BY c.receive_date DESC\nLIMIT 0, 1", array(1 => array($mid, 'Integer'))); if ($dao->fetch()) { $contribution = self::getRenewalPayment($dao->contribution_id); $renewTransaction = new CRM_Core_Transaction(); $membership['membership_type_id'] = $params['sp_mtype']; $membership['start_date'] = $today->format('Ymd'); if ($today->format('m') >= 10) { $newEndDate = clone $today; $newEndDate->modify('last day of +1 year'); $membership['end_date'] = $newEndDate->format('Ymd'); } $new_membership = civicrm_api3('Membership', 'create', $membership); if ($contribution) { $contribution['financial_type_id'] = civicrm_api3('MembershipType', 'getvalue', array('return' => 'financial_type_id', 'id' => $params['sp_mtype'])); if ((double) $contribution['total_amount'] < (double) $params['minimum_fee']) { $contribution['total_amount'] = $params['minimum_fee']; } $result = civicrm_api3('Contribution', 'create', $contribution); // Get Soft contributions $softContributions = civicrm_api3('ContributionSoft', 'get', array('contribution_id' => $dao->contribution_id)); foreach ($softContributions['values'] as $softContribution) { $newSoftContribution = $softContribution; unset($newSoftContribution['id']); $newSoftContribution['contribution_id'] = $result['id']; civicrm_api3('ContributionSoft', 'create', $newSoftContribution); } $membershipPayment['contribution_id'] = $result['id']; $membershipPayment['membership_id'] = $new_membership['id']; civicrm_api3('MembershipPayment', 'create', $membershipPayment); } $oldMembership['id'] = $mid; $oldMembership['is_override'] = 1; $oldMembership['status_id'] = $oldMembershipStatus; $oldMembership['custom_' . $reason_fid] = '28 jarige'; $oldMembership['end_date'] = $today->format('Ymd'); civicrm_api3('Membership', 'create', $oldMembership); $renewTransaction->commit(); } return true; }
function run() { // get the requested action $action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'browse'); // assign vars to templates $this->assign('action', $action); $id = CRM_Utils_Request::retrieve('id', 'Positive', $this, FALSE, 0); if ($action & CRM_Core_Action::UPDATE) { $controller = new CRM_Core_Controller_Simple('CRM_Wci_Form_NewEmbedCode', 'Edit Embed Code', CRM_Core_Action::UPDATE); $controller->set('id', $id); $controller->process(); return $controller->run(); } elseif ($action & CRM_Core_Action::DELETE) { try { $transaction = new CRM_Core_Transaction(); $sql = "DELETE FROM civicrm_wci_embed_code where id = %1"; $params = array(1 => array($id, 'Integer')); CRM_Core_DAO::executeQuery($sql, $params); $transaction->commit(); } catch (Exception $e) { CRM_Core_Session::setStatus(ts('Failed to delete embed code. ') . $e->getMessage(), '', 'error'); $transaction->rollback(); } } CRM_Utils_System::setTitle(ts('Embed Code List')); $query = "SELECT * FROM civicrm_wci_embed_code"; $params = array(); $dao = CRM_Core_DAO::executeQuery($query, $params, TRUE, 'CRM_Wci_DAO_EmbedCode'); while ($dao->fetch()) { $emb_code[$dao->id] = array(); CRM_Core_DAO::storeValues($dao, $emb_code[$dao->id]); $emb_code[$dao->id]['id'] = $emb_code[$dao->id]['id']; $emb_code[$dao->id]['name'] = $emb_code[$dao->id]['name']; $action = array_sum(array_keys($this->actionLinks())); //build the normal action links. $emb_code[$dao->id]['action'] = CRM_Core_Action::formLink(self::actionLinks(), $action, array('id' => $dao->id)); } if (isset($emb_code)) { $this->assign('rows', $emb_code); } parent::run(); }
static function nodeapi(&$params, $op) { $transaction = new CRM_Core_Transaction(); // first create or update the CiviCRM group $groupParams = $params; $groupParams['source'] = CRM_Bridge_OG_Utils::ogSyncName($params['og_id']); $groupParams['group_type'] = array('2' => 1); self::updateCiviGroup($groupParams, $op); if (CRM_Bridge_OG_Utils::aclEnabled()) { // next create or update the CiviCRM ACL group $aclParams = $params; $aclParams['name'] = $aclParams['title'] = "{$aclParams['name']}: Administrator"; $aclParams['source'] = CRM_Bridge_OG_Utils::ogSyncACLName($params['og_id']); $aclParams['group_type'] = array('1'); self::updateCiviGroup($aclParams, $op); $aclParams['acl_group_id'] = $aclParams['group_id']; $aclParams['civicrm_group_id'] = $groupParams['group_id']; self::updateCiviACLTables($aclParams, $op); } $transaction->commit(); }
/** * Process the participant. * * @param CRM_Core_Form $form * @param int $contactID * * @return \CRM_Event_BAO_Participant */ public static function addParticipant(&$form, $contactID) { if (empty($form->_params)) { return NULL; } $params = $form->_params; $transaction = new CRM_Core_Transaction(); $groupName = 'participant_role'; $query = "\nSELECT v.label as label ,v.value as value\nFROM civicrm_option_value v,\n civicrm_option_group g\nWHERE v.option_group_id = g.id\n AND g.name = %1\n AND v.is_active = 1\n AND g.is_active = 1\n"; $p = array(1 => array($groupName, 'String')); $dao = CRM_Core_DAO::executeQuery($query, $p); if ($dao->fetch()) { $roleID = $dao->value; } // handle register date CRM-4320 $registerDate = NULL; if (!empty($form->_allowConfirmation) && $form->_participantId) { $registerDate = $params['participant_register_date']; } elseif (!empty($params['participant_register_date']) && is_array($params['participant_register_date']) && !empty($params['participant_register_date'])) { $registerDate = CRM_Utils_Date::format($params['participant_register_date']); } $participantFields = CRM_Event_DAO_Participant::fields(); $participantParams = array('id' => CRM_Utils_Array::value('participant_id', $params), 'contact_id' => $contactID, 'event_id' => $form->_eventId ? $form->_eventId : $params['event_id'], 'status_id' => CRM_Utils_Array::value('participant_status', $params, 1), 'role_id' => CRM_Utils_Array::value('participant_role_id', $params, $roleID), 'register_date' => $registerDate ? $registerDate : date('YmdHis'), 'source' => CRM_Utils_String::ellipsify(isset($params['participant_source']) ? CRM_Utils_Array::value('participant_source', $params) : CRM_Utils_Array::value('description', $params), $participantFields['participant_source']['maxlength']), 'fee_level' => CRM_Utils_Array::value('amount_level', $params), 'is_pay_later' => CRM_Utils_Array::value('is_pay_later', $params, 0), 'fee_amount' => CRM_Utils_Array::value('fee_amount', $params), 'registered_by_id' => CRM_Utils_Array::value('registered_by_id', $params), 'discount_id' => CRM_Utils_Array::value('discount_id', $params), 'fee_currency' => CRM_Utils_Array::value('currencyID', $params), 'campaign_id' => CRM_Utils_Array::value('campaign_id', $params)); if ($form->_action & CRM_Core_Action::PREVIEW || CRM_Utils_Array::value('mode', $params) == 'test') { $participantParams['is_test'] = 1; } else { $participantParams['is_test'] = 0; } if (!empty($form->_params['note'])) { $participantParams['note'] = $form->_params['note']; } elseif (!empty($form->_params['participant_note'])) { $participantParams['note'] = $form->_params['participant_note']; } // reuse id if one already exists for this one (can happen // with back button being hit etc) if (!$participantParams['id'] && !empty($params['contributionID'])) { $pID = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $params['contributionID'], 'participant_id', 'contribution_id'); $participantParams['id'] = $pID; } $participantParams['discount_id'] = CRM_Core_BAO_Discount::findSet($form->_eventId, 'civicrm_event'); if (!$participantParams['discount_id']) { $participantParams['discount_id'] = "null"; } $participant = CRM_Event_BAO_Participant::create($participantParams); $transaction->commit(); return $participant; }
/** * Delete membership. * * @param int $membershipId * Membership id that needs to be deleted. * * @return int * Id of deleted Membership on success, false otherwise. */ public static function deleteMembership($membershipId) { // CRM-12147, retrieve membership data before we delete it for hooks $params = array('id' => $membershipId); $memValues = array(); $memberships = self::getValues($params, $memValues); $membership = $memberships[$membershipId]; CRM_Utils_Hook::pre('delete', 'Membership', $membershipId, $memValues); $transaction = new CRM_Core_Transaction(); $results = NULL; //delete activity record $activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, FALSE, FALSE, 'name'); $params = array(); $deleteActivity = FALSE; $membershipActivities = array('Membership Signup', 'Membership Renewal', 'Change Membership Status', 'Change Membership Type', 'Membership Renewal Reminder'); foreach ($membershipActivities as $membershipActivity) { $activityId = array_search($membershipActivity, $activityTypes); if ($activityId) { $params['activity_type_id'][] = $activityId; $deleteActivity = TRUE; } } if ($deleteActivity) { $params['source_record_id'] = $membershipId; CRM_Activity_BAO_Activity::deleteActivity($params); } self::deleteMembershipPayment($membershipId); $results = $membership->delete(); $transaction->commit(); CRM_Utils_Hook::post('delete', 'Membership', $membership->id, $membership); // delete the recently created Membership $membershipRecent = array('id' => $membershipId, 'type' => 'Membership'); CRM_Utils_Recent::del($membershipRecent); return $results; }
/** * Delete the campaign page. * * @param int $id * Campaign page id. * * @return; */ public static function deleteById($id) { CRM_Utils_Hook::pre('delete', 'Campaign', $id, CRM_Core_DAO::$_nullArray); $transaction = new CRM_Core_Transaction(); // delete from pcp table $pcp = new CRM_PCP_DAO_PCP(); $pcp->id = $id; $pcp->delete(); $transaction->commit(); CRM_Utils_Hook::post('delete', 'Campaign', $id, $pcp); }
/** * Delete the record that are associated with this case * record are deleted from case * * @param int $caseId id of the case to delete * * @param bool $moveToTrash * * @return bool is successful * @access public * @static */ static function deleteCase($caseId, $moveToTrash = FALSE) { CRM_Utils_Hook::pre('delete', 'Case', $caseId, CRM_Core_DAO::$_nullArray); //delete activities $activities = self::getCaseActivityDates($caseId); if ($activities) { foreach ($activities as $value) { CRM_Activity_BAO_Activity::deleteActivity($value, $moveToTrash); } } if (!$moveToTrash) { $transaction = new CRM_Core_Transaction(); } $case = new CRM_Case_DAO_Case(); $case->id = $caseId; if (!$moveToTrash) { $result = $case->delete(); $transaction->commit(); } else { $result = $case->is_deleted = 1; $case->save(); } if ($result) { // CRM-7364, disable relationships self::enableDisableCaseRelationships($caseId, FALSE); CRM_Utils_Hook::post('delete', 'Case', $caseId, $case); // remove case from recent items. $caseRecent = array('id' => $caseId, 'type' => 'Case'); CRM_Utils_Recent::del($caseRecent); return TRUE; } return FALSE; }
/** * Delete the records that are associated with this participation. * * @param int $id * Id of the participation to delete. * * @return \CRM_Event_DAO_Participant */ public static function deleteParticipant($id) { CRM_Utils_Hook::pre('delete', 'Participant', $id, CRM_Core_DAO::$_nullArray); $transaction = new CRM_Core_Transaction(); //delete activity record $params = array('source_record_id' => $id, 'activity_type_id' => 5); CRM_Activity_BAO_Activity::deleteActivity($params); // delete the participant payment record // we need to do this since the cascaded constraints // dont work with join tables $p = array('participant_id' => $id); CRM_Event_BAO_ParticipantPayment::deleteParticipantPayment($p); // cleanup line items. $participantsId = array(); $participantsId = self::getAdditionalParticipantIds($id); $participantsId[] = $id; CRM_Price_BAO_LineItem::deleteLineItems($participantsId, 'civicrm_participant'); //delete note when participant deleted. $note = CRM_Core_BAO_Note::getNote($id, 'civicrm_participant'); $noteId = key($note); if ($noteId) { CRM_Core_BAO_Note::del($noteId, FALSE); } $participant = new CRM_Event_DAO_Participant(); $participant->id = $id; $participant->delete(); $transaction->commit(); CRM_Utils_Hook::post('delete', 'Participant', $participant->id, $participant); // delete the recently created Participant $participantRecent = array('id' => $id, 'type' => 'Participant'); CRM_Utils_Recent::del($participantRecent); return $participant; }
/** * Delete the indirect records associated with this contribution first * * @return $results no of deleted Contribution on success, false otherwise * @access public * @static */ static function deleteContribution($id) { require_once 'CRM/Utils/Hook.php'; CRM_Utils_Hook::pre('delete', 'Contribution', $id, CRM_Core_DAO::$_nullArray); require_once 'CRM/Core/Transaction.php'; $transaction = new CRM_Core_Transaction(); $results = null; //delete activity record require_once "CRM/Activity/BAO/Activity.php"; $params = array('source_record_id' => $id, 'activity_type_id' => 6); // activity type id for contribution CRM_Activity_BAO_Activity::deleteActivity($params); //delete billing address if exists for this contribution. self::deleteAddress($id); //update pledge and pledge payment, CRM-3961 require_once 'CRM/Pledge/BAO/Payment.php'; CRM_Pledge_BAO_Payment::resetPledgePayment($id); // remove entry from civicrm_price_set_entity, CRM-5095 require_once 'CRM/Price/BAO/Set.php'; if (CRM_Price_BAO_Set::getFor('civicrm_contribution', $id)) { CRM_Price_BAO_Set::removeFrom('civicrm_contribution', $id); } // cleanup line items. require_once 'CRM/Price/BAO/Field.php'; require_once 'CRM/Event/BAO/ParticipantPayment.php'; $participantId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id'); // delete any related entity_financial_trxn and financial_trxn records. require_once 'CRM/Core/BAO/FinancialTrxn.php'; CRM_Core_BAO_FinancialTrxn::deleteFinancialTrxn($id, 'civicrm_contribution'); if ($participantId) { require_once 'CRM/Price/BAO/LineItem.php'; CRM_Price_BAO_LineItem::deleteLineItems($participantId, 'civicrm_participant'); } else { require_once 'CRM/Price/BAO/LineItem.php'; CRM_Price_BAO_LineItem::deleteLineItems($id, 'civicrm_contribution'); } $dao = new CRM_Contribute_DAO_Contribution(); $dao->id = $id; $results = $dao->delete(); $transaction->commit(); CRM_Utils_Hook::post('delete', 'Contribution', $dao->id, $dao); // delete the recently created Contribution require_once 'CRM/Utils/Recent.php'; $contributionRecent = array('id' => $id, 'type' => 'Contribution'); CRM_Utils_Recent::del($contributionRecent); return $results; }
/** * Create WordPress user from contacts * * @access private * * @param array $rows The contacts data array * @return void */ private function createUsers($rows) { // set debug flag when testing $debug = false; // init debug arrays $users = array(); $messages = array(); // extend PHP's execution time ini_set('max_execution_time', 300); // get default role only once $default_role = get_option('default_role'); // get Civi config object $config = CRM_Core_Config::singleton(); // code for redirect grabbed from CRM_Contact_Form_Task_Delete::postProcess() $urlParams = 'force=1'; $urlString = "civicrm/contact/search/advanced"; // let WordPress plugins know what we're about to do do_action('civicrm_wp_profile_sync_user_add_pre'); // disable Civi's own register hook remove_action('user_register', array(civi_wp(), 'update_user')); remove_action('profile_update', array($this, 'update_user')); // process data foreach ($rows as $row) { // skip if no email if (empty($row['email'])) { continue; } // skip if email is not valid if (!is_email($row['email'])) { continue; } // skip if email already exists if (email_exists($row['email'])) { $messages[] = $row['email'] . ' already exists'; continue; } // filter names $first_name = $this->filterName($row['first_name']); $middle_name = $this->filterName($row['middle_name']); $last_name = $this->filterName($row['last_name']); // lots of first names are simply initials - if so, use both first and middle names if (strlen($first_name) == 1) { $first_name .= $middle_name; } // lets only take a maximum of 8 letters of the last name $last_name = substr($last_name, 0, 8); // concatenate first and last names $uname = $first_name . $last_name; // construct a likely username $uname = sanitize_user($uname); // skip if username not valid if (!validate_username($uname)) { $messages[] = 'username ' . $uname . ' is not valid'; continue; } // does this username already exist? if (username_exists($uname)) { $messages[] = 'username ' . $uname . ' already exists'; $messages[] = $row; // let's try adding in the middle name $uname = $first_name . $middle_name . $last_name; // construct a likely username $uname = sanitize_user($uname); // skip if username not valid if (!validate_username($uname)) { $messages[] = 'username ' . $uname . ' is not valid'; continue; } // skip if this username already exists if (username_exists($uname)) { $messages[] = 'extra username ' . $uname . ' already exists'; continue; } else { $messages[] = 'extra username ' . $uname . ' does not exist - we could add it'; } } /** * We cannot create WP user using CRM_Core_BAO_CMSUser::create() because it * will attempt to log the user in and notify them of their new account. We * have to find another means to do this. * * In the meantime, what follows is cloned from the CiviCRM process for * creating WordPress users and modified accordingly. */ // create an arbitrary password $password = substr(md5(uniqid(microtime())), 0, 8); // populate user data $user_data = array('ID' => '', 'user_login' => $uname, 'user_email' => $row['email'], 'user_pass' => $password, 'nickname' => $uname, 'role' => $default_role, 'first_name' => $row['first_name'], 'last_name' => $row['last_name']); // skip if debugging if (!$debug) { // add the user $user_id = wp_insert_user($user_data); // if contact doesn't already exist create UF Match if ($user_id !== FALSE && isset($row['id'])) { $transaction = new CRM_Core_Transaction(); // create the UF Match record $ufmatch = new CRM_Core_DAO_UFMatch(); $ufmatch->domain_id = CRM_Core_Config::domainID(); $ufmatch->uf_id = $user_id; $ufmatch->contact_id = $row['id']; $ufmatch->uf_name = $row['mail']; if (!$ufmatch->find(TRUE)) { $ufmatch->save(); $ufmatch->free(); $transaction->commit(); } } } else { // add to debug array $users[] = $user_data; } } // if debugging die now if ($debug) { trigger_error(print_r(array('method' => 'createUsers', 'messages' => $messages, 'count' => count($messages), 'users' => $users), true), E_USER_ERROR); die; } // re-enable Civi's register hook add_action('user_register', array(civi_wp(), 'update_user')); // let WordPress plugins know what we've done do_action('civicrm_wp_profile_sync_user_add_post'); // set a message CRM_Core_Session::setStatus('', ts('Users Added to WordPress'), 'success'); // redirect? CRM_Utils_System::redirect(CRM_Utils_System::url($urlString, $urlParams)); }
/** * 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; }
/** * Process the form submission. */ public function postProcess() { // get the submitted form values. $params = $this->controller->exportValues($this->_name); if ($this->_action & CRM_Core_Action::DELETE) { if (CRM_Utils_Array::value('delete_participant', $params) == 2) { $additionalId = CRM_Event_BAO_Participant::getAdditionalParticipantIds($this->_id); $participantLinks = CRM_Event_BAO_Participant::getAdditionalParticipantUrl($additionalId); } if (CRM_Utils_Array::value('delete_participant', $params) == 1) { $additionalIds = CRM_Event_BAO_Participant::getAdditionalParticipantIds($this->_id); foreach ($additionalIds as $value) { CRM_Event_BAO_Participant::deleteParticipant($value); } } CRM_Event_BAO_Participant::deleteParticipant($this->_id); CRM_Core_Session::setStatus(ts('Selected participant was deleted successfully.'), ts('Record Deleted'), 'success'); if (!empty($participantLinks)) { $status = ts('The following participants no longer have an event fee recorded. You can edit their registration and record a replacement contribution by clicking the links below:') . '<br/>' . $participantLinks; CRM_Core_Session::setStatus($status, ts('Group Payment Deleted')); } return; } // When adding a single contact, the formRule prevents you from adding duplicates // (See above in formRule()). When adding more than one contact, the duplicates are // removed automatically and the user receives one notification. if ($this->_action & CRM_Core_Action::ADD) { $event_id = $this->_eventId; if (empty($event_id) && !empty($params['event_id'])) { $event_id = $params['event_id']; } if (!$this->_single && !empty($event_id)) { $duplicateContacts = 0; while (list($k, $dupeCheckContactId) = each($this->_contactIds)) { // Eliminate contacts that have already been assigned to this event. $dupeCheck = new CRM_Event_BAO_Participant(); $dupeCheck->contact_id = $dupeCheckContactId; $dupeCheck->event_id = $event_id; $dupeCheck->find(TRUE); if (!empty($dupeCheck->id)) { $duplicateContacts++; unset($this->_contactIds[$k]); } } if ($duplicateContacts > 0) { $msg = ts("%1 contacts have already been assigned to this event. They were not added a second time.", array(1 => $duplicateContacts)); CRM_Core_Session::setStatus($msg); } if (count($this->_contactIds) == 0) { CRM_Core_Session::setStatus(ts("No participants were added.")); return; } // We have to re-key $this->_contactIds so each contact has the same // key as their corresponding record in the $participants array that // will be created below. $this->_contactIds = array_values($this->_contactIds); } } $participantStatus = CRM_Event_PseudoConstant::participantStatus(); // set the contact, when contact is selected if (!empty($params['contact_id'])) { $this->_contactId = $params['contact_id']; } if ($this->_priceSetId && ($isQuickConfig = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config'))) { $this->_quickConfig = $isQuickConfig; } if ($this->_id) { $params['id'] = $this->_id; } $config = CRM_Core_Config::singleton(); if ($this->_isPaidEvent) { $contributionParams = array(); $lineItem = array(); $additionalParticipantDetails = array(); if (CRM_Contribute_BAO_Contribution::checkContributeSettings('deferred_revenue_enabled')) { $eventStartDate = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $this->_eventId, 'start_date'); if ($eventStartDate) { $contributionParams['revenue_recognition_date'] = date('Ymd', strtotime($eventStartDate)); } } if ($this->_id && $this->_action & CRM_Core_Action::UPDATE && $this->_paymentId) { $participantBAO = new CRM_Event_BAO_Participant(); $participantBAO->id = $this->_id; $participantBAO->find(TRUE); $contributionParams['total_amount'] = $participantBAO->fee_amount; $params['discount_id'] = NULL; //re-enter the values for UPDATE mode $params['fee_level'] = $params['amount_level'] = $participantBAO->fee_level; $params['fee_amount'] = $participantBAO->fee_amount; if (isset($params['priceSetId'])) { $lineItem[0] = CRM_Price_BAO_LineItem::getLineItems($this->_id); } //also add additional participant's fee level/priceset if (CRM_Event_BAO_Participant::isPrimaryParticipant($this->_id)) { $additionalIds = CRM_Event_BAO_Participant::getAdditionalParticipantIds($this->_id); $hasLineItems = CRM_Utils_Array::value('priceSetId', $params, FALSE); $additionalParticipantDetails = CRM_Event_BAO_Participant::getFeeDetails($additionalIds, $hasLineItems); } } else { //check if discount is selected if (!empty($params['discount_id'])) { $discountId = $params['discount_id']; } else { $discountId = $params['discount_id'] = 'null'; } //lets carry currency, CRM-4453 $params['fee_currency'] = $config->defaultCurrency; CRM_Price_BAO_PriceSet::processAmount($this->_values['fee'], $params, $lineItem[0]); //CRM-11529 for quick config backoffice transactions //when financial_type_id is passed in form, update the //lineitems with the financial type selected in form $submittedFinancialType = CRM_Utils_Array::value('financial_type_id', $params); $isPaymentRecorded = CRM_Utils_Array::value('record_contribution', $params); if ($isPaymentRecorded && $this->_quickConfig && $submittedFinancialType) { foreach ($lineItem[0] as &$values) { $values['financial_type_id'] = $submittedFinancialType; } } $params['fee_level'] = $params['amount_level']; $contributionParams['total_amount'] = $params['amount']; if ($this->_quickConfig && !empty($params['total_amount']) && $params['status_id'] != array_search('Partially paid', $participantStatus)) { $params['fee_amount'] = $params['total_amount']; } else { //fix for CRM-3086 $params['fee_amount'] = $params['amount']; } } if (isset($params['priceSetId'])) { if (!empty($lineItem[0])) { $this->set('lineItem', $lineItem); $this->_lineItem = $lineItem; $lineItem = array_merge($lineItem, $additionalParticipantDetails); $participantCount = array(); foreach ($lineItem as $k) { foreach ($k as $v) { if (CRM_Utils_Array::value('participant_count', $v) > 0) { $participantCount[] = $v['participant_count']; } } } } if (isset($participantCount)) { $this->assign('pricesetFieldsCount', $participantCount); } $this->assign('lineItem', empty($lineItem[0]) || $this->_quickConfig ? FALSE : $lineItem); } else { $this->assign('amount_level', $params['amount_level']); } } $this->_params = $params; $amountOwed = NULL; if (isset($params['amount'])) { $amountOwed = $params['amount']; unset($params['amount']); } $params['register_date'] = CRM_Utils_Date::processDate($params['register_date'], $params['register_date_time']); $params['receive_date'] = CRM_Utils_Date::processDate(CRM_Utils_Array::value('receive_date', $params), CRM_Utils_Array::value('receive_date_time', $params)); $params['contact_id'] = $this->_contactId; // overwrite actual payment amount if entered if (!empty($params['total_amount'])) { $contributionParams['total_amount'] = CRM_Utils_Array::value('total_amount', $params); } // Retrieve the name and email of the current user - this will be the FROM for the receipt email $userName = CRM_Core_Session::singleton()->getLoggedInContactDisplayName(); if ($this->_contactId) { list($this->_contributorDisplayName, $this->_contributorEmail, $this->_toDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($this->_contactId); } //modify params according to parameter used in create //participant method (addParticipant) $this->_params['participant_status_id'] = $params['status_id']; $this->_params['participant_role_id'] = is_array($params['role_id']) ? $params['role_id'] : explode(',', $params['role_id']); $this->_params['participant_register_date'] = $params['register_date']; $roleIdWithSeparator = implode(CRM_Core_DAO::VALUE_SEPARATOR, $this->_params['participant_role_id']); if ($this->_mode) { if (!$this->_isPaidEvent) { CRM_Core_Error::fatal(ts('Selected Event is not Paid Event ')); } $eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'title'); // set source if not set if (empty($params['source'])) { $this->_params['participant_source'] = ts('Offline Registration for Event: %2 by: %1', array(1 => $userName, 2 => $eventTitle)); } else { $this->_params['participant_source'] = $params['source']; } $this->_params['description'] = $this->_params['participant_source']; $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($this->_params['payment_processor_id'], $this->_mode); $now = date('YmdHis'); $fields = array(); // set email for primary location. $fields['email-Primary'] = 1; $params['email-Primary'] = $params["email-{$this->_bltID}"] = $this->_contributorEmail; $params['register_date'] = $now; // now set the values for the billing location. foreach ($this->_fields as $name => $dontCare) { $fields[$name] = 1; } // also add location name to the array $params["address_name-{$this->_bltID}"] = CRM_Utils_Array::value('billing_first_name', $params) . ' ' . CRM_Utils_Array::value('billing_middle_name', $params) . ' ' . CRM_Utils_Array::value('billing_last_name', $params); $params["address_name-{$this->_bltID}"] = trim($params["address_name-{$this->_bltID}"]); $fields["address_name-{$this->_bltID}"] = 1; $fields["email-{$this->_bltID}"] = 1; $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactId, 'contact_type'); $nameFields = array('first_name', 'middle_name', 'last_name'); foreach ($nameFields as $name) { $fields[$name] = 1; if (array_key_exists("billing_{$name}", $params)) { $params[$name] = $params["billing_{$name}"]; $params['preserveDBName'] = TRUE; } } $contactID = CRM_Contact_BAO_Contact::createProfileContact($params, $fields, $this->_contactId, NULL, NULL, $ctype); } if (!empty($this->_params['participant_role_id'])) { $customFieldsRole = array(); foreach ($this->_params['participant_role_id'] as $roleKey) { $customFieldsRole = CRM_Utils_Array::crmArrayMerge(CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, $roleKey, $this->_roleCustomDataTypeID), $customFieldsRole); } $customFieldsEvent = CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, CRM_Utils_Array::value('event_id', $params), $this->_eventNameCustomDataTypeID); $customFieldsEventType = CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, $this->_eventTypeId, $this->_eventTypeCustomDataTypeID); $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsRole, CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, NULL, NULL, TRUE)); $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsEvent, $customFields); $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsEventType, $customFields); $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $this->_id, 'Participant'); } //do cleanup line items if participant edit the Event Fee. if (($this->_lineItem || !isset($params['proceSetId'])) && !$this->_paymentId && $this->_id) { CRM_Price_BAO_LineItem::deleteLineItems($this->_id, 'civicrm_participant'); } if ($this->_mode) { // add all the additional payment params we need $this->_params["state_province-{$this->_bltID}"] = $this->_params["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($this->_params["billing_state_province_id-{$this->_bltID}"]); $this->_params["country-{$this->_bltID}"] = $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]); $this->_params['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($this->_params); $this->_params['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($this->_params); $this->_params['ip_address'] = CRM_Utils_System::ipAddress(); $this->_params['amount'] = $params['fee_amount']; $this->_params['amount_level'] = $params['amount_level']; $this->_params['currencyID'] = $config->defaultCurrency; $this->_params['invoiceID'] = md5(uniqid(rand(), TRUE)); // at this point we've created a contact and stored its address etc // all the payment processors expect the name and address to be in the // so we copy stuff over to first_name etc. $paymentParams = $this->_params; if (!empty($this->_params['send_receipt'])) { $paymentParams['email'] = $this->_contributorEmail; } // The only reason for merging in the 'contact_id' rather than ensuring it is set // is that this patch is being done around the time of the stable release // so more conservative approach is called for. // In fact the use of $params and $this->_params & $this->_contactId vs $contactID // needs rationalising. $mapParams = array_merge(array('contact_id' => $contactID), $this->_params); CRM_Core_Payment_Form::mapParams($this->_bltID, $mapParams, $paymentParams, TRUE); $payment = $this->_paymentProcessor['object']; // CRM-15622: fix for incorrect contribution.fee_amount $paymentParams['fee_amount'] = NULL; $result = $payment->doPayment($paymentParams); if (is_a($result, 'CRM_Core_Error')) { CRM_Core_Error::displaySessionError($result); CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/participant', "reset=1&action=add&cid={$this->_contactId}&context=participant&mode={$this->_mode}")); } if ($result) { $this->_params = array_merge($this->_params, $result); } $this->_params['receive_date'] = $now; if (!empty($this->_params['send_receipt'])) { $this->_params['receipt_date'] = $now; } else { $this->_params['receipt_date'] = NULL; } $this->set('params', $this->_params); $this->assign('trxn_id', $result['trxn_id']); $this->assign('receive_date', CRM_Utils_Date::processDate($this->_params['receive_date'])); //add contribution record $this->_params['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'financial_type_id'); $this->_params['mode'] = $this->_mode; //add contribution record $contributions[] = $contribution = CRM_Event_Form_Registration_Confirm::processContribution($this, $this->_params, $result, $contactID, FALSE); // add participant record $participants = array(); if (!empty($this->_params['role_id']) && is_array($this->_params['role_id'])) { $this->_params['role_id'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, $this->_params['role_id']); } //CRM-15372 patch to fix fee amount replacing amount $this->_params['fee_amount'] = $this->_params['amount']; $participants[] = CRM_Event_Form_Registration::addParticipant($this, $contactID); //add custom data for participant CRM_Core_BAO_CustomValueTable::postProcess($this->_params, 'civicrm_participant', $participants[0]->id, 'Participant'); //add participant payment $paymentParticipant = array('participant_id' => $participants[0]->id, 'contribution_id' => $contribution->id); $ids = array(); CRM_Event_BAO_ParticipantPayment::create($paymentParticipant, $ids); $this->_contactIds[] = $this->_contactId; } else { $participants = array(); if ($this->_single) { if ($params['role_id']) { $params['role_id'] = $roleIdWithSeparator; } else { $params['role_id'] = 'NULL'; } $participants[] = CRM_Event_BAO_Participant::create($params); } else { foreach ($this->_contactIds as $contactID) { $commonParams = $params; $commonParams['contact_id'] = $contactID; if ($commonParams['role_id']) { $commonParams['role_id'] = $commonParams['role_id'] = str_replace(',', CRM_Core_DAO::VALUE_SEPARATOR, $params['role_id']); } else { $commonParams['role_id'] = 'NULL'; } $participants[] = CRM_Event_BAO_Participant::create($commonParams); } } if (isset($params['event_id'])) { $eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'title'); } if ($this->_single) { $this->_contactIds[] = $this->_contactId; } $contributions = array(); if (!empty($params['record_contribution'])) { if (!empty($params['id'])) { if ($this->_onlinePendingContributionId) { $ids['contribution'] = $this->_onlinePendingContributionId; } else { $ids['contribution'] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $params['id'], 'contribution_id', 'participant_id'); } } unset($params['note']); //build contribution params if (!$this->_onlinePendingContributionId) { if (empty($params['source'])) { $contributionParams['source'] = ts('%1 : Offline registration (by %2)', array(1 => $eventTitle, 2 => $userName)); } else { $contributionParams['source'] = $params['source']; } } $contributionParams['currency'] = $config->defaultCurrency; $contributionParams['non_deductible_amount'] = 'null'; $contributionParams['receipt_date'] = !empty($params['send_receipt']) ? CRM_Utils_Array::value('receive_date', $params) : 'null'; $recordContribution = array('contact_id', 'financial_type_id', 'payment_instrument_id', 'trxn_id', 'contribution_status_id', 'receive_date', 'check_number', 'campaign_id'); foreach ($recordContribution as $f) { $contributionParams[$f] = CRM_Utils_Array::value($f, $params); if ($f == 'trxn_id') { $this->assign('trxn_id', $contributionParams[$f]); } } //insert financial type name in receipt. $this->assign('financialTypeName', CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', $contributionParams['financial_type_id'])); // legacy support $this->assign('contributionTypeName', CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', $contributionParams['financial_type_id'])); $contributionParams['skipLineItem'] = 1; if ($this->_id) { $contributionParams['contribution_mode'] = 'participant'; $contributionParams['participant_id'] = $this->_id; } // Set is_pay_later flag for back-office offline Pending status contributions if ($contributionParams['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Pending', 'name')) { $contributionParams['is_pay_later'] = 1; } elseif ($contributionParams['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name')) { $contributionParams['is_pay_later'] = 0; } if ($params['status_id'] == array_search('Partially paid', $participantStatus)) { if (!$amountOwed && $this->_action & CRM_Core_Action::UPDATE) { $amountOwed = $params['fee_amount']; } // if multiple participants are link, consider contribution total amount as the amount Owed if ($this->_id && CRM_Event_BAO_Participant::isPrimaryParticipant($this->_id)) { $amountOwed = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $ids['contribution'], 'total_amount'); } // CRM-13964 partial_payment_total if ($amountOwed > $params['total_amount']) { // the owed amount $contributionParams['partial_payment_total'] = $amountOwed; // the actual amount paid $contributionParams['partial_amount_pay'] = $params['total_amount']; } } if (CRM_Utils_Array::value('tax_amount', $this->_params)) { $contributionParams['tax_amount'] = $this->_params['tax_amount']; } if ($this->_single) { if (empty($ids)) { $ids = array(); } $contributions[] = CRM_Contribute_BAO_Contribution::create($contributionParams, $ids); } else { $ids = array(); foreach ($this->_contactIds as $contactID) { $contributionParams['contact_id'] = $contactID; $contributions[] = CRM_Contribute_BAO_Contribution::create($contributionParams, $ids); } } //insert payment record for this participation if (empty($ids['contribution'])) { foreach ($this->_contactIds as $num => $contactID) { $ppDAO = new CRM_Event_DAO_ParticipantPayment(); $ppDAO->participant_id = $participants[$num]->id; $ppDAO->contribution_id = $contributions[$num]->id; $ppDAO->save(); } } // next create the transaction record $transaction = new CRM_Core_Transaction(); // CRM-11124 if ($this->_params['discount_id']) { CRM_Event_BAO_Participant::createDiscountTrxn($this->_eventId, $contributionParams, NULL, CRM_Price_BAO_PriceSet::parseFirstPriceSetValueIDFromParams($this->_params)); } $transaction->commit(); } } // also store lineitem stuff here if ($this->_lineItem & $this->_action & CRM_Core_Action::ADD || $this->_lineItem && CRM_Core_Action::UPDATE && !$this->_paymentId) { foreach ($this->_contactIds as $num => $contactID) { foreach ($this->_lineItem as $key => $value) { if (is_array($value) && $value != 'skip') { foreach ($value as $lineKey => $line) { //10117 update the line items for participants if contribution amount is recorded if ($this->_quickConfig && !empty($params['total_amount']) && $params['status_id'] != array_search('Partially paid', $participantStatus)) { $line['unit_price'] = $line['line_total'] = $params['total_amount']; if (!empty($params['tax_amount'])) { $line['unit_price'] = $line['unit_price'] - $params['tax_amount']; $line['line_total'] = $line['line_total'] - $params['tax_amount']; } } $lineItem[$this->_priceSetId][$lineKey] = $line; } CRM_Price_BAO_LineItem::processPriceSet($participants[$num]->id, $lineItem, CRM_Utils_Array::value($num, $contributions, NULL), 'civicrm_participant'); CRM_Contribute_BAO_Contribution::addPayments($value, $contributions); } } } } $updateStatusMsg = NULL; //send mail when participant status changed, CRM-4326 if ($this->_id && $this->_statusId && $this->_statusId != CRM_Utils_Array::value('status_id', $params) && !empty($params['is_notify'])) { $updateStatusMsg = CRM_Event_BAO_Participant::updateStatusMessage($this->_id, $params['status_id'], $this->_statusId); } $sent = array(); $notSent = array(); if (!empty($params['send_receipt'])) { if (array_key_exists($params['from_email_address'], $this->_fromEmails['from_email_id'])) { $receiptFrom = $params['from_email_address']; } $this->assign('module', 'Event Registration'); //use of the message template below requires variables in different format $event = $events = array(); $returnProperties = array('fee_label', 'start_date', 'end_date', 'is_show_location', 'title'); //get all event details. CRM_Core_DAO::commonRetrieveAll('CRM_Event_DAO_Event', 'id', $params['event_id'], $events, $returnProperties); $event = $events[$params['event_id']]; unset($event['start_date']); unset($event['end_date']); $role = CRM_Event_PseudoConstant::participantRole(); $participantRoles = CRM_Utils_Array::value('role_id', $params); if (is_array($participantRoles)) { $selectedRoles = array(); foreach ($participantRoles as $roleId) { $selectedRoles[] = $role[$roleId]; } $event['participant_role'] = implode(', ', $selectedRoles); } else { $event['participant_role'] = CRM_Utils_Array::value($participantRoles, $role); } $event['is_monetary'] = $this->_isPaidEvent; if ($params['receipt_text']) { $event['confirm_email_text'] = $params['receipt_text']; } $this->assign('isAmountzero', 1); $this->assign('event', $event); $this->assign('isShowLocation', $event['is_show_location']); if (CRM_Utils_Array::value('is_show_location', $event) == 1) { $locationParams = array('entity_id' => $params['event_id'], 'entity_table' => 'civicrm_event'); $location = CRM_Core_BAO_Location::getValues($locationParams, TRUE); $this->assign('location', $location); } $status = CRM_Event_PseudoConstant::participantStatus(); if ($this->_isPaidEvent) { $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument(); if (!$this->_mode) { if (isset($params['payment_instrument_id'])) { $this->assign('paidBy', CRM_Utils_Array::value($params['payment_instrument_id'], $paymentInstrument)); } } $this->assign('totalAmount', $contributionParams['total_amount']); if (isset($contributionParams['partial_payment_total'])) { // balance amount $balanceAmount = $contributionParams['partial_payment_total'] - $contributionParams['partial_amount_pay']; $this->assign('balanceAmount', $balanceAmount); } $this->assign('isPrimary', 1); $this->assign('checkNumber', CRM_Utils_Array::value('check_number', $params)); } if ($this->_mode) { if (!empty($params['billing_first_name'])) { $name = $params['billing_first_name']; } if (!empty($params['billing_middle_name'])) { $name .= " {$params['billing_middle_name']}"; } if (!empty($params['billing_last_name'])) { $name .= " {$params['billing_last_name']}"; } $this->assign('billingName', $name); // assign the address formatted up for display $addressParts = array("street_address-{$this->_bltID}", "city-{$this->_bltID}", "postal_code-{$this->_bltID}", "state_province-{$this->_bltID}", "country-{$this->_bltID}"); $addressFields = array(); foreach ($addressParts as $part) { list($n, $id) = explode('-', $part); if (isset($this->_params['billing_' . $part])) { $addressFields[$n] = $this->_params['billing_' . $part]; } } $this->assign('address', CRM_Utils_Address::format($addressFields)); $date = CRM_Utils_Date::format($params['credit_card_exp_date']); $date = CRM_Utils_Date::mysqlToIso($date); $this->assign('credit_card_exp_date', $date); $this->assign('credit_card_number', CRM_Utils_System::mungeCreditCard($params['credit_card_number'])); $this->assign('credit_card_type', $params['credit_card_type']); // The concept of contributeMode is deprecated. $this->assign('contributeMode', 'direct'); $this->assign('isAmountzero', 0); $this->assign('is_pay_later', 0); $this->assign('isPrimary', 1); } $this->assign('register_date', $params['register_date']); if ($params['receive_date']) { $this->assign('receive_date', $params['receive_date']); } $participant = array(array('participant_id', '=', $participants[0]->id, 0, 0)); // check whether its a test drive ref CRM-3075 if (!empty($this->_defaultValues['is_test'])) { $participant[] = array('participant_test', '=', 1, 0, 0); } $template = CRM_Core_Smarty::singleton(); $customGroup = array(); //format submitted data foreach ($params['custom'] as $fieldID => $values) { foreach ($values as $fieldValue) { $customFields[$fieldID]['id'] = $fieldID; $formattedValue = CRM_Core_BAO_CustomField::displayValue($fieldValue['value'], $fieldID, $participants[0]->id); $customGroup[$customFields[$fieldID]['groupTitle']][$customFields[$fieldID]['label']] = str_replace(' ', '', $formattedValue); } } foreach ($this->_contactIds as $num => $contactID) { // Retrieve the name and email of the contact - this will be the TO for receipt email list($this->_contributorDisplayName, $this->_contributorEmail, $this->_toDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($contactID); $this->_contributorDisplayName = $this->_contributorDisplayName == ' ' ? $this->_contributorEmail : $this->_contributorDisplayName; $waitStatus = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Waiting'"); if ($waitingStatus = CRM_Utils_Array::value($params['status_id'], $waitStatus)) { $this->assign('isOnWaitlist', TRUE); } $this->assign('customGroup', $customGroup); $this->assign('contactID', $contactID); $this->assign('participantID', $participants[$num]->id); $this->_id = $participants[$num]->id; if ($this->_isPaidEvent) { // fix amount for each of participants ( for bulk mode ) $eventAmount = array(); $invoiceSettings = Civi::settings()->get('contribution_invoice_settings'); $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings); $totalTaxAmount = 0; //add dataArray in the receipts in ADD and UPDATE condition $dataArray = array(); if ($this->_action & CRM_Core_Action::ADD) { $line = $lineItem[0]; } elseif ($this->_action & CRM_Core_Action::UPDATE) { $line = $this->_values['line_items']; } if ($invoicing) { foreach ($line as $key => $value) { if (isset($value['tax_amount'])) { $totalTaxAmount += $value['tax_amount']; if (isset($dataArray[(string) $value['tax_rate']])) { $dataArray[(string) $value['tax_rate']] = $dataArray[(string) $value['tax_rate']] + CRM_Utils_Array::value('tax_amount', $value); } else { $dataArray[(string) $value['tax_rate']] = CRM_Utils_Array::value('tax_amount', $value); } } } $this->assign('totalTaxAmount', $totalTaxAmount); $this->assign('taxTerm', CRM_Utils_Array::value('tax_term', $invoiceSettings)); $this->assign('dataArray', $dataArray); } if (!empty($additionalParticipantDetails)) { $params['amount_level'] = preg_replace('//', '', $params['amount_level']) . ' - ' . $this->_contributorDisplayName; } $eventAmount[$num] = array('label' => preg_replace('//', '', $params['amount_level']), 'amount' => $params['fee_amount']); //as we are using same template for online & offline registration. //So we have to build amount as array. $eventAmount = array_merge($eventAmount, $additionalParticipantDetails); $this->assign('amount', $eventAmount); } $sendTemplateParams = array('groupName' => 'msg_tpl_workflow_event', 'valueName' => 'event_offline_receipt', 'contactId' => $contactID, 'isTest' => !empty($this->_defaultValues['is_test']), 'PDFFilename' => ts('confirmation') . '.pdf'); // try to send emails only if email id is present // and the do-not-email option is not checked for that contact if ($this->_contributorEmail and !$this->_toDoNotEmail) { $sendTemplateParams['from'] = $receiptFrom; $sendTemplateParams['toName'] = $this->_contributorDisplayName; $sendTemplateParams['toEmail'] = $this->_contributorEmail; $sendTemplateParams['cc'] = CRM_Utils_Array::value('cc', $this->_fromEmails); $sendTemplateParams['bcc'] = CRM_Utils_Array::value('bcc', $this->_fromEmails); } //send email with pdf invoice $template = CRM_Core_Smarty::singleton(); $taxAmt = $template->get_template_vars('dataArray'); $contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id, 'contribution_id', 'participant_id'); $prefixValue = Civi::settings()->get('contribution_invoice_settings'); $invoicing = CRM_Utils_Array::value('invoicing', $prefixValue); if (count($taxAmt) > 0 && (isset($invoicing) && isset($prefixValue['is_email_pdf']))) { $sendTemplateParams['isEmailPdf'] = TRUE; $sendTemplateParams['contributionId'] = $contributionId; } list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams); if ($mailSent) { $sent[] = $contactID; foreach ($participants as $ids => $values) { if ($values->contact_id == $contactID) { $values->details = CRM_Utils_Array::value('receipt_text', $params); CRM_Activity_BAO_Activity::addActivity($values, 'Email'); break; } } } else { $notSent[] = $contactID; } } } // set the participant id if it is not set if (!$this->_id) { $this->_id = $participants[0]->id; } if ($this->_action & CRM_Core_Action::UPDATE) { $statusMsg = ts('Event registration information for %1 has been updated.', array(1 => $this->_contributorDisplayName)); if (!empty($params['send_receipt']) && count($sent)) { $statusMsg .= ' ' . ts('A confirmation email has been sent to %1', array(1 => $this->_contributorEmail)); } if ($updateStatusMsg) { $statusMsg = "{$statusMsg} {$updateStatusMsg}"; } } elseif ($this->_action & CRM_Core_Action::ADD) { if ($this->_single) { $statusMsg = ts('Event registration for %1 has been added.', array(1 => $this->_contributorDisplayName)); if (!empty($params['send_receipt']) && count($sent)) { $statusMsg .= ' ' . ts('A confirmation email has been sent to %1.', array(1 => $this->_contributorEmail)); } } else { $statusMsg = ts('Total Participant(s) added to event: %1.', array(1 => count($this->_contactIds))); if (count($notSent) > 0) { $statusMsg .= ' ' . ts('Email has NOT been sent to %1 contact(s) - communication preferences specify DO NOT EMAIL OR valid Email is NOT present. ', array(1 => count($notSent))); } elseif (isset($params['send_receipt'])) { $statusMsg .= ' ' . ts('A confirmation email has been sent to ALL participants'); } } } CRM_Core_Session::setStatus($statusMsg, ts('Saved'), 'success'); $session = CRM_Core_Session::singleton(); $buttonName = $this->controller->getButtonName(); if ($this->_context == 'standalone') { if ($buttonName == $this->getButtonName('upload', 'new')) { $urlParams = 'reset=1&action=add&context=standalone'; if ($this->_mode) { $urlParams .= '&mode=' . $this->_mode; } if ($this->_eID) { $urlParams .= '&eid=' . $this->_eID; } $session->replaceUserContext(CRM_Utils_System::url('civicrm/participant/add', $urlParams)); } else { $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$this->_contactId}&selectedChild=participant")); } } elseif ($buttonName == $this->getButtonName('upload', 'new')) { $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/participant', "reset=1&action=add&context={$this->_context}&cid={$this->_contactId}")); } }
/** * This function deletes the activity record related to contact record. * * This is conditional on there being no target and assignee record * with other contacts. * * @param int $contactId * ContactId. * * @return true/null */ public static function cleanupActivity($contactId) { $result = NULL; if (!$contactId) { return $result; } $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name'); $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts); $transaction = new CRM_Core_Transaction(); // delete activity if there is no record in civicrm_activity_contact // pointing to any other contact record $activityContact = new CRM_Activity_DAO_ActivityContact(); $activityContact->contact_id = $contactId; $activityContact->record_type_id = $sourceID; $activityContact->find(); while ($activityContact->fetch()) { // delete activity_contact record for the deleted contact $activityContact->delete(); $activityContactOther = new CRM_Activity_DAO_ActivityContact(); $activityContactOther->activity_id = $activityContact->activity_id; // delete activity only if no other contacts connected if (!$activityContactOther->find(TRUE)) { $activityParams = array('id' => $activityContact->activity_id); $result = self::deleteActivity($activityParams); } $activityContactOther->free(); } $activityContact->free(); $transaction->commit(); return $result; }