/**
 * Get CiviCRM domain details
 * {@getfields domain_create}
 * @example DomainGet.php
 */
function civicrm_api3_domain_get($params)
{
    $params['version'] = CRM_Utils_Array::value('domain_version', $params);
    unset($params['version']);
    $bao = new CRM_Core_BAO_Domain();
    if (CRM_Utils_Array::value('current_domain', $params)) {
        $domainBAO = CRM_Core_Config::domainID();
        $params['id'] = $domainBAO;
    }
    _civicrm_api3_dao_set_filter($bao, $params, true, 'domain');
    $domains = _civicrm_api3_dao_to_array($bao, $params, true, 'domain');
    foreach ($domains as $domain) {
        if (!empty($domain['contact_id'])) {
            $values = array();
            $locparams = array('contact_id' => $domain['contact_id']);
            $values['location'] = CRM_Core_BAO_Location::getValues($locparams, TRUE);
            $address_array = array('street_address', 'supplemental_address_1', 'supplemental_address_2', 'city', 'state_province_id', 'postal_code', 'country_id', 'geo_code_1', 'geo_code_2');
            if (!empty($values['location']['email'])) {
                $domain['domain_email'] = CRM_Utils_Array::value('email', $values['location']['email'][1]);
            }
            if (!empty($values['location']['phone'])) {
                $domain['domain_phone'] = array('phone_type' => CRM_Core_PseudoConstant::getLabel('CRM_Core_BAO_Phone', 'phone_type_id', CRM_Utils_Array::value('phone_type_id', $values['location']['phone'][1])), 'phone' => CRM_Utils_Array::value('phone', $values['location']['phone'][1]));
            }
            if (!empty($values['location']['address'])) {
                foreach ($address_array as $value) {
                    $domain['domain_address'][$value] = CRM_Utils_Array::value($value, $values['location']['address'][1]);
                }
            }
            list($domain['from_name'], $domain['from_email']) = CRM_Core_BAO_Domain::getNameAndEmail(TRUE);
            $domains[$domain['id']] = array_merge($domains[$domain['id']], $domain);
        }
    }
    return civicrm_api3_create_success($domains, $params, 'domain', 'get', $bao);
}
Example #2
0
/**
 * Generic file to retrieve all the constants and
 * pseudo constants used in CiviCRM
 *
 */
function civicrm_domain_get()
{
    require_once 'CRM/Core/BAO/Domain.php';
    $dao = CRM_Core_BAO_Domain::getDomain();
    $values = array();
    $params = array('entity_id' => $dao->id, 'entity_table' => 'civicrm_domain');
    require_once 'CRM/Core/BAO/Location.php';
    $values['location'] = CRM_Core_BAO_Location::getValues($params, true);
    $address_array = array('street_address', 'supplemental_address_1', 'supplemental_address_2', 'city', 'state_province_id', 'postal_code', 'country_id', 'geo_code_1', 'geo_code_2');
    require_once 'CRM/Core/OptionGroup.php';
    $domain[$dao->id] = array('id' => $dao->id, 'domain_name' => $dao->name, 'description' => $dao->description, 'domain_email' => CRM_Utils_Array::value('email', $values['location']['email'][1]), 'domain_phone' => array('phone_type' => CRM_Core_OptionGroup::getLabel('phone_type', CRM_Utils_Array::value('phone_type_id', $values['location']['phone'][1])), 'phone' => CRM_Utils_Array::value('phone', $values['location']['phone'][1])));
    foreach ($address_array as $value) {
        $domain[$dao->id]['domain_address'][$value] = CRM_Utils_Array::value($value, $values['location']['address'][1]);
    }
    list($domain[$dao->id]['from_name'], $domain[$dao->id]['from_email']) = CRM_Core_BAO_Domain::getNameAndEmail();
    return $domain;
}
Example #3
0
 /**
  * Register a subscription event.  Create a new contact if one does not
  * already exist.
  *
  * @param int $domain_id        The domain id of the new subscription
  * @param int $group_id         The group id to subscribe to
  * @param string $email         The email address of the (new) contact
  * @return int|null $se_id      The id of the subscription event, null on failure
  * @access public
  * @static
  */
 function &subscribe($domain_id, $group_id, $email)
 {
     /* First, find out if the contact already exists */
     $params = array('email' => $email, 'domain_id' => $domain_id);
     require_once 'CRM/Core/BAO/UFGroup.php';
     $contact_id = CRM_Core_BAO_UFGroup::findContact($params);
     CRM_Core_DAO::transaction('BEGIN');
     if (is_a($contact_id, CRM_Core_Error)) {
         require_once 'CRM/Core/BAO/LocationType.php';
         /* If the contact does not exist, create one. */
         $formatted = array('contact_type' => 'Individual');
         $value = array('email' => $email, 'location_type' => CRM_Core_BAO_LocationType::getDefaultID());
         _crm_add_formatted_param($value, $formatted);
         $contact =& crm_create_contact_formatted($formatted, CRM_IMPORT_PARSER_DUPLICATE_SKIP);
         if (is_a($contact, CRM_Core_Error)) {
             return null;
         }
         $contact_id = $contact->id;
     }
     require_once 'CRM/Core/BAO/Email.php';
     require_once 'CRM/Core/BAO/Location.php';
     require_once 'CRM/Contact/BAO/Contact.php';
     /* Get the primary email id from the contact to use as a hash input */
     $dao =& new CRM_Core_DAO();
     $emailTable = CRM_Core_BAO_Email::getTableName();
     $locTable = CRM_Core_BAO_Location::getTableName();
     $contactTable = CRM_Contact_BAO_Contact::getTableName();
     $dao->query("SELECT {$emailTable}.id as email_id\n                    FROM {$emailTable}\n                    INNER JOIN {$locTable}\n                        ON  {$emailTable}.location_id = {$locTable}.id\n                    WHERE   {$emailTable}.is_primary = 1\n                    AND     {$locTable}.is_primary = 1\n                    AND     {$locTable}.entity_table = '{$contactTable}'\n                    AND     {$locTable}.entity_id = " . CRM_Utils_Type::escape($contact_id, 'Integer'));
     $dao->fetch();
     $se =& new CRM_Mailing_Event_BAO_Subscribe();
     $se->group_id = $group_id;
     $se->contact_id = $contact_id;
     $se->time_stamp = date('YmdHis');
     $se->hash = sha1("{$group_id}:{$contact_id}:{$dao->email_id}");
     $se->save();
     $contacts = array($contact_id);
     require_once 'CRM/Contact/BAO/GroupContact.php';
     CRM_Contact_BAO_GroupContact::addContactsToGroup($contacts, $group_id, 'Email', 'Pending', $se->id);
     CRM_Core_DAO::transaction('COMMIT');
     return $se;
 }
 static function register($extension)
 {
     if ($domain_id = CRM_Core_Config::domainID()) {
         // Gather information from domain settings
         $params = array('id' => $domain_id);
         CRM_Core_BAO_Domain::retrieve($params, $domain);
         unset($params['id']);
         $locParams = $params + array('entity_id' => $domain_id, 'entity_table' => 'civicrm_domain');
         $defaults = CRM_Core_BAO_Location::getValues($locParams);
         foreach (array('address', 'phone', 'email') as $info) {
             $domain[$info] = reset(CRM_Utils_Array::value($info, $defaults));
         }
         // Create registration parameters
         $registration = array('extension' => $extension, 'organization_name' => $domain['name'], 'description' => $domain['description']);
         foreach (array('street_address', 'supplemental_address_1', 'supplemental_address_2', 'city', 'postal_code', 'state_province_id', 'country_id') as $field) {
             $registration[$field] = CRM_Utils_Array::value($field, $domain['address']);
         }
         $registration['phone'] = $domain['phone']['phone'];
         $registration['email'] = $domain['email']['email'];
         return self::_rest_helper('http://my.cividesk.com/register.php', $registration, 'POST');
     }
     return false;
 }
Example #5
0
/**
 *
 * @param <type> $contact
 * @param <type> $locationTypes = array( 'Home', 'Work' ) else empty.
 * @return <type>
 */
function &_civicrm_location_get($contact, $locationTypes = array())
{
    $params = array('contact_id' => $contact['contact_id'], 'entity_id' => $contact['contact_id']);
    require_once 'CRM/Core/BAO/Location.php';
    $locations = CRM_Core_BAO_Location::getValues($params);
    $locValues = array();
    // filter the blocks return only those from given loc type.
    if (is_array($locationTypes) && !empty($locationTypes)) {
        foreach ($locationTypes as $locName) {
            if (!$locName) {
                continue;
            }
            if ($locTypeId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_LocationType', $locName, 'id', 'name')) {
                foreach (array('email', 'im', 'phone', 'address', 'openid') as $name) {
                    if (!array_key_exists($name, $locations) || !is_array($locations[$name])) {
                        continue;
                    }
                    $blkCount = 0;
                    if (array_key_exists($name, $locValues)) {
                        $blkCount = count($locValues[$name]);
                    }
                    foreach ($locations[$name] as $count => $values) {
                        if ($locTypeId == $values['location_type_id']) {
                            $locValues[$name][++$blkCount] = $values;
                        }
                    }
                }
            }
        }
    } else {
        $locValues = $locations;
    }
    // CRM-4800
    if ('3.0' != CRM_Utils_Array::value('version', $contact)) {
        _civicrm_location_get_v3_to_v2($locValues);
    }
    return $locValues;
}
Example #6
0
 /**
  * Run the page.
  *
  * This method is called after the page is created. It checks for the
  * type of action and executes that action.
  * Finally it calls the parent's run method.
  *
  * @return void
  */
 public function run()
 {
     //get the event id.
     $this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this, TRUE);
     $config = CRM_Core_Config::singleton();
     // ensure that the user has permission to see this page
     if (!CRM_Core_Permission::event(CRM_Core_Permission::VIEW, $this->_id, 'view event info')) {
         CRM_Utils_System::setUFMessage(ts('You do not have permission to view this event'));
         return CRM_Utils_System::permissionDenied();
     }
     $action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE);
     $context = CRM_Utils_Request::retrieve('context', 'String', $this, FALSE, 'register');
     $this->assign('context', $context);
     // Sometimes we want to suppress the Event Full msg
     $noFullMsg = CRM_Utils_Request::retrieve('noFullMsg', 'String', $this, FALSE, 'false');
     // set breadcrumb to append to 2nd layer pages
     $breadCrumbPath = CRM_Utils_System::url('civicrm/event/info', "id={$this->_id}&reset=1");
     //retrieve event information
     $params = array('id' => $this->_id);
     CRM_Event_BAO_Event::retrieve($params, $values['event']);
     if (!$values['event']['is_active']) {
         // form is inactive, die a fatal death
         CRM_Utils_System::setUFMessage(ts('The event you requested is currently unavailable (contact the site administrator for assistance).'));
         return CRM_Utils_System::permissionDenied();
     }
     if (!empty($values['event']['is_template'])) {
         // form is an Event Template
         CRM_Core_Error::fatal(ts('The page you requested is currently unavailable.'));
     }
     // Add Event Type to $values in case folks want to display it
     $values['event']['event_type'] = CRM_Utils_Array::value($values['event']['event_type_id'], CRM_Event_PseudoConstant::eventType());
     $this->assign('isShowLocation', CRM_Utils_Array::value('is_show_location', $values['event']));
     // show event fees.
     if ($this->_id && !empty($values['event']['is_monetary'])) {
         //CRM-6907
         $config = CRM_Core_Config::singleton();
         $config->defaultCurrency = CRM_Utils_Array::value('currency', $values['event'], $config->defaultCurrency);
         //CRM-10434
         $discountId = CRM_Core_BAO_Discount::findSet($this->_id, 'civicrm_event');
         if ($discountId) {
             $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Discount', $discountId, 'price_set_id');
         } else {
             $priceSetId = CRM_Price_BAO_PriceSet::getFor('civicrm_event', $this->_id);
         }
         // get price set options, - CRM-5209
         if ($priceSetId) {
             $setDetails = CRM_Price_BAO_PriceSet::getSetDetail($priceSetId, TRUE, TRUE);
             $priceSetFields = $setDetails[$priceSetId]['fields'];
             if (is_array($priceSetFields)) {
                 $fieldCnt = 1;
                 $visibility = CRM_Core_PseudoConstant::visibility('name');
                 // CRM-14492 Admin price fields should show up on event registration if user has 'administer CiviCRM' permissions
                 $adminFieldVisible = FALSE;
                 if (CRM_Core_Permission::check('administer CiviCRM')) {
                     $adminFieldVisible = TRUE;
                 }
                 foreach ($priceSetFields as $fid => $fieldValues) {
                     if (!is_array($fieldValues['options']) || empty($fieldValues['options']) || CRM_Utils_Array::value('visibility_id', $fieldValues) != array_search('public', $visibility) && $adminFieldVisible == FALSE) {
                         continue;
                     }
                     if (count($fieldValues['options']) > 1) {
                         $values['feeBlock']['value'][$fieldCnt] = '';
                         $values['feeBlock']['label'][$fieldCnt] = $fieldValues['label'];
                         $values['feeBlock']['lClass'][$fieldCnt] = 'price_set_option_group-label';
                         $values['feeBlock']['isDisplayAmount'][$fieldCnt] = CRM_Utils_Array::value('is_display_amounts', $fieldValues);
                         $fieldCnt++;
                         $labelClass = 'price_set_option-label';
                     } else {
                         $labelClass = 'price_set_field-label';
                     }
                     // show tax rate with amount
                     $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
                     $taxTerm = CRM_Utils_Array::value('tax_term', $invoiceSettings);
                     $displayOpt = CRM_Utils_Array::value('tax_display_settings', $invoiceSettings);
                     $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
                     foreach ($fieldValues['options'] as $optionId => $optionVal) {
                         $values['feeBlock']['isDisplayAmount'][$fieldCnt] = CRM_Utils_Array::value('is_display_amounts', $fieldValues);
                         if ($invoicing && isset($optionVal['tax_amount'])) {
                             $values['feeBlock']['value'][$fieldCnt] = CRM_Price_BAO_PriceField::getTaxLabel($optionVal, 'amount', $displayOpt, $taxTerm);
                             $values['feeBlock']['tax_amount'][$fieldCnt] = $optionVal['tax_amount'];
                         } else {
                             $values['feeBlock']['value'][$fieldCnt] = $optionVal['amount'];
                         }
                         $values['feeBlock']['label'][$fieldCnt] = $optionVal['label'];
                         $values['feeBlock']['lClass'][$fieldCnt] = $labelClass;
                         $fieldCnt++;
                     }
                 }
             }
             // Tell tpl we have price set fee data and whether it's a quick_config price set
             $this->assign('isPriceSet', 1);
             $this->assign('isQuickConfig', $setDetails[$priceSetId]['is_quick_config']);
         }
     }
     $params = array('entity_id' => $this->_id, 'entity_table' => 'civicrm_event');
     $values['location'] = CRM_Core_BAO_Location::getValues($params, TRUE);
     // fix phone type labels
     if (!empty($values['location']['phone'])) {
         $phoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id');
         foreach ($values['location']['phone'] as &$val) {
             if (!empty($val['phone_type_id'])) {
                 $val['phone_type_display'] = $phoneTypes[$val['phone_type_id']];
             }
         }
     }
     //retrieve custom field information
     $groupTree = CRM_Core_BAO_CustomGroup::getTree('Event', $this, $this->_id, 0, $values['event']['event_type_id']);
     CRM_Core_BAO_CustomGroup::buildCustomDataView($this, $groupTree, FALSE, NULL, NULL, NULL, $this->_id);
     $this->assign('action', CRM_Core_Action::VIEW);
     //To show the event location on maps directly on event info page
     $locations = CRM_Event_BAO_Event::getMapInfo($this->_id);
     if (!empty($locations) && !empty($values['event']['is_map'])) {
         $this->assign('locations', $locations);
         $this->assign('mapProvider', $config->mapProvider);
         $this->assign('mapKey', $config->mapAPIKey);
         $sumLat = $sumLng = 0;
         $maxLat = $maxLng = -400;
         $minLat = $minLng = 400;
         foreach ($locations as $location) {
             $sumLat += $location['lat'];
             $sumLng += $location['lng'];
             if ($location['lat'] > $maxLat) {
                 $maxLat = $location['lat'];
             }
             if ($location['lat'] < $minLat) {
                 $minLat = $location['lat'];
             }
             if ($location['lng'] > $maxLng) {
                 $maxLng = $location['lng'];
             }
             if ($location['lng'] < $minLng) {
                 $minLng = $location['lng'];
             }
         }
         $center = array('lat' => (double) $sumLat / count($locations), 'lng' => (double) $sumLng / count($locations));
         $span = array('lat' => (double) ($maxLat - $minLat), 'lng' => (double) ($maxLng - $minLng));
         $this->assign_by_ref('center', $center);
         $this->assign_by_ref('span', $span);
         if ($action == CRM_Core_Action::PREVIEW) {
             $mapURL = CRM_Utils_System::url('civicrm/contact/map/event', "eid={$this->_id}&reset=1&action=preview", TRUE, NULL, TRUE, TRUE);
         } else {
             $mapURL = CRM_Utils_System::url('civicrm/contact/map/event', "eid={$this->_id}&reset=1", TRUE, NULL, TRUE, TRUE);
         }
         $this->assign('skipLocationType', TRUE);
         $this->assign('mapURL', $mapURL);
     }
     if (CRM_Core_Permission::check('view event participants') && CRM_Core_Permission::check('view all contacts')) {
         $statusTypes = CRM_Event_PseudoConstant::participantStatus(NULL, 'is_counted = 1', 'label');
         $statusTypesPending = CRM_Event_PseudoConstant::participantStatus(NULL, 'is_counted = 0', 'label');
         $findParticipants['statusCounted'] = implode(', ', array_values($statusTypes));
         $findParticipants['statusNotCounted'] = implode(', ', array_values($statusTypesPending));
         $this->assign('findParticipants', $findParticipants);
     }
     $participantListingID = CRM_Utils_Array::value('participant_listing_id', $values['event']);
     if ($participantListingID) {
         $participantListingURL = CRM_Utils_System::url('civicrm/event/participant', "reset=1&id={$this->_id}", TRUE, NULL, TRUE, TRUE);
         $this->assign('participantListingURL', $participantListingURL);
     }
     $hasWaitingList = CRM_Utils_Array::value('has_waitlist', $values['event']);
     $eventFullMessage = CRM_Event_BAO_Participant::eventFull($this->_id, FALSE, $hasWaitingList);
     $allowRegistration = FALSE;
     if (!empty($values['event']['is_online_registration'])) {
         if (CRM_Event_BAO_Event::validRegistrationRequest($values['event'], $this->_id)) {
             // we always generate urls for the front end in joomla
             $action_query = $action === CRM_Core_Action::PREVIEW ? "&action={$action}" : '';
             $url = CRM_Utils_System::url('civicrm/event/register', "id={$this->_id}&reset=1{$action_query}", TRUE, NULL, TRUE, TRUE);
             if (!$eventFullMessage || $hasWaitingList) {
                 $registerText = ts('Register Now');
                 if (!empty($values['event']['registration_link_text'])) {
                     $registerText = $values['event']['registration_link_text'];
                 }
                 // check if we're in shopping cart mode for events
                 $enable_cart = Civi::settings()->get('enable_cart');
                 if ($enable_cart) {
                     $link = CRM_Event_Cart_BAO_EventInCart::get_registration_link($this->_id);
                     $registerText = $link['label'];
                     $url = CRM_Utils_System::url($link['path'], $link['query'] . $action_query, TRUE, NULL, TRUE, TRUE);
                 }
                 //Fixed for CRM-4855
                 $allowRegistration = CRM_Event_BAO_Event::showHideRegistrationLink($values);
                 $this->assign('registerText', $registerText);
                 $this->assign('registerURL', $url);
                 $this->assign('eventCartEnabled', $enable_cart);
             }
         } elseif (CRM_Core_Permission::check('register for events')) {
             $this->assign('registerClosed', TRUE);
         }
     }
     $this->assign('allowRegistration', $allowRegistration);
     $session = CRM_Core_Session::singleton();
     $params = array('contact_id' => $session->get('userID'), 'event_id' => CRM_Utils_Array::value('id', $values['event']), 'role_id' => CRM_Utils_Array::value('default_role_id', $values['event']));
     if ($eventFullMessage && $noFullMsg == 'false' || CRM_Event_BAO_Event::checkRegistration($params)) {
         $statusMessage = $eventFullMessage;
         if (CRM_Event_BAO_Event::checkRegistration($params)) {
             if ($noFullMsg == 'false') {
                 if ($values['event']['allow_same_participant_emails']) {
                     $statusMessage = ts('It looks like you are already registered for this event.  You may proceed if you want to create an additional registration.');
                 } else {
                     $registerUrl = CRM_Utils_System::url('civicrm/event/register', "reset=1&id={$values['event']['id']}&cid=0");
                     $statusMessage = ts("It looks like you are already registered for this event. If you want to change your registration, or you feel that you've gotten this message in error, please contact the site administrator.") . ' ' . ts('You can also <a href="%1">register another participant</a>.', array(1 => $registerUrl));
                 }
             }
         } elseif ($hasWaitingList) {
             $statusMessage = CRM_Utils_Array::value('waitlist_text', $values['event']);
             if (!$statusMessage) {
                 $statusMessage = ts('Event is currently full, but you can register and be a part of waiting list.');
             }
         }
         CRM_Core_Session::setStatus($statusMessage);
     }
     // we do not want to display recently viewed items, so turn off
     $this->assign('displayRecent', FALSE);
     // set page title = event title
     CRM_Utils_System::setTitle($values['event']['title']);
     $this->assign('event', $values['event']);
     if (isset($values['feeBlock'])) {
         $this->assign('feeBlock', $values['feeBlock']);
     }
     $this->assign('location', $values['location']);
     if (CRM_Core_Permission::check('access CiviEvent')) {
         $enableCart = Civi::settings()->get('enable_cart');
         $this->assign('manageEventLinks', CRM_Event_Page_ManageEvent::tabs($enableCart));
     }
     return parent::run();
 }
Example #7
0
 /**
  * function to get the information to map a event
  *
  * @param $id
  *
  * @internal param array $ids the list of ids for which we want map info
  *
  * @return null|string     title of the event
  * @static
  * @access public
  */
 static function &getMapInfo(&$id)
 {
     $sql = "\nSELECT\n   civicrm_event.id AS event_id,\n   civicrm_event.title AS display_name,\n   civicrm_address.street_address AS street_address,\n   civicrm_address.city AS city,\n   civicrm_address.postal_code AS postal_code,\n   civicrm_address.postal_code_suffix AS postal_code_suffix,\n   civicrm_address.geo_code_1 AS latitude,\n   civicrm_address.geo_code_2 AS longitude,\n   civicrm_state_province.abbreviation AS state,\n   civicrm_country.name AS country,\n   civicrm_location_type.name AS location_type\nFROM\n   civicrm_event\n   LEFT JOIN civicrm_loc_block ON ( civicrm_event.loc_block_id = civicrm_loc_block.id )\n   LEFT JOIN civicrm_address ON ( civicrm_loc_block.address_id = civicrm_address.id )\n   LEFT JOIN civicrm_state_province ON ( civicrm_address.state_province_id = civicrm_state_province.id )\n   LEFT JOIN civicrm_country ON civicrm_address.country_id = civicrm_country.id\n   LEFT JOIN civicrm_location_type ON ( civicrm_location_type.id = civicrm_address.location_type_id )\nWHERE civicrm_address.geo_code_1 IS NOT NULL\n  AND civicrm_address.geo_code_2 IS NOT NULL\n  AND civicrm_event.id = " . CRM_Utils_Type::escape($id, 'Integer');
     $dao = new CRM_Core_DAO();
     $dao->query($sql);
     $locations = array();
     $config = CRM_Core_Config::singleton();
     while ($dao->fetch()) {
         $location = array();
         $location['displayName'] = addslashes($dao->display_name);
         $location['lat'] = $dao->latitude;
         $location['marker_class'] = 'Event';
         $location['lng'] = $dao->longitude;
         $params = array('entity_id' => $id, 'entity_table' => 'civicrm_event');
         $addressValues = CRM_Core_BAO_Location::getValues($params, TRUE);
         $location['address'] = str_replace(array("\r", "\n"), '', addslashes(nl2br($addressValues['address'][1]['display_text'])));
         $location['url'] = CRM_Utils_System::url('civicrm/event/register', 'reset=1&id=' . $dao->event_id);
         $location['location_type'] = $dao->location_type;
         $eventImage = '<img src="' . $config->resourceBase . 'i/contact_org.gif" alt="Organization " height="20" width="15" />';
         $location['image'] = $eventImage;
         $location['displayAddress'] = str_replace('<br />', ', ', $location['address']);
         $locations[] = $location;
     }
     return $locations;
 }
Example #8
0
 /**
  * Function takes participant ids and statuses
  * update status from $fromStatusId to $toStatusId
  * and send mail + create activities.
  *
  * @param array $participantIds
  *   Participant ids.
  * @param int $toStatusId
  *   Update status id.
  * @param int $fromStatusId
  *   From status id.
  * @param bool $returnResult
  * @param bool $skipCascadeRule
  *
  * @return array|NULL
  */
 public static function transitionParticipants($participantIds, $toStatusId, $fromStatusId = NULL, $returnResult = FALSE, $skipCascadeRule = FALSE)
 {
     if (!is_array($participantIds) || empty($participantIds) || !$toStatusId) {
         return NULL;
     }
     //thumb rule is if we triggering  primary participant need to triggered additional
     $allParticipantIds = $primaryANDAdditonalIds = array();
     foreach ($participantIds as $id) {
         $allParticipantIds[] = $id;
         if (self::isPrimaryParticipant($id)) {
             //filter additional as per status transition rules, CRM-5403
             if ($skipCascadeRule) {
                 $additionalIds = self::getAdditionalParticipantIds($id);
             } else {
                 $additionalIds = self::getValidAdditionalIds($id, $fromStatusId, $toStatusId);
             }
             if (!empty($additionalIds)) {
                 $allParticipantIds = array_merge($allParticipantIds, $additionalIds);
                 $primaryANDAdditonalIds[$id] = $additionalIds;
             }
         }
     }
     //get the unique participant ids,
     $allParticipantIds = array_unique($allParticipantIds);
     //pull required participants, contacts, events  data, if not in hand
     static $eventDetails = array();
     static $domainValues = array();
     static $contactDetails = array();
     $contactIds = $eventIds = $participantDetails = array();
     $statusTypes = CRM_Event_PseudoConstant::participantStatus();
     $participantRoles = CRM_Event_PseudoConstant::participantRole();
     $pendingStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Pending'");
     //first thing is pull all necessory data from db.
     $participantIdClause = '(' . implode(',', $allParticipantIds) . ')';
     //get all participants data.
     $query = "SELECT * FROM civicrm_participant WHERE id IN {$participantIdClause}";
     $dao = CRM_Core_DAO::executeQuery($query);
     while ($dao->fetch()) {
         $participantDetails[$dao->id] = array('id' => $dao->id, 'role' => $participantRoles[$dao->role_id], 'is_test' => $dao->is_test, 'event_id' => $dao->event_id, 'status_id' => $dao->status_id, 'fee_amount' => $dao->fee_amount, 'contact_id' => $dao->contact_id, 'register_date' => $dao->register_date, 'registered_by_id' => $dao->registered_by_id);
         if (!array_key_exists($dao->contact_id, $contactDetails)) {
             $contactIds[$dao->contact_id] = $dao->contact_id;
         }
         if (!array_key_exists($dao->event_id, $eventDetails)) {
             $eventIds[$dao->event_id] = $dao->event_id;
         }
     }
     //get the domain values.
     if (empty($domainValues)) {
         // making all tokens available to templates.
         $domain = CRM_Core_BAO_Domain::getDomain();
         $tokens = array('domain' => array('name', 'phone', 'address', 'email'), 'contact' => CRM_Core_SelectValues::contactTokens());
         foreach ($tokens['domain'] as $token) {
             $domainValues[$token] = CRM_Utils_Token::getDomainTokenReplacement($token, $domain);
         }
     }
     //get all required contacts detail.
     if (!empty($contactIds)) {
         // get the contact details.
         list($currentContactDetails) = CRM_Utils_Token::getTokenDetails($contactIds, NULL, FALSE, FALSE, NULL, array(), 'CRM_Event_BAO_Participant');
         foreach ($currentContactDetails as $contactId => $contactValues) {
             $contactDetails[$contactId] = $contactValues;
         }
     }
     //get all required events detail.
     if (!empty($eventIds)) {
         foreach ($eventIds as $eventId) {
             //retrieve event information
             $eventParams = array('id' => $eventId);
             CRM_Event_BAO_Event::retrieve($eventParams, $eventDetails[$eventId]);
             //get default participant role.
             $eventDetails[$eventId]['participant_role'] = CRM_Utils_Array::value($eventDetails[$eventId]['default_role_id'], $participantRoles);
             //get the location info
             $locParams = array('entity_id' => $eventId, 'entity_table' => 'civicrm_event');
             $eventDetails[$eventId]['location'] = CRM_Core_BAO_Location::getValues($locParams, TRUE);
         }
     }
     //now we are ready w/ all required data.
     //take a decision as per statuses.
     $emailType = NULL;
     $toStatus = $statusTypes[$toStatusId];
     $fromStatus = CRM_Utils_Array::value($fromStatusId, $statusTypes);
     switch ($toStatus) {
         case 'Pending from waitlist':
         case 'Pending from approval':
             switch ($fromStatus) {
                 case 'On waitlist':
                 case 'Awaiting approval':
                     $emailType = 'Confirm';
                     break;
             }
             break;
         case 'Expired':
             //no matter from where u come send expired mail.
             $emailType = $toStatus;
             break;
         case 'Cancelled':
             //no matter from where u come send cancel mail.
             $emailType = $toStatus;
             break;
     }
     //as we process additional w/ primary, there might be case if user
     //select primary as well as additionals, so avoid double processing.
     $processedParticipantIds = array();
     $mailedParticipants = array();
     //send mails and update status.
     foreach ($participantDetails as $participantId => $participantValues) {
         $updateParticipantIds = array();
         if (in_array($participantId, $processedParticipantIds)) {
             continue;
         }
         //check is it primary and has additional.
         if (array_key_exists($participantId, $primaryANDAdditonalIds)) {
             foreach ($primaryANDAdditonalIds[$participantId] as $additonalId) {
                 if ($emailType) {
                     $mail = self::sendTransitionParticipantMail($additonalId, $participantDetails[$additonalId], $eventDetails[$participantDetails[$additonalId]['event_id']], $contactDetails[$participantDetails[$additonalId]['contact_id']], $domainValues, $emailType);
                     //get the mail participant ids
                     if ($mail) {
                         $mailedParticipants[$additonalId] = $contactDetails[$participantDetails[$additonalId]['contact_id']]['display_name'];
                     }
                 }
                 $updateParticipantIds[] = $additonalId;
                 $processedParticipantIds[] = $additonalId;
             }
         }
         //now send email appropriate mail to primary.
         if ($emailType) {
             $mail = self::sendTransitionParticipantMail($participantId, $participantValues, $eventDetails[$participantValues['event_id']], $contactDetails[$participantValues['contact_id']], $domainValues, $emailType);
             //get the mail participant ids
             if ($mail) {
                 $mailedParticipants[$participantId] = $contactDetails[$participantValues['contact_id']]['display_name'];
             }
         }
         //now update status of group/one at once.
         $updateParticipantIds[] = $participantId;
         //update the register date only when we,
         //move participant to pending class, CRM-6496
         $updateRegisterDate = FALSE;
         if (array_key_exists($toStatusId, $pendingStatuses)) {
             $updateRegisterDate = TRUE;
         }
         self::updateStatus($updateParticipantIds, $toStatusId, $updateRegisterDate);
         $processedParticipantIds[] = $participantId;
     }
     //return result for cron.
     if ($returnResult) {
         $results = array('mailedParticipants' => $mailedParticipants, 'updatedParticipantIds' => $processedParticipantIds);
         return $results;
     }
 }
 function completeTransaction(&$input, &$ids, &$objects, &$transaction, $recur = FALSE)
 {
     $contribution =& $objects['contribution'];
     $primaryContributionID = isset($contribution->id) ? $contribution->id : $objects['first_contribution']->id;
     $memberships =& $objects['membership'];
     if (is_numeric($memberships)) {
         $memberships = array($objects['membership']);
     }
     $participant =& $objects['participant'];
     $event =& $objects['event'];
     $changeToday = CRM_Utils_Array::value('trxn_date', $input, self::$_now);
     $recurContrib =& $objects['contributionRecur'];
     $values = array();
     if (isset($input['is_email_receipt'])) {
         $values['is_email_receipt'] = $input['is_email_receipt'];
     }
     $source = NULL;
     if ($input['component'] == 'contribute') {
         if ($contribution->contribution_page_id) {
             CRM_Contribute_BAO_ContributionPage::setValues($contribution->contribution_page_id, $values);
             $source = ts('Online Contribution') . ': ' . $values['title'];
         } elseif ($recurContrib && $recurContrib->id) {
             $contribution->contribution_page_id = NULL;
             $values['amount'] = $recurContrib->amount;
             $values['financial_type_id'] = $objects['contributionType']->id;
             $values['title'] = $source = ts('Offline Recurring Contribution');
             $domainValues = CRM_Core_BAO_Domain::getNameAndEmail();
             $values['receipt_from_name'] = $domainValues[0];
             $values['receipt_from_email'] = $domainValues[1];
         }
         if ($recurContrib && $recurContrib->id && !isset($input['is_email_receipt'])) {
             //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting
             // but CRM-16124 if $input['is_email_receipt'] is set then that should not be overridden.
             $values['is_email_receipt'] = $recurContrib->is_email_receipt;
         }
         $contribution->source = $source;
         if (CRM_Utils_Array::value('is_email_receipt', $values)) {
             $contribution->receipt_date = self::$_now;
         }
         if (!empty($memberships)) {
             $membershipsUpdate = array();
             foreach ($memberships as $membershipTypeIdKey => $membership) {
                 if ($membership) {
                     $format = '%Y%m%d';
                     $currentMembership = CRM_Member_BAO_Membership::getContactMembership($membership->contact_id, $membership->membership_type_id, $membership->is_test, $membership->id);
                     // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
                     // this picks up membership type changes during renewals
                     $sql = "\nSELECT    membership_type_id\nFROM      civicrm_membership_log\nWHERE     membership_id={$membership->id}\nORDER BY  id DESC\nLIMIT 1;";
                     $dao = new CRM_Core_DAO();
                     $dao->query($sql);
                     if ($dao->fetch()) {
                         if (!empty($dao->membership_type_id)) {
                             $membership->membership_type_id = $dao->membership_type_id;
                             $membership->save();
                         }
                         // else fall back to using current membership type
                     }
                     // else fall back to using current membership type
                     $dao->free();
                     $num_terms = $contribution->getNumTermsByContributionAndMembershipType($membership->membership_type_id, $primaryContributionID);
                     if ($currentMembership) {
                         /*
                          * Fixed FOR CRM-4433
                          * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
                          * when Contribution mode is notify and membership is for renewal )
                          */
                         CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($currentMembership, $changeToday);
                         // @todo - we should pass membership_type_id instead of null here but not
                         // adding as not sure of testing
                         $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membership->id, $changeToday, NULL, $num_terms);
                         $dates['join_date'] = CRM_Utils_Date::customFormat($currentMembership['join_date'], $format);
                     } else {
                         $dates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membership->membership_type_id, NULL, NULL, NULL, $num_terms);
                     }
                     //get the status for membership.
                     $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($dates['start_date'], $dates['end_date'], $dates['join_date'], 'today', TRUE, $membership->membership_type_id, (array) $membership);
                     $formatedParams = array('status_id' => CRM_Utils_Array::value('id', $calcStatus, 2), 'join_date' => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('join_date', $dates), $format), 'start_date' => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('start_date', $dates), $format), 'end_date' => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('end_date', $dates), $format));
                     //we might be renewing membership,
                     //so make status override false.
                     $formatedParams['is_override'] = FALSE;
                     $membership->copyValues($formatedParams);
                     $membership->save();
                     //updating the membership log
                     $membershipLog = array();
                     $membershipLog = $formatedParams;
                     $logStartDate = $formatedParams['start_date'];
                     if (CRM_Utils_Array::value('log_start_date', $dates)) {
                         $logStartDate = CRM_Utils_Date::customFormat($dates['log_start_date'], $format);
                         $logStartDate = CRM_Utils_Date::isoToMysql($logStartDate);
                     }
                     $membershipLog['start_date'] = $logStartDate;
                     $membershipLog['membership_id'] = $membership->id;
                     $membershipLog['modified_id'] = $membership->contact_id;
                     $membershipLog['modified_date'] = date('Ymd');
                     $membershipLog['membership_type_id'] = $membership->membership_type_id;
                     CRM_Member_BAO_MembershipLog::add($membershipLog, CRM_Core_DAO::$_nullArray);
                     //update related Memberships.
                     CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $formatedParams);
                     //update the membership type key of membership relatedObjects array
                     //if it has changed after membership update
                     if ($membershipTypeIdKey != $membership->membership_type_id) {
                         $membershipsUpdate[$membership->membership_type_id] = $membership;
                         $contribution->_relatedObjects['membership'][$membership->membership_type_id] = $membership;
                         unset($contribution->_relatedObjects['membership'][$membershipTypeIdKey]);
                         unset($memberships[$membershipTypeIdKey]);
                     }
                 }
             }
             //update the memberships object with updated membershipTypeId data
             //if membershipTypeId has changed after membership update
             if (!empty($membershipsUpdate)) {
                 $memberships = $memberships + $membershipsUpdate;
             }
         }
     } else {
         // event
         $eventParams = array('id' => $objects['event']->id);
         $values['event'] = array();
         CRM_Event_BAO_Event::retrieve($eventParams, $values['event']);
         //get location details
         $locationParams = array('entity_id' => $objects['event']->id, 'entity_table' => 'civicrm_event');
         $values['location'] = CRM_Core_BAO_Location::getValues($locationParams);
         $ufJoinParams = array('entity_table' => 'civicrm_event', 'entity_id' => $ids['event'], 'module' => 'CiviEvent');
         list($custom_pre_id, $custom_post_ids) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
         $values['custom_pre_id'] = $custom_pre_id;
         $values['custom_post_id'] = $custom_post_ids;
         //for tasks 'Change Participant Status' and 'Batch Update Participants Via Profile' case
         //and cases involving status updation through ipn
         $values['totalAmount'] = $input['amount'];
         $contribution->source = ts('Online Event Registration') . ': ' . $values['event']['title'];
         if ($values['event']['is_email_confirm']) {
             $contribution->receipt_date = self::$_now;
             $values['is_email_receipt'] = 1;
         }
         if (!CRM_Utils_Array::value('skipComponentSync', $input)) {
             $participant->status_id = 1;
         }
         $participant->save();
     }
     if (CRM_Utils_Array::value('net_amount', $input, 0) == 0 && CRM_Utils_Array::value('fee_amount', $input, 0) != 0) {
         $input['net_amount'] = $input['amount'] - $input['fee_amount'];
     }
     // This complete transaction function is being overloaded to create new contributions too.
     // here we record if it is a new contribution.
     // @todo separate the 2 more appropriately.
     $isNewContribution = FALSE;
     if (empty($contribution->id)) {
         $isNewContribution = TRUE;
         if (!empty($input['amount']) && $input['amount'] != $contribution->total_amount) {
             $contribution->total_amount = $input['amount'];
             // The BAO does this stuff but we are actually kinda bypassing it here (bad code! go sit in the corner)
             // so we have to handle net_amount in this (naughty) code.
             if (isset($input['fee_amount']) && is_numeric($input['fee_amount'])) {
                 $contribution->fee_amount = $input['fee_amount'];
             }
             $contribution->net_amount = $contribution->total_amount - $contribution->fee_amount;
         }
         if (!empty($input['campaign_id'])) {
             $contribution->campaign_id = $input['campaign_id'];
         }
     }
     $contributionStatuses = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array('labelColumn' => 'name', 'flip' => 1));
     // @todo this section should call the api  in order to have hooks called &
     // because all this 'messiness' setting variables could be avoided
     // by letting the api resolve pseudoconstants & copy set values and format dates.
     $contribution->contribution_status_id = $contributionStatuses['Completed'];
     $contribution->is_test = $input['is_test'];
     // CRM-15960 If we don't have a value we 'want' for the amounts, leave it to the BAO to sort out.
     if (isset($input['net_amount'])) {
         $contribution->fee_amount = CRM_Utils_Array::value('fee_amount', $input, 0);
     }
     if (isset($input['net_amount'])) {
         $contribution->net_amount = $input['net_amount'];
     }
     $contribution->trxn_id = $input['trxn_id'];
     $contribution->receive_date = CRM_Utils_Date::isoToMysql($contribution->receive_date);
     $contribution->thankyou_date = CRM_Utils_Date::isoToMysql($contribution->thankyou_date);
     $contribution->receipt_date = CRM_Utils_Date::isoToMysql($contribution->receipt_date);
     $contribution->cancel_date = 'null';
     if (CRM_Utils_Array::value('check_number', $input)) {
         $contribution->check_number = $input['check_number'];
     }
     if (CRM_Utils_Array::value('payment_instrument_id', $input)) {
         $contribution->payment_instrument_id = $input['payment_instrument_id'];
     }
     if (!empty($contribution->id)) {
         $contributionId['id'] = $contribution->id;
         $input['prevContribution'] = CRM_Contribute_BAO_Contribution::getValues($contributionId, CRM_Core_DAO::$_nullArray, CRM_Core_DAO::$_nullArray);
     }
     $contribution->save();
     //add line items for recurring payments
     if (!empty($contribution->contribution_recur_id)) {
         if ($isNewContribution) {
             $input['line_item'] = $this->addRecurLineItems($contribution->contribution_recur_id, $contribution);
         } else {
             // this is just to prevent e-notices when we call recordFinancialAccounts - per comments on that line - intention is somewhat unclear
             $input['line_item'] = array();
         }
         if (!empty($memberships) && $primaryContributionID != $contribution->id) {
             foreach ($memberships as $membership) {
                 try {
                     $membershipPayment = array('membership_id' => $membership->id, 'contribution_id' => $contribution->id);
                     if (!civicrm_api3('membership_payment', 'getcount', $membershipPayment)) {
                         civicrm_api3('membership_payment', 'create', $membershipPayment);
                     }
                 } catch (CiviCRM_API3_Exception $e) {
                     echo $e->getMessage();
                     // we are catching & ignoring errors as an extra precaution since lost IPNs may be more serious that lost membership_payment data
                     // this fn is unit-tested so risk of changes elsewhere breaking it are otherwise mitigated
                 }
             }
         }
     }
     //copy initial contribution custom fields for recurring contributions
     if ($recurContrib && $recurContrib->id) {
         $this->copyCustomValues($recurContrib->id, $contribution->id);
     }
     // next create the transaction record
     $paymentProcessor = $paymentProcessorId = '';
     if (isset($objects['paymentProcessor'])) {
         if (is_array($objects['paymentProcessor'])) {
             $paymentProcessor = $objects['paymentProcessor']['payment_processor_type'];
             $paymentProcessorId = $objects['paymentProcessor']['id'];
         } else {
             $paymentProcessor = $objects['paymentProcessor']->payment_processor_type;
             $paymentProcessorId = $objects['paymentProcessor']->id;
         }
     }
     //it's hard to see how it could reach this point without a contributon id as it is saved in line 511 above
     // which raised the question as to whether this check preceded line 511 & if so whether something could be broken
     // From a lot of code reading /debugging I'm still not sure the intent WRT first & subsequent payments in this code
     // it would be good if someone added some comments or refactored this
     if ($contribution->id) {
         $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
         if (empty($input['prevContribution']) && $paymentProcessorId || !$input['prevContribution']->is_pay_later && $input['prevContribution']->contribution_status_id == array_search('Pending', $contributionStatuses)) {
             $input['payment_processor'] = $paymentProcessorId;
         }
         $input['contribution_status_id'] = array_search('Completed', $contributionStatuses);
         $input['total_amount'] = $input['amount'];
         $input['contribution'] = $contribution;
         $input['financial_type_id'] = $contribution->financial_type_id;
         if (CRM_Utils_Array::value('participant', $contribution->_relatedObjects)) {
             $input['contribution_mode'] = 'participant';
             $input['participant_id'] = $contribution->_relatedObjects['participant']->id;
             $input['skipLineItem'] = 1;
         }
         //@todo writing a unit test I was unable to create a scenario where this line did not fatal on second
         // and subsequent payments. In this case the line items are created at $this->addRecurLineItems
         // and since the contribution is saved prior to this line there is always a contribution-id,
         // however there is never a prevContribution (which appears to mean original contribution not previous
         // contribution - or preUpdateContributionObject most accurately)
         // so, this is always called & only appears to succeed when prevContribution exists - which appears
         // to mean "are we updating an exisitng pending contribution"
         //I was able to make the unit test complete as fataling here doesn't prevent
         // the contribution being created - but activities would not be created or emails sent
         CRM_Contribute_BAO_Contribution::recordFinancialAccounts($input, NULL);
     }
     self::updateRecurLinkedPledge($contribution);
     // create an activity record
     if ($input['component'] == 'contribute') {
         //CRM-4027
         $targetContactID = NULL;
         if (CRM_Utils_Array::value('related_contact', $ids)) {
             $targetContactID = $contribution->contact_id;
             $contribution->contact_id = $ids['related_contact'];
         }
         CRM_Activity_BAO_Activity::addActivity($contribution, NULL, $targetContactID);
         // event
     } else {
         CRM_Activity_BAO_Activity::addActivity($participant);
     }
     CRM_Core_Error::debug_log_message("Contribution record updated successfully");
     $transaction->commit();
     // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending
     // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set
     if (!array_key_exists('is_email_receipt', $values) || $values['is_email_receipt'] == 1) {
         self::sendMail($input, $ids, $objects, $values, $recur, FALSE);
         CRM_Core_Error::debug_log_message("Receipt sent");
     }
     CRM_Core_Error::debug_log_message("Success: Database updated");
 }
Example #10
0
 /**
  * Validate country / state / county match and suppress unwanted "required" errors
  */
 private function validateChainSelectFields()
 {
     foreach ($this->_chainSelectFields as $control => $target) {
         if ($this->elementExists($control) && $this->elementExists($target)) {
             $controlValue = (array) $this->getElementValue($control);
             $targetField = $this->getElement($target);
             $controlType = $targetField->getAttribute('data-callback') == 'civicrm/ajax/jqCounty' ? 'stateProvince' : 'country';
             $targetValue = array_filter((array) $targetField->getValue());
             if ($targetValue || $this->getElementError($target)) {
                 $options = CRM_Core_BAO_Location::getChainSelectValues($controlValue, $controlType, TRUE);
                 if ($targetValue) {
                     if (!array_intersect($targetValue, array_keys($options))) {
                         $this->setElementError($target, $controlType == 'country' ? ts('State/Province does not match the selected Country') : ts('County does not match the selected State/Province'));
                     }
                 } elseif (!$options) {
                     $this->setElementError($target, NULL);
                 }
             }
         }
     }
 }
 function completeTransaction(&$input, &$ids, &$objects, &$transaction, $recur = FALSE)
 {
     $contribution =& $objects['contribution'];
     $memberships =& $objects['membership'];
     if (is_numeric($memberships)) {
         $memberships = array($objects['membership']);
     }
     $participant =& $objects['participant'];
     $event =& $objects['event'];
     $changeToday = CRM_Utils_Array::value('trxn_date', $input, self::$_now);
     $recurContrib =& $objects['contributionRecur'];
     $values = array();
     if ($input['component'] == 'contribute') {
         if ($contribution->contribution_page_id) {
             CRM_Contribute_BAO_ContributionPage::setValues($contribution->contribution_page_id, $values);
             $source = ts('Online Contribution') . ': ' . $values['title'];
         } elseif ($recurContrib->id) {
             $contribution->contribution_page_id = NULL;
             $values['amount'] = $recurContrib->amount;
             $values['contribution_type_id'] = $objects['contributionType']->id;
             $values['title'] = $source = ts('Offline Recurring Contribution');
             $values['is_email_receipt'] = $recurContrib->is_email_receipt;
             $domainValues = CRM_Core_BAO_Domain::getNameAndEmail();
             $values['receipt_from_name'] = $domainValues[0];
             $values['receipt_from_email'] = $domainValues[1];
         }
         $contribution->source = $source;
         if (CRM_Utils_Array::value('is_email_receipt', $values)) {
             $contribution->receipt_date = self::$_now;
         }
         if (!empty($memberships)) {
             foreach ($memberships as $membershipTypeIdKey => $membership) {
                 if ($membership) {
                     $format = '%Y%m%d';
                     $currentMembership = CRM_Member_BAO_Membership::getContactMembership($membership->contact_id, $membership->membership_type_id, $membership->is_test, $membership->id);
                     // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
                     // this picks up membership type changes during renewals
                     $sql = "\nSELECT    membership_type_id\nFROM      civicrm_membership_log\nWHERE     membership_id={$membership->id}\nORDER BY  id DESC\nLIMIT 1;";
                     $dao = new CRM_Core_DAO();
                     $dao->query($sql);
                     if ($dao->fetch()) {
                         if (!empty($dao->membership_type_id)) {
                             $membership->membership_type_id = $dao->membership_type_id;
                             $membership->save();
                         }
                         // else fall back to using current membership type
                     }
                     // else fall back to using current membership type
                     $dao->free();
                     if ($currentMembership) {
                         /*
                          * Fixed FOR CRM-4433
                          * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
                          * when Contribution mode is notify and membership is for renewal )
                          */
                         CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($currentMembership, $changeToday);
                         $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membership->id, $changeToday);
                         $dates['join_date'] = CRM_Utils_Date::customFormat($currentMembership['join_date'], $format);
                     } else {
                         $dates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membership->membership_type_id);
                     }
                     //get the status for membership.
                     $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($dates['start_date'], $dates['end_date'], $dates['join_date'], 'today', TRUE);
                     $formatedParams = array('status_id' => CRM_Utils_Array::value('id', $calcStatus, 2), 'join_date' => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('join_date', $dates), $format), 'start_date' => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('start_date', $dates), $format), 'end_date' => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('end_date', $dates), $format), 'reminder_date' => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('reminder_date', $dates), $format));
                     //we might be renewing membership,
                     //so make status override false.
                     $formatedParams['is_override'] = FALSE;
                     $membership->copyValues($formatedParams);
                     $membership->save();
                     //updating the membership log
                     $membershipLog = array();
                     $membershipLog = $formatedParams;
                     $logStartDate = $formatedParams['start_date'];
                     if (CRM_Utils_Array::value('log_start_date', $dates)) {
                         $logStartDate = CRM_Utils_Date::customFormat($dates['log_start_date'], $format);
                         $logStartDate = CRM_Utils_Date::isoToMysql($logStartDate);
                     }
                     $membershipLog['start_date'] = $logStartDate;
                     $membershipLog['membership_id'] = $membership->id;
                     $membershipLog['modified_id'] = $membership->contact_id;
                     $membershipLog['modified_date'] = date('Ymd');
                     $membershipLog['membership_type_id'] = $membership->membership_type_id;
                     CRM_Member_BAO_MembershipLog::add($membershipLog, CRM_Core_DAO::$_nullArray);
                     //update related Memberships.
                     CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $formatedParams);
                     //update the membership type key of membership relatedObjects array
                     //if it has changed after membership update
                     if ($membershipTypeIdKey != $membership->membership_type_id) {
                         $memberships[$membership->membership_type_id] = $membership;
                         $contribution->_relatedObjects['membership'][$membership->membership_type_id] = $membership;
                         unset($contribution->_relatedObjects['membership'][$membershipTypeIdKey]);
                         unset($memberships[$membershipTypeIdKey]);
                     }
                 }
             }
         }
     } else {
         // event
         $eventParams = array('id' => $objects['event']->id);
         $values['event'] = array();
         CRM_Event_BAO_Event::retrieve($eventParams, $values['event']);
         $eventParams = array('id' => $objects['event']->id);
         $values['event'] = array();
         CRM_Event_BAO_Event::retrieve($eventParams, $values['event']);
         //get location details
         $locationParams = array('entity_id' => $objects['event']->id, 'entity_table' => 'civicrm_event');
         $values['location'] = CRM_Core_BAO_Location::getValues($locationParams);
         $ufJoinParams = array('entity_table' => 'civicrm_event', 'entity_id' => $ids['event'], 'module' => 'CiviEvent');
         list($custom_pre_id, $custom_post_ids) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
         $values['custom_pre_id'] = $custom_pre_id;
         $values['custom_post_id'] = $custom_post_ids;
         $contribution->source = ts('Online Event Registration') . ': ' . $values['event']['title'];
         if ($values['event']['is_email_confirm']) {
             $contribution->receipt_date = self::$_now;
             $values['is_email_receipt'] = 1;
         }
         $participant->status_id = 1;
         $participant->save();
     }
     if (CRM_Utils_Array::value('net_amount', $input, 0) == 0 && CRM_Utils_Array::value('fee_amount', $input, 0) != 0) {
         $input['net_amount'] = $input['amount'] - $input['fee_amount'];
     }
     $addLineItems = FALSE;
     if (empty($contribution->id)) {
         $addLineItems = TRUE;
     }
     $contribution->contribution_status_id = 1;
     $contribution->is_test = $input['is_test'];
     $contribution->fee_amount = CRM_Utils_Array::value('fee_amount', $input, 0);
     $contribution->net_amount = CRM_Utils_Array::value('net_amount', $input, 0);
     $contribution->trxn_id = $input['trxn_id'];
     $contribution->receive_date = CRM_Utils_Date::isoToMysql($contribution->receive_date);
     $contribution->thankyou_date = CRM_Utils_Date::isoToMysql($contribution->thankyou_date);
     $contribution->cancel_date = 'null';
     if (CRM_Utils_Array::value('check_number', $input)) {
         $contribution->check_number = $input['check_number'];
     }
     if (CRM_Utils_Array::value('payment_instrument_id', $input)) {
         $contribution->payment_instrument_id = $input['payment_instrument_id'];
     }
     $contribution->save();
     //add lineitems for recurring payments
     if (CRM_Utils_Array::value('contributionRecur', $objects) && $objects['contributionRecur']->id && $addLineItems) {
         $this->addrecurLineItems($objects['contributionRecur']->id, $contribution->id);
     }
     // next create the transaction record
     $paymentProcessor = '';
     if (isset($objects['paymentProcessor'])) {
         if (is_array($objects['paymentProcessor'])) {
             $paymentProcessor = $objects['paymentProcessor']['payment_processor_type'];
         } else {
             $paymentProcessor = $objects['paymentProcessor']->payment_processor_type;
         }
     }
     if ($contribution->trxn_id) {
         $trxnParams = array('contribution_id' => $contribution->id, 'trxn_date' => isset($input['trxn_date']) ? $input['trxn_date'] : self::$_now, 'trxn_type' => 'Debit', 'total_amount' => $input['amount'], 'fee_amount' => $contribution->fee_amount, 'net_amount' => $contribution->net_amount, 'currency' => $contribution->currency, 'payment_processor' => $paymentProcessor, 'trxn_id' => $contribution->trxn_id);
         $trxn = CRM_Core_BAO_FinancialTrxn::create($trxnParams);
     }
     self::updateRecurLinkedPledge($contribution);
     // create an activity record
     if ($input['component'] == 'contribute') {
         //CRM-4027
         $targetContactID = NULL;
         if (CRM_Utils_Array::value('related_contact', $ids)) {
             $targetContactID = $contribution->contact_id;
             $contribution->contact_id = $ids['related_contact'];
         }
         CRM_Activity_BAO_Activity::addActivity($contribution, NULL, $targetContactID);
         // event
     } else {
         CRM_Activity_BAO_Activity::addActivity($participant);
     }
     CRM_Core_Error::debug_log_message("Contribution record updated successfully");
     $transaction->commit();
     // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending
     // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set
     if (!array_key_exists('is_email_receipt', $values) || $values['is_email_receipt'] == 1) {
         self::sendMail($input, $ids, $objects, $values, $recur, FALSE);
     }
     CRM_Core_Error::debug_log_message("Success: Database updated and mail sent");
 }
Example #12
0
 /**
  * Cancel this participant and finish, send cancellation email. At this point no
  * auto-cancellation of payment is handled, so payment needs to be manually cancelled
  *
  * return @void
  */
 public function cancelParticipant($params)
 {
     //set participant record status to Cancelled, refund payment if possible
     // send email to participant and admin, and log Activity
     $value = array();
     $value['id'] = $this->_participant_id;
     $cancelledId = array_search('Cancelled', CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Negative'"));
     $value['status_id'] = $cancelledId;
     CRM_Event_BAO_Participant::create($value);
     $domainValues = array();
     $domain = CRM_Core_BAO_Domain::getDomain();
     $tokens = array('domain' => array('name', 'phone', 'address', 'email'), 'contact' => CRM_Core_SelectValues::contactTokens());
     foreach ($tokens['domain'] as $token) {
         $domainValues[$token] = CRM_Utils_Token::getDomainTokenReplacement($token, $domain);
     }
     $participantRoles = array();
     $participantRoles = CRM_Event_PseudoConstant::participantRole();
     $participantDetails = array();
     $query = "SELECT * FROM civicrm_participant WHERE id = {$this->_participant_id}";
     $dao = CRM_Core_DAO::executeQuery($query);
     while ($dao->fetch()) {
         $participantDetails[$dao->id] = array('id' => $dao->id, 'role' => $participantRoles[$dao->role_id], 'is_test' => $dao->is_test, 'event_id' => $dao->event_id, 'status_id' => $dao->status_id, 'fee_amount' => $dao->fee_amount, 'contact_id' => $dao->contact_id, 'register_date' => $dao->register_date, 'registered_by_id' => $dao->registered_by_id);
     }
     $eventDetails = array();
     $eventParams = array('id' => $this->_event_id);
     CRM_Event_BAO_Event::retrieve($eventParams, $eventDetails[$this->_event_id]);
     //get default participant role.
     $eventDetails[$this->_event_id]['participant_role'] = CRM_Utils_Array::value($eventDetails[$this->_event_id]['default_role_id'], $participantRoles);
     //get the location info
     $locParams = array('entity_id' => $this->_event_id, 'entity_table' => 'civicrm_event');
     $eventDetails[$this->_event_id]['location'] = CRM_Core_BAO_Location::getValues($locParams, TRUE);
     //get contact details
     $contactIds[$this->_contact_id] = $this->_contact_id;
     list($currentContactDetails) = CRM_Utils_Token::getTokenDetails($contactIds, NULL, FALSE, FALSE, NULL, array(), 'CRM_Event_BAO_Participant');
     foreach ($currentContactDetails as $contactId => $contactValues) {
         $contactDetails[$this->_contact_id] = $contactValues;
     }
     //send a 'cancelled' email to user, and cc the event's cc_confirm email
     $mail = CRM_Event_BAO_Participant::sendTransitionParticipantMail($this->_participant_id, $participantDetails[$this->_participant_id], $eventDetails[$this->_event_id], $contactDetails[$this->_contact_id], $domainValues, "Cancelled", "");
     $statusMsg = ts('Event registration information for %1 has been updated.', array(1 => $this->_contact_name));
     $statusMsg .= ' ' . ts('A cancellation email has been sent to %1.', array(1 => $this->_contact_email));
     CRM_Core_Session::setStatus($statusMsg, ts('Saved'), 'success');
     $url = CRM_Utils_System::url('civicrm/event/info', "reset=1&id={$this->_event_id}&noFullMsg=true");
     CRM_Utils_System::redirect($url);
 }
Example #13
0
 /**
  * Function to get events Summary
  *
  * @static
  * @return array Array of event summary values
  */
 static function getEventSummary()
 {
     $eventSummary = $eventIds = array();
     require_once 'CRM/Core/Config.php';
     $config = CRM_Core_Config::singleton();
     // We're fetching recent and upcoming events (where start date is 7 days ago OR later)
     $query = "SELECT count(id) as total_events\n                  FROM   civicrm_event e\n                  WHERE  e.is_active=1 AND\n                        ( e.is_template IS NULL OR e.is_template = 0) AND\n                        e.start_date >= DATE_SUB( NOW(), INTERVAL 7 day );";
     $dao =& CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
     if ($dao->fetch()) {
         $eventSummary['total_events'] = $dao->total_events;
     }
     if (empty($eventSummary) || $dao->total_events == 0) {
         return $eventSummary;
     }
     // Get the Id of Option Group for Event Types
     require_once 'CRM/Core/DAO/OptionGroup.php';
     $optionGroupDAO = new CRM_Core_DAO_OptionGroup();
     $optionGroupDAO->name = 'event_type';
     $optionGroupId = null;
     if ($optionGroupDAO->find(true)) {
         $optionGroupId = $optionGroupDAO->id;
     }
     $query = "\nSELECT     civicrm_event.id as id, civicrm_event.title as event_title, civicrm_event.is_public as is_public,\n           civicrm_event.max_participants as max_participants, civicrm_event.start_date as start_date,\n           civicrm_event.end_date as end_date, civicrm_event.is_online_registration, civicrm_event.is_monetary, civicrm_event.is_show_location,civicrm_event.is_map as is_map, civicrm_option_value.label as event_type, civicrm_tell_friend.is_active as is_friend_active,\n           civicrm_event.summary as summary\nFROM       civicrm_event\nLEFT JOIN  civicrm_option_value ON (\n           civicrm_event.event_type_id = civicrm_option_value.value AND\n           civicrm_option_value.option_group_id = %1 )\nLEFT JOIN  civicrm_tell_friend ON ( civicrm_tell_friend.entity_id = civicrm_event.id  AND civicrm_tell_friend.entity_table = 'civicrm_event' )\nWHERE      civicrm_event.is_active = 1 AND\n           ( civicrm_event.is_template IS NULL OR civicrm_event.is_template = 0) AND\n           civicrm_event.start_date >= DATE_SUB( NOW(), INTERVAL 7 day )\nGROUP BY   civicrm_event.id\nORDER BY   civicrm_event.start_date ASC\nLIMIT      0, 10\n";
     $eventParticipant = array();
     $eventParticipant['participants'] = self::getParticipantCount();
     $eventParticipant['notCountedParticipants'] = self::getParticipantCount(true, false, true, false);
     $eventParticipant['notCountedDueToRole'] = self::getParticipantCount(false, false, true, false);
     $eventParticipant['notCountedDueToStatus'] = self::getParticipantCount(true, false, false, false);
     $properties = array('eventTitle' => 'event_title', 'isPublic' => 'is_public', 'maxParticipants' => 'max_participants', 'startDate' => 'start_date', 'endDate' => 'end_date', 'eventType' => 'event_type', 'isMap' => 'is_map', 'participants' => 'participants', 'notCountedDueToRole' => 'notCountedDueToRole', 'notCountedDueToStatus' => 'notCountedDueToStatus', 'notCountedParticipants' => 'notCountedParticipants');
     $permissions = CRM_Event_BAO_Event::checkPermission();
     $params = array(1 => array($optionGroupId, 'Integer'));
     $dao = CRM_Core_DAO::executeQuery($query, $params);
     while ($dao->fetch()) {
         if (in_array($dao->id, $permissions[CRM_Core_Permission::VIEW])) {
             foreach ($properties as $property => $name) {
                 $set = null;
                 switch ($name) {
                     case 'is_public':
                         if ($dao->{$name}) {
                             $set = 'Yes';
                         } else {
                             $set = 'No';
                         }
                         $eventSummary['events'][$dao->id][$property] = $set;
                         break;
                     case 'is_map':
                         if ($dao->{$name} && $config->mapAPIKey) {
                             $params = array();
                             $values = array();
                             $ids = array();
                             $params = array('entity_id' => $dao->id, 'entity_table' => 'civicrm_event');
                             require_once 'CRM/Core/BAO/Location.php';
                             $values['location'] = CRM_Core_BAO_Location::getValues($params, true);
                             if (is_numeric(CRM_Utils_Array::value('geo_code_1', $values['location']['address'][1])) || $config->mapGeoCoding && $values['location']['address'][1]['city'] && $values['location']['address'][1]['state_province_id']) {
                                 $set = CRM_Utils_System::url('civicrm/contact/map/event', "reset=1&eid={$dao->id}");
                             }
                         }
                         $eventSummary['events'][$dao->id][$property] = $set;
                         if (in_array($dao->id, $permissions[CRM_Core_Permission::EDIT])) {
                             $eventSummary['events'][$dao->id]['configure'] = CRM_Utils_System::url("civicrm/admin/event", "action=update&id={$dao->id}&reset=1");
                         }
                         break;
                     case 'end_date':
                     case 'start_date':
                         $eventSummary['events'][$dao->id][$property] = CRM_Utils_Date::customFormat($dao->{$name}, null, array('d'));
                         break;
                     case 'participants':
                     case 'notCountedDueToRole':
                     case 'notCountedDueToStatus':
                     case 'notCountedParticipants':
                         $propertyCnt = 0;
                         if (CRM_Utils_Array::value($dao->id, $eventParticipant[$name])) {
                             $propertyCnt = $eventParticipant[$name][$dao->id];
                             if ($name == 'participants') {
                                 $set = CRM_Utils_System::url('civicrm/event/search', "reset=1&force=1&event={$dao->id}&status=true&role=true");
                             } else {
                                 if ($name == 'notCountedParticipants') {
                                     // FIXME : selector fail to search w/ OR operator.
                                     // $set = CRM_Utils_System::url( 'civicrm/event/search',
                                     // "reset=1&force=1&event=$dao->id&status=false&role=false" );
                                 } else {
                                     if ($name == 'notCountedDueToStatus') {
                                         $set = CRM_Utils_System::url('civicrm/event/search', "reset=1&force=1&event={$dao->id}&status=false");
                                     } else {
                                         $set = CRM_Utils_System::url('civicrm/event/search', "reset=1&force=1&event={$dao->id}&role=false");
                                     }
                                 }
                             }
                         }
                         $eventSummary['events'][$dao->id][$property] = $propertyCnt;
                         $eventSummary['events'][$dao->id][$name . '_url'] = $set;
                         break;
                     default:
                         $eventSummary['events'][$dao->id][$property] = $dao->{$name};
                         break;
                 }
             }
             // prepare the area for per-status participant counts
             $statusClasses = array('Positive', 'Pending', 'Waiting', 'Negative');
             $eventSummary['events'][$dao->id]['statuses'] = array_fill_keys($statusClasses, array());
             // get eventIds.
             if (!in_array($dao->id, $eventIds)) {
                 $eventIds[] = $dao->id;
             }
         } else {
             $eventSummary['total_events']--;
         }
         $eventSummary['events'][$dao->id]['friend'] = $dao->is_friend_active;
         $eventSummary['events'][$dao->id]['is_monetary'] = $dao->is_monetary;
         $eventSummary['events'][$dao->id]['is_online_registration'] = $dao->is_online_registration;
         $eventSummary['events'][$dao->id]['is_show_location'] = $dao->is_show_location;
     }
     require_once 'CRM/Event/PseudoConstant.php';
     $countedRoles = CRM_Event_PseudoConstant::participantRole(null, 'filter = 1');
     $nonCountedRoles = CRM_Event_PseudoConstant::participantRole(null, '( filter = 0 OR filter IS NULL )');
     $countedStatus = CRM_Event_PseudoConstant::participantStatus(null, 'is_counted = 1');
     $nonCountedStatus = CRM_Event_PseudoConstant::participantStatus(null, '( is_counted = 0 OR is_counted IS NULL )');
     $roleSQL = '';
     if (!empty($countedRoles)) {
         $roleSQL = " AND role_id in ( " . implode(',', array_keys($countedRoles)) . ') ';
     }
     $eventIdsClause = '';
     if (!empty($eventIds)) {
         $eventIdsClause = "WHERE p.event_id IN (" . implode(',', $eventIds) . ") {$roleSQL} ";
     }
     $statusTypes = CRM_Event_PseudoConstant::participantStatus();
     $participantStatusSummary = self::getParticipantCount(false, false, false, false, $eventIds, true);
     foreach ($participantStatusSummary as $eventId => $values) {
         foreach ($values as $statusId => $statusValues) {
             $class = $statusValues['class'];
             $count = CRM_Utils_Array::value('count', $statusValues);
             $urlString = "reset=1&force=1&event={$eventId}&status={$statusId}";
             $statusInfo = array('url' => CRM_Utils_System::url('civicrm/event/search', $urlString), 'name' => $statusTypes[$statusId], 'count' => $count);
             $eventSummary['events'][$eventId]['statuses'][$class][] = $statusInfo;
         }
     }
     $countedStatusANDRoles = array_merge($countedStatus, $countedRoles);
     $nonCountedStatusANDRoles = array_merge($nonCountedStatus, $nonCountedRoles);
     $eventSummary['nonCountedRoles'] = implode('/', array_values($nonCountedRoles));
     $eventSummary['nonCountedStatus'] = implode('/', array_values($nonCountedStatus));
     $eventSummary['countedStatusANDRoles'] = implode('/', array_values($countedStatusANDRoles));
     $eventSummary['nonCountedStatusANDRoles'] = implode('/', array_values($nonCountedStatusANDRoles));
     return $eventSummary;
 }
Example #14
0
 /**
  * Browse all events.
  *
  * @return void
  */
 public function browse()
 {
     Civi::resources()->addStyleFile('civicrm', 'css/searchForm.css', 1, 'html-header');
     $this->_sortByCharacter = CRM_Utils_Request::retrieve('sortByCharacter', 'String', $this);
     $createdId = CRM_Utils_Request::retrieve('cid', 'Positive', $this, FALSE, 0);
     if (strtolower($this->_sortByCharacter) == 'all' || !empty($_POST)) {
         $this->_sortByCharacter = '';
         $this->set('sortByCharacter', '');
     }
     $this->_force = $this->_searchResult = NULL;
     $this->search();
     $params = array();
     $this->_force = CRM_Utils_Request::retrieve('force', 'Boolean', $this, FALSE);
     $this->_searchResult = CRM_Utils_Request::retrieve('searchResult', 'Boolean', $this);
     $whereClause = $this->whereClause($params, FALSE, $this->_force);
     $this->pagerAToZ($whereClause, $params);
     $params = array();
     $whereClause = $this->whereClause($params, TRUE, $this->_force);
     // because is_template != 1 would be to simple
     $whereClause .= ' AND (is_template = 0 OR is_template IS NULL)';
     $this->pager($whereClause, $params);
     list($offset, $rowCount) = $this->_pager->getOffsetAndRowCount();
     // get all custom groups sorted by weight
     $manageEvent = array();
     $query = "\n  SELECT *\n    FROM civicrm_event\n   WHERE {$whereClause}\nORDER BY start_date desc\n   LIMIT {$offset}, {$rowCount}";
     $dao = CRM_Core_DAO::executeQuery($query, $params, TRUE, 'CRM_Event_DAO_Event');
     $permissions = CRM_Event_BAO_Event::checkPermission();
     //get all campaigns.
     $allCampaigns = CRM_Campaign_BAO_Campaign::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
     // get the list of active event pcps
     $eventPCPS = array();
     $pcpDao = new CRM_PCP_DAO_PCPBlock();
     $pcpDao->entity_table = 'civicrm_event';
     $pcpDao->find();
     while ($pcpDao->fetch()) {
         $eventPCPS[$pcpDao->entity_id] = $pcpDao->entity_id;
     }
     // check if we're in shopping cart mode for events
     $enableCart = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::EVENT_PREFERENCES_NAME, 'enable_cart');
     $this->assign('eventCartEnabled', $enableCart);
     $mapping = CRM_Utils_Array::first(CRM_Core_BAO_ActionSchedule::getMappings(array('id' => CRM_Event_ActionMapping::EVENT_NAME_MAPPING_ID)));
     $eventType = CRM_Core_OptionGroup::values('event_type');
     while ($dao->fetch()) {
         if (in_array($dao->id, $permissions[CRM_Core_Permission::VIEW])) {
             $manageEvent[$dao->id] = array();
             $repeat = CRM_Core_BAO_RecurringEntity::getPositionAndCount($dao->id, 'civicrm_event');
             $manageEvent[$dao->id]['repeat'] = '';
             if ($repeat) {
                 $manageEvent[$dao->id]['repeat'] = ts('Repeating (%1 of %2)', array(1 => $repeat[0], 2 => $repeat[1]));
             }
             CRM_Core_DAO::storeValues($dao, $manageEvent[$dao->id]);
             // form all action links
             $action = array_sum(array_keys($this->links()));
             if ($dao->is_active) {
                 $action -= CRM_Core_Action::ENABLE;
             } else {
                 $action -= CRM_Core_Action::DISABLE;
             }
             if (!in_array($dao->id, $permissions[CRM_Core_Permission::DELETE])) {
                 $action -= CRM_Core_Action::DELETE;
             }
             if (!in_array($dao->id, $permissions[CRM_Core_Permission::EDIT])) {
                 $action -= CRM_Core_Action::UPDATE;
             }
             $manageEvent[$dao->id]['action'] = CRM_Core_Action::formLink(self::links(), $action, array('id' => $dao->id), ts('more'), TRUE, 'event.manage.list', 'Event', $dao->id);
             $params = array('entity_id' => $dao->id, 'entity_table' => 'civicrm_event', 'is_active' => 1);
             $defaults['location'] = CRM_Core_BAO_Location::getValues($params, TRUE);
             $manageEvent[$dao->id]['friend'] = CRM_Friend_BAO_Friend::getValues($params);
             if (isset($defaults['location']['address'][1]['city'])) {
                 $manageEvent[$dao->id]['city'] = $defaults['location']['address'][1]['city'];
             }
             if (isset($defaults['location']['address'][1]['state_province_id'])) {
                 $manageEvent[$dao->id]['state_province'] = CRM_Core_PseudoConstant::stateProvince($defaults['location']['address'][1]['state_province_id']);
             }
             //show campaigns on selector.
             $manageEvent[$dao->id]['campaign'] = CRM_Utils_Array::value($dao->campaign_id, $allCampaigns);
             $manageEvent[$dao->id]['reminder'] = CRM_Core_BAO_ActionSchedule::isConfigured($dao->id, $mapping->getId());
             $manageEvent[$dao->id]['is_pcp_enabled'] = CRM_Utils_Array::value($dao->id, $eventPCPS);
             $manageEvent[$dao->id]['event_type'] = CRM_Utils_Array::value($manageEvent[$dao->id]['event_type_id'], $eventType);
             $manageEvent[$dao->id]['is_repeating_event'] = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_RecurringEntity', $dao->id, 'parent_id', 'entity_id');
             // allow hooks to set 'field' value which allows configuration pop-up to show a tab as enabled/disabled
             CRM_Utils_Hook::tabset('civicrm/event/manage/rows', $manageEvent, array('event_id' => $dao->id));
         }
     }
     $manageEvent['tab'] = self::tabs($enableCart);
     $this->assign('rows', $manageEvent);
     $statusTypes = CRM_Event_PseudoConstant::participantStatus(NULL, 'is_counted = 1');
     $statusTypesPending = CRM_Event_PseudoConstant::participantStatus(NULL, 'is_counted = 0');
     $findParticipants['statusCounted'] = implode(', ', array_values($statusTypes));
     $findParticipants['statusNotCounted'] = implode(', ', array_values($statusTypesPending));
     $this->assign('findParticipants', $findParticipants);
 }
 /**
  * @param array $params
  *
  * @return mixed
  */
 public function emailReceipt(&$params)
 {
     // email receipt sending
     // send message template
     if ($this->_component == 'event') {
         $eventId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $this->_id, 'event_id', 'id');
         $returnProperties = array('fee_label', 'start_date', 'end_date', 'is_show_location', 'title');
         CRM_Core_DAO::commonRetrieveAll('CRM_Event_DAO_Event', 'id', $eventId, $events, $returnProperties);
         $event = $events[$eventId];
         unset($event['start_date']);
         unset($event['end_date']);
         $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' => $eventId, 'entity_table' => 'civicrm_event');
             $location = CRM_Core_BAO_Location::getValues($locationParams, TRUE);
             $this->assign('location', $location);
         }
     }
     // assign payment info here
     $paymentConfig['confirm_email_text'] = CRM_Utils_Array::value('confirm_email_text', $params);
     $this->assign('paymentConfig', $paymentConfig);
     $isRefund = $this->_paymentType == 'refund' ? TRUE : FALSE;
     $this->assign('isRefund', $isRefund);
     if ($isRefund) {
         $this->assign('totalPaid', $this->_amtPaid);
         $this->assign('totalAmount', $this->_amtTotal);
         $this->assign('refundAmount', $params['total_amount']);
     } else {
         $balance = $this->_amtTotal - ($this->_amtPaid + $params['total_amount']);
         $paymentsComplete = $balance == 0 ? 1 : 0;
         $this->assign('amountOwed', $balance);
         $this->assign('totalAmount', $this->_amtTotal);
         $this->assign('paymentAmount', $params['total_amount']);
         $this->assign('paymentsComplete', $paymentsComplete);
     }
     $this->assign('contactDisplayName', $this->_contributorDisplayName);
     // assign trxn details
     $this->assign('trxn_id', CRM_Utils_Array::value('trxn_id', $params));
     $this->assign('receive_date', CRM_Utils_Array::value('trxn_date', $params));
     $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
     if (array_key_exists('payment_instrument_id', $params)) {
         $this->assign('paidBy', CRM_Utils_Array::value($params['payment_instrument_id'], $paymentInstrument));
     }
     $this->assign('checkNumber', CRM_Utils_Array::value('check_number', $params));
     $sendTemplateParams = array('groupName' => 'msg_tpl_workflow_contribution', 'valueName' => 'payment_or_refund_notification', 'contactId' => $this->_contactId, 'PDFFilename' => ts('notification') . '.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 && !$this->_toDoNotEmail) {
         if (array_key_exists($params['from_email_address'], $this->_fromEmails['from_email_id'])) {
             $receiptFrom = $params['from_email_address'];
         }
         $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);
     }
     list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
     return $mailSent;
 }
Example #16
0
 /**
  * Run the page.
  *
  * This method is called after the page is created. It checks for the  
  * type of action and executes that action.
  * Finally it calls the parent's run method.
  *
  * @return void
  * @access public
  *
  */
 function run()
 {
     //get the event id.
     $this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this, true);
     $config =& CRM_Core_Config::singleton();
     require_once 'CRM/Event/BAO/Event.php';
     // ensure that the user has permission to see this page
     if (!CRM_Core_Permission::event(CRM_Core_Permission::VIEW, $this->_id)) {
         CRM_Core_Error::fatal(ts('You do not have permission to view this event'));
     }
     $action = CRM_Utils_Request::retrieve('action', 'String', $this, false);
     $context = CRM_Utils_Request::retrieve('context', 'String', $this, false, 'register');
     $this->assign('context', $context);
     // Sometimes we want to suppress the Event Full msg
     $noFullMsg = CRM_Utils_Request::retrieve('noFullMsg', 'String', $this, false, 'false');
     // set breadcrumb to append to 2nd layer pages
     $breadCrumbPath = CRM_Utils_System::url("civicrm/event/info", "id={$this->_id}&reset=1");
     $additionalBreadCrumb = "<a href=\"{$breadCrumbPath}\">" . ts('Events') . '</a>';
     //retrieve event information
     $params = array('id' => $this->_id);
     CRM_Event_BAO_Event::retrieve($params, $values['event']);
     if (!$values['event']['is_active']) {
         // form is inactive, die a fatal death
         CRM_Core_Error::fatal(ts('The page you requested is currently unavailable.'));
     }
     $this->assign('isShowLocation', CRM_Utils_Array::value('is_show_location', $values['event']));
     // show event fees.
     require_once 'CRM/Price/BAO/Set.php';
     if ($this->_id && CRM_Utils_Array::value('is_monetary', $values['event'])) {
         // get price set options, - CRM-5209
         if ($priceSetId = CRM_Price_BAO_Set::getFor('civicrm_event', $this->_id)) {
             $setDetails = CRM_Price_BAO_Set::getSetDetail($priceSetId);
             eval("\$priceSetFields = \$setDetails[{$priceSetId}][fields];");
             if (is_array($priceSetFields)) {
                 $fieldCnt = 1;
                 foreach ($priceSetFields as $fid => $fieldValues) {
                     if (!is_array($fieldValues['options']) || empty($fieldValues['options'])) {
                         continue;
                     }
                     foreach ($fieldValues['options'] as $optionId => $optionVal) {
                         $values['feeBlock']['value'][$fieldCnt] = $optionVal['value'];
                         $values['feeBlock']['label'][$fieldCnt] = $optionVal['description'];
                         $fieldCnt++;
                     }
                 }
             }
         } else {
             //retrieve event fee block.
             require_once 'CRM/Core/OptionGroup.php';
             require_once 'CRM/Core/BAO/Discount.php';
             $discountId = CRM_Core_BAO_Discount::findSet($this->_id, 'civicrm_event');
             if ($discountId) {
                 CRM_Core_OptionGroup::getAssoc(CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Discount', $discountId, 'option_group_id'), $values['feeBlock'], false, 'id');
             } else {
                 CRM_Core_OptionGroup::getAssoc("civicrm_event.amount.{$this->_id}", $values['feeBlock']);
             }
         }
     }
     $params = array('entity_id' => $this->_id, 'entity_table' => 'civicrm_event');
     require_once 'CRM/Core/BAO/Location.php';
     $values['location'] = CRM_Core_BAO_Location::getValues($params, true);
     //retrieve custom field information
     require_once 'CRM/Core/BAO/CustomGroup.php';
     $groupTree =& CRM_Core_BAO_CustomGroup::getTree("Event", $this, $this->_id, 0, $values['event']['event_type_id']);
     CRM_Core_BAO_CustomGroup::buildCustomDataView($this, $groupTree);
     $this->assign('action', CRM_Core_Action::VIEW);
     //To show the event location on maps directly on event info page
     $locations =& CRM_Event_BAO_Event::getMapInfo($this->_id);
     if (!empty($locations) && CRM_Utils_Array::value('is_map', $values['event'])) {
         $this->assign('locations', $locations);
         $this->assign('mapProvider', $config->mapProvider);
         $this->assign('mapKey', $config->mapAPIKey);
         $sumLat = $sumLng = 0;
         $maxLat = $maxLng = -400;
         $minLat = $minLng = +400;
         foreach ($locations as $location) {
             $sumLat += $location['lat'];
             $sumLng += $location['lng'];
             if ($location['lat'] > $maxLat) {
                 $maxLat = $location['lat'];
             }
             if ($location['lat'] < $minLat) {
                 $minLat = $location['lat'];
             }
             if ($location['lng'] > $maxLng) {
                 $maxLng = $location['lng'];
             }
             if ($location['lng'] < $minLng) {
                 $minLng = $location['lng'];
             }
         }
         $center = array('lat' => (double) $sumLat / count($locations), 'lng' => (double) $sumLng / count($locations));
         $span = array('lat' => (double) ($maxLat - $minLat), 'lng' => (double) ($maxLng - $minLng));
         $this->assign_by_ref('center', $center);
         $this->assign_by_ref('span', $span);
     }
     require_once 'CRM/Event/BAO/Participant.php';
     $eventFullMessage = CRM_Event_BAO_Participant::eventFull($this->_id);
     if ($eventFullMessage and $noFullMsg == 'false') {
         if (CRM_Utils_Array::value('has_waitlist', $values['event'])) {
             $eventFullMessage = null;
             $statusMessage = CRM_Utils_Array::value('waitlist_text', $values['event'], 'Event is currently full, but you can register and be a part of waiting list.');
         } else {
             $statusMessage = $eventFullMessage;
         }
         CRM_Core_Session::setStatus($statusMessage);
     }
     if (CRM_Utils_Array::value('is_online_registration', $values['event'])) {
         if (CRM_Event_BAO_Event::validRegistrationDate($values['event'], $this->_id)) {
             if (!$eventFullMessage) {
                 $registerText = ts('Register Now');
                 if (CRM_Utils_Array::value('registration_link_text', $values['event'])) {
                     $registerText = $values['event']['registration_link_text'];
                 }
                 //Fixed for CRM-4855
                 if (CRM_Event_BAO_Event::showHideRegistrationLink($values)) {
                     $this->assign('allowRegistration', true);
                 }
                 $this->assign('registerText', $registerText);
             }
             // we always generate urls for the front end in joomla
             if ($action == CRM_Core_Action::PREVIEW) {
                 $url = CRM_Utils_System::url('civicrm/event/register', "id={$this->_id}&reset=1&action=preview", true, null, true, true);
             } else {
                 $url = CRM_Utils_System::url('civicrm/event/register', "id={$this->_id}&reset=1", true, null, true, true);
             }
             if (!$eventFullMessage) {
                 $this->assign('registerURL', $url);
             }
         }
         if ($action == CRM_Core_Action::PREVIEW) {
             $mapURL = CRM_Utils_System::url('civicrm/contact/map/event', "eid={$this->_id}&reset=1&action=preview", true, null, true, true);
         } else {
             $mapURL = CRM_Utils_System::url('civicrm/contact/map/event', "eid={$this->_id}&reset=1", true, null, true, true);
         }
         $this->assign('mapURL', $mapURL);
     }
     // we do not want to display recently viewed items, so turn off
     $this->assign('displayRecent', false);
     // set page title = event title
     CRM_Utils_System::setTitle($values['event']['title']);
     $this->assign('event', $values['event']);
     if (isset($values['feeBlock'])) {
         $this->assign('feeBlock', $values['feeBlock']);
     }
     $this->assign('location', $values['location']);
     parent::run();
 }
Example #17
0
 /**
  * Build elements to enable pay on behalf of an organization.
  */
 public function buildOnBehalfOrganization()
 {
     if ($this->_membershipContactID) {
         $entityBlock = array('contact_id' => $this->_membershipContactID);
         CRM_Core_BAO_Location::getValues($entityBlock, $this->_defaults);
     }
     if (!$this->_onBehalfRequired) {
         $this->addElement('checkbox', 'is_for_organization', $this->_values['for_organization'], NULL, array('onclick' => "showOnBehalf( );"));
     }
     $this->assign('is_for_organization', TRUE);
     $this->assign('urlPath', 'civicrm/contribute/transact');
 }
Example #18
0
 /**
  * Process the form when submitted
  *
  * @return void
  * @access public
  */
 public function postProcess()
 {
     require_once 'CRM/Core/BAO/Domain.php';
     $params = array();
     $params = $this->exportValues();
     $params['entity_id'] = $this->_id;
     $params['entity_table'] = CRM_Core_BAO_Domain::getTableName();
     $domain = CRM_Core_BAO_Domain::edit($params, $this->_id);
     require_once 'CRM/Core/BAO/LocationType.php';
     $defaultLocationType =& CRM_Core_BAO_LocationType::getDefault();
     $location = array();
     $params['address'][1]['location_type_id'] = $defaultLocationType->id;
     $params['phone'][1]['location_type_id'] = $defaultLocationType->id;
     $params['email'][1]['location_type_id'] = $defaultLocationType->id;
     $location = CRM_Core_BAO_Location::create($params, true, 'domain');
     $params['loc_block_id'] = $location['id'];
     require_once 'CRM/Core/BAO/Domain.php';
     CRM_Core_BAO_Domain::edit($params, $this->_id);
     //set domain from email address, CRM-3552
     $emailName = '"' . $params['email_name'] . '"<' . $params['email_address'] . '>';
     $emailParams = array('label' => $emailName, 'description' => $params['description'], 'is_active' => 1, 'is_default' => 1);
     $groupParams = array('name' => 'from_email_address');
     //get the option value wt.
     if ($this->_fromEmailId) {
         $action = $this->_action;
         $emailParams['weight'] = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionValue', $this->_fromEmailId, 'weight');
     } else {
         //add from email address.
         $action = CRM_Core_Action::ADD;
         require_once 'CRM/Utils/Weight.php';
         $grpId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup', 'from_email_address', 'id', 'name');
         $fieldValues = array('option_group_id' => $grpId);
         $emailParams['weight'] = CRM_Utils_Weight::getDefaultWeight('CRM_Core_DAO_OptionValue', $fieldValues);
     }
     require_once 'CRM/Core/OptionValue.php';
     //reset default within domain.
     $emailParams['reset_default_for'] = array('domain_id' => CRM_Core_Config::domainID());
     CRM_Core_OptionValue::addOptionValue($emailParams, $groupParams, $action, $this->_fromEmailId);
     CRM_Core_Session::setStatus(ts('Domain information for \'%1\' has been saved.', array(1 => $domain->name)));
     $session =& CRM_Core_Session::singleton();
     $session->replaceUserContext(CRM_Utils_System::url('civicrm/admin', 'reset=1'));
 }
Example #19
0
 /**
  * process the form after the input has been submitted and validated
  *
  * @access public
  *
  * @return void
  */
 public function postProcess()
 {
     $fv = $this->controller->exportValues($this->_name);
     $config = CRM_Core_Config::singleton();
     $locName = NULL;
     //get the address format sequence from the config file
     $mailingFormat = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'mailing_format');
     $sequence = CRM_Utils_Address::sequence($mailingFormat);
     foreach ($sequence as $v) {
         $address[$v] = 1;
     }
     if (array_key_exists('postal_code', $address)) {
         $address['postal_code_suffix'] = 1;
     }
     //build the returnproperties
     $returnProperties = array('display_name' => 1, 'contact_type' => 1);
     $mailingFormat = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'mailing_format');
     $mailingFormatProperties = array();
     if ($mailingFormat) {
         $mailingFormatProperties = self::getReturnProperties($mailingFormat);
         $returnProperties = array_merge($returnProperties, $mailingFormatProperties);
     }
     //we should not consider addressee for data exists, CRM-6025
     if (array_key_exists('addressee', $mailingFormatProperties)) {
         unset($mailingFormatProperties['addressee']);
     }
     $customFormatProperties = array();
     if (stristr($mailingFormat, 'custom_')) {
         foreach ($mailingFormatProperties as $token => $true) {
             if (substr($token, 0, 7) == 'custom_') {
                 if (empty($customFormatProperties[$token])) {
                     $customFormatProperties[$token] = $mailingFormatProperties[$token];
                 }
             }
         }
     }
     if (!empty($customFormatProperties)) {
         $returnProperties = array_merge($returnProperties, $customFormatProperties);
     }
     if (isset($fv['merge_same_address'])) {
         // we need first name/last name for summarising to avoid spillage
         $returnProperties['first_name'] = 1;
         $returnProperties['last_name'] = 1;
     }
     $individualFormat = FALSE;
     /*
      * CRM-8338: replace ids of household members with the id of their household
      * so we can merge labels by household.
      */
     if (isset($fv['merge_same_household'])) {
         $this->mergeContactIdsByHousehold();
         $individualFormat = TRUE;
     }
     //get the contacts information
     $params = array();
     if (!empty($fv['location_type_id'])) {
         $locType = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
         $locName = $locType[$fv['location_type_id']];
         $location = array('location' => array("{$locName}" => $address));
         $returnProperties = array_merge($returnProperties, $location);
         $params[] = array('location_type', '=', array($fv['location_type_id'] => 1), 0, 0);
     } else {
         $returnProperties = array_merge($returnProperties, $address);
     }
     $rows = array();
     foreach ($this->_contactIds as $key => $contactID) {
         $params[] = array(CRM_Core_Form::CB_PREFIX . $contactID, '=', 1, 0, 0);
     }
     // fix for CRM-2651
     if (!empty($fv['do_not_mail'])) {
         $params[] = array('do_not_mail', '=', 0, 0, 0);
     }
     // fix for CRM-2613
     $params[] = array('is_deceased', '=', 0, 0, 0);
     $custom = array();
     foreach ($returnProperties as $name => $dontCare) {
         $cfID = CRM_Core_BAO_CustomField::getKeyID($name);
         if ($cfID) {
             $custom[] = $cfID;
         }
     }
     //get the total number of contacts to fetch from database.
     $numberofContacts = count($this->_contactIds);
     $query = new CRM_Contact_BAO_Query($params, $returnProperties);
     $details = $query->apiQuery($params, $returnProperties, NULL, NULL, 0, $numberofContacts);
     $messageToken = CRM_Utils_Token::getTokens($mailingFormat);
     // also get all token values
     CRM_Utils_Hook::tokenValues($details[0], $this->_contactIds, NULL, $messageToken, 'CRM_Contact_Form_Task_Label');
     $tokens = array();
     CRM_Utils_Hook::tokens($tokens);
     $tokenFields = array();
     foreach ($tokens as $category => $catTokens) {
         foreach ($catTokens as $token => $tokenName) {
             $tokenFields[] = $token;
         }
     }
     foreach ($this->_contactIds as $value) {
         foreach ($custom as $cfID) {
             if (isset($details[0][$value]["custom_{$cfID}"])) {
                 $details[0][$value]["custom_{$cfID}"] = CRM_Core_BAO_CustomField::getDisplayValue($details[0][$value]["custom_{$cfID}"], $cfID, $details[1]);
             }
         }
         $contact = CRM_Utils_Array::value($value, $details['0']);
         if (is_a($contact, 'CRM_Core_Error')) {
             return NULL;
         }
         // we need to remove all the "_id"
         unset($contact['contact_id']);
         if ($locName && !empty($contact[$locName])) {
             // If location type is not primary, $contact contains
             // one more array as "$contact[$locName] = array( values... )"
             if (!$this->tokenIsFound($contact, $mailingFormatProperties, $tokenFields)) {
                 continue;
             }
             unset($contact[$locName]);
             if (!empty($contact['county_id'])) {
                 unset($contact['county_id']);
             }
             foreach ($contact as $field => $fieldValue) {
                 $rows[$value][$field] = $fieldValue;
             }
             $valuesothers = array();
             $paramsothers = array('contact_id' => $value);
             $valuesothers = CRM_Core_BAO_Location::getValues($paramsothers, $valuesothers);
             if (!empty($fv['location_type_id'])) {
                 foreach ($valuesothers as $vals) {
                     if (CRM_Utils_Array::value('location_type_id', $vals) == CRM_Utils_Array::value('location_type_id', $fv)) {
                         foreach ($vals as $k => $v) {
                             if (in_array($k, array('email', 'phone', 'im', 'openid'))) {
                                 if ($k == 'im') {
                                     $rows[$value][$k] = $v['1']['name'];
                                 } else {
                                     $rows[$value][$k] = $v['1'][$k];
                                 }
                                 $rows[$value][$k . '_id'] = $v['1']['id'];
                             }
                         }
                     }
                 }
             }
         } else {
             if (!$this->tokenIsFound($contact, $mailingFormatProperties, $tokenFields)) {
                 continue;
             }
             if (!empty($contact['addressee_display'])) {
                 $contact['addressee_display'] = trim($contact['addressee_display']);
             }
             if (!empty($contact['addressee'])) {
                 $contact['addressee'] = $contact['addressee_display'];
             }
             // now create the rows for generating mailing labels
             foreach ($contact as $field => $fieldValue) {
                 $rows[$value][$field] = $fieldValue;
             }
         }
     }
     if (isset($fv['merge_same_address'])) {
         $this->mergeSameAddress($rows);
         $individualFormat = TRUE;
     }
     // format the addresses according to CIVICRM_ADDRESS_FORMAT (CRM-1327)
     foreach ($rows as $id => $row) {
         if ($commMethods = CRM_Utils_Array::value('preferred_communication_method', $row)) {
             $val = array_filter(explode(CRM_Core_DAO::VALUE_SEPARATOR, $commMethods));
             $comm = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'preferred_communication_method');
             $temp = array();
             foreach ($val as $vals) {
                 $temp[] = $comm[$vals];
             }
             $row['preferred_communication_method'] = implode(', ', $temp);
         }
         $row['id'] = $id;
         $formatted = CRM_Utils_Address::format($row, 'mailing_format', FALSE, TRUE, $individualFormat, $tokenFields);
         // CRM-2211: UFPDF doesn't have bidi support; use the PECL fribidi package to fix it.
         // On Ubuntu (possibly Debian?) be aware of http://pecl.php.net/bugs/bug.php?id=12366
         // Due to FriBidi peculiarities, this can't be called on
         // a multi-line string, hence the explode+implode approach.
         if (function_exists('fribidi_log2vis')) {
             $lines = explode("\n", $formatted);
             foreach ($lines as $i => $line) {
                 $lines[$i] = fribidi_log2vis($line, FRIBIDI_AUTO, FRIBIDI_CHARSET_UTF8);
             }
             $formatted = implode("\n", $lines);
         }
         $rows[$id] = array($formatted);
     }
     //call function to create labels
     self::createLabel($rows, $fv['label_name']);
     CRM_Utils_System::civiExit(1);
 }
Example #20
0
 /** 
  * Function to process the form 
  * 
  * @access public 
  */
 public function postProcess()
 {
     if ($this->_action & CRM_Core_Action::DELETE) {
         require_once "CRM/Event/BAO/Participant.php";
         CRM_Event_BAO_Participant::deleteParticipant($this->_participantId);
         return;
     }
     // get the submitted form values.
     $params = $this->controller->exportValues($this->_name);
     // set the contact, when contact is selected
     if (CRM_Utils_Array::value('contact_select_id', $params)) {
         $this->_contactID = CRM_Utils_Array::value('contact_select_id', $params);
     }
     $config =& CRM_Core_Config::singleton();
     //check if discount is selected
     if (CRM_Utils_Array::value('discount_id', $params)) {
         $discountId = $params['discount_id'];
     } else {
         $params['discount_id'] = 'null';
         $discountId = null;
     }
     if ($this->_isPaidEvent) {
         //lets carry currency, CRM-4453
         $params['fee_currency'] = $config->defaultCurrency;
         // fix for CRM-3088
         if ($discountId && !empty($this->_values['discount'][$discountId])) {
             $params['amount_level'] = $this->_values['discount'][$discountId][$params['amount']]['label'];
             $params['amount'] = $this->_values['discount'][$discountId][$params['amount']]['value'];
             $this->assign('amount_level', $params['amount_level']);
         } else {
             if (!isset($params['priceSetId'])) {
                 $params['amount_level'] = $this->_values['fee'][$params['amount']]['label'];
                 $params['amount'] = $this->_values['fee'][$params['amount']]['value'];
                 $this->assign('amount_level', $params['amount_level']);
             } else {
                 if (!$this->_online) {
                     $lineItem = array();
                     CRM_Price_BAO_Set::processAmount($this->_values['fee']['fields'], $params, $lineItem[0]);
                     $this->set('lineItem', $lineItem);
                     $this->assign('lineItem', $lineItem);
                     $this->_lineItem = $lineItem;
                 }
             }
         }
         $params['fee_level'] = $params['amount_level'];
         $contributionParams = array();
         $contributionParams['total_amount'] = $params['amount'];
     }
     //fix for CRM-3086
     $params['fee_amount'] = $params['amount'];
     $this->_params = $params;
     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));
     $params['contact_id'] = $this->_contactID;
     if ($this->_participantId) {
         $params['id'] = $this->_participantId;
     }
     $status = null;
     if ($this->_action & CRM_Core_Action::UPDATE) {
         $participantBAO =& new CRM_Event_BAO_Participant();
         $participantBAO->id = $this->_participantId;
         $participantBAO->find();
         while ($participantBAO->fetch()) {
             $status = $participantBAO->status_id;
             $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;
     }
     require_once 'CRM/Contact/BAO/Contact.php';
     // Retrieve the name and email of the current user - this will be the FROM for the receipt email
     $session =& CRM_Core_Session::singleton();
     $userID = $session->get('userID');
     list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($userID);
     require_once "CRM/Event/BAO/Participant.php";
     if ($this->_mode) {
         if (!$this->_isPaidEvent) {
             CRM_Core_Error::fatal(ts('Selected Event is not Paid Event '));
         }
         //modify params according to parameter used in create
         //participant method (addParticipant)
         $params['participant_status_id'] = $params['status_id'];
         $params['participant_role_id'] = $params['role_id'];
         $params['participant_register_date'] = $params['register_date'];
         $params['participant_source'] = $params['source'];
         require_once 'CRM/Core/BAO/PaymentProcessor.php';
         $this->_paymentProcessor = CRM_Core_BAO_PaymentProcessor::getPayment($this->_params['payment_processor_id'], $this->_mode);
         require_once "CRM/Contact/BAO/Contact.php";
         $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);
     }
     // build custom data getFields array
     $customFieldsRole = CRM_Core_BAO_CustomField::getFields('Participant', false, false, CRM_Utils_Array::value('role_id', $params), $this->_roleCustomDataTypeID);
     $customFieldsEvent = CRM_Core_BAO_CustomField::getFields('Participant', false, false, CRM_Utils_Array::value('event_id', $params), $this->_eventNameCustomDataTypeID);
     $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsRole, CRM_Core_BAO_CustomField::getFields('Participant', false, false, null, null, true));
     $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsEvent, $customFields);
     $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $customFields, $this->_participantId, 'Participant');
     if ($this->_mode) {
         // add all the additioanl payment params we need
         $this->_params["state_province-{$this->_bltID}"] = $this->_params["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($this->_params["billing_state_province_id-{$this->_bltID}"]);
         $this->_params["country-{$this->_bltID}"] = $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]);
         $this->_params['year'] = $this->_params['credit_card_exp_date']['Y'];
         $this->_params['month'] = $this->_params['credit_card_exp_date']['M'];
         $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['payment_action'] = 'Sale';
         $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 (CRM_Utils_Array::value('send_receipt', $this->_params)) {
             $paymentParams['email'] = $this->_contributorEmail;
         }
         require_once 'CRM/Core/Payment/Form.php';
         CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, true);
         $payment =& CRM_Core_Payment::singleton($this->_mode, 'Event', $this->_paymentProcessor, $this);
         $result =& $payment->doDirectPayment($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 (CRM_Utils_Array::value('send_receipt', $this->_params)) {
             $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']));
         // set source if not set
         $this->_params['description'] = ts('Submit Credit Card for Event Registration by: %1', array(1 => $userName));
         require_once 'CRM/Event/Form/Registration/Confirm.php';
         require_once 'CRM/Event/Form/Registration.php';
         //add contribution record
         $this->_params['contribution_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'contribution_type_id');
         $this->_params['mode'] = $this->_mode;
         //add contribution reocord
         $contribution = CRM_Event_Form_Registration_Confirm::processContribution($this, $this->_params, $result, $contactID, false);
         // add participant record
         $participants = array();
         $participants[] = CRM_Event_Form_Registration::addParticipant($this->_params, $contactID);
         //add custom data for participant
         require_once 'CRM/Core/BAO/CustomValueTable.php';
         CRM_Core_BAO_CustomValueTable::postProcess($this->_params, CRM_Core_DAO::$_nullArray, 'civicrm_participant', $participants[0]->id, 'Participant');
         //add participant payment
         require_once 'CRM/Event/BAO/ParticipantPayment.php';
         $paymentParticipant = array('participant_id' => $participants[0]->id, 'contribution_id' => $contribution->id);
         $ids = array();
         CRM_Event_BAO_ParticipantPayment::create($paymentParticipant, $ids);
         $eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'title');
         $this->_contactIds[] = $this->_contactID;
     } else {
         $participants = array();
         // fix note if deleted
         if (!$params['note']) {
             $params['note'] = 'null';
         }
         if ($this->_single) {
             $participants[] = CRM_Event_BAO_Participant::create($params);
         } else {
             foreach ($this->_contactIds as $contactID) {
                 $commonParams = $params;
                 $commonParams['contact_id'] = $contactID;
                 $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;
         }
         if (CRM_Utils_Array::value('record_contribution', $params)) {
             if (CRM_Utils_Array::value('id', $params)) {
                 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) {
                 $contributionParams['source'] = "{$eventTitle}: Offline registration (by {$userName})";
             }
             $contributionParams['currency'] = $config->defaultCurrency;
             $contributionParams['non_deductible_amount'] = 'null';
             $contributionParams['receipt_date'] = CRM_Utils_Array::value('send_receipt', $params) ? CRM_Utils_Array::value('receive_date', $params) : 'null';
             $recordContribution = array('contact_id', 'contribution_type_id', 'payment_instrument_id', 'trxn_id', 'contribution_status_id', 'receive_date', 'check_number');
             foreach ($recordContribution as $f) {
                 $contributionParams[$f] = CRM_Utils_Array::value($f, $params);
                 if ($f == 'trxn_id') {
                     $this->assign('trxn_id', $contributionParams[$f]);
                 }
             }
             //insert contribution type name in receipt.
             $this->assign('contributionTypeName', CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionType', $contributionParams['contribution_type_id']));
             require_once 'CRM/Contribute/BAO/Contribution.php';
             $contributions = array();
             if ($this->_single) {
                 $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 (!$ids['contribution']) {
                 require_once 'CRM/Event/DAO/ParticipantPayment.php';
                 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();
                 }
             }
         }
     }
     // also store lineitem stuff here
     if ($this->_lineItem) {
         require_once 'CRM/Price/BAO/LineItem.php';
         foreach ($this->_contactIds as $num => $contactID) {
             foreach ($this->_lineItem as $key => $value) {
                 if (is_array($value) && $value != 'skip') {
                     foreach ($value as $line) {
                         $line['entity_table'] = 'civicrm_participant';
                         $line['entity_id'] = $participants[$num]->id;
                         CRM_Price_BAO_LineItem::create($line);
                     }
                 }
             }
         }
     }
     $updateStatusMsg = null;
     //send mail when participant status changed, CRM-4326
     if ($this->_participantId && $this->_statusId && $this->_statusId != CRM_Utils_Array::value('status_id', $params) && CRM_Utils_Array::value('is_notify', $params)) {
         require_once "CRM/Event/BAO/Participant.php";
         $updateStatusMsg = CRM_Event_BAO_Participant::updateStatusMessage($this->_participantId, $params['status_id'], $this->_statusId);
     }
     if (CRM_Utils_Array::value('send_receipt', $params)) {
         $receiptFrom = "{$userName} <{$userEmail}>";
         $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();
         $event['participant_role'] = $role[$params['role_id']];
         $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');
             require_once 'CRM/Core/BAO/Location.php';
             $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) {
                 $this->assign('paidBy', CRM_Utils_Array::value($params['payment_instrument_id'], $paymentInstrument));
             }
             $this->assign('totalAmount', $contributionParams['total_amount']);
             $this->assign('isPrimary', 1);
             $this->assign('checkNumber', CRM_Utils_Array::value('check_number', $params));
         }
         if ($this->_mode) {
             if (CRM_Utils_Array::value('billing_first_name', $params)) {
                 $name = $params['billing_first_name'];
             }
             if (CRM_Utils_Array::value('billing_middle_name', $params)) {
                 $name .= " {$params['billing_middle_name']}";
             }
             if (CRM_Utils_Array::value('billing_last_name', $params)) {
                 $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];
                 }
             }
             require_once 'CRM/Utils/Address.php';
             $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']);
             $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 (CRM_Utils_Array::value('is_test', $this->_defaultValues)) {
             $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) {
                 $customValue = array('data' => $fieldValue['value']);
                 $customFields[$fieldID]['id'] = $fieldID;
                 $formattedValue = CRM_Core_BAO_CustomGroup::formatCustomValues($customValue, $customFields[$fieldID]);
                 $customGroup[$customFields[$fieldID]['groupTitle']][$customFields[$fieldID]['label']] = str_replace('&nbsp;', '', $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;
             $this->assign('customGroup', $customGroup);
             $this->assign('contactID', $contactID);
             $this->assign('participantID', $participants[$num]->id);
             if ($this->_isPaidEvent) {
                 // fix amount for each of participants ( for bulk mode )
                 $eventAmount = array();
                 $eventAmount[$num] = array('label' => $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.
                 $this->assign('amount', $eventAmount);
             }
             $sendTemplateParams = array('groupName' => 'msg_tpl_workflow_event', 'valueName' => 'event_offline_receipt', 'contactId' => $contactID, 'isTest' => (bool) CRM_Utils_Array::value('is_test', $this->_defaultValues));
             // 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;
             }
             require_once 'CRM/Core/BAO/MessageTemplates.php';
             list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplates::sendTemplate($sendTemplateParams);
             if ($mailSent) {
                 $sent[] = $contactID;
             } else {
                 $notSent[] = $contactID;
             }
         }
     }
     if ($this->_action & CRM_Core_Action::UPDATE) {
         $statusMsg = ts('Event registration information for %1 has been updated.', array(1 => $this->_contributorDisplayName));
         if ($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 (CRM_Utils_Array::value('send_receipt', $params) && 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 - 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');
             }
         }
     }
     require_once "CRM/Core/Session.php";
     CRM_Core_Session::setStatus("{$statusMsg}");
     $buttonName = $this->controller->getButtonName();
     if ($this->_context == 'standalone') {
         if ($buttonName == $this->getButtonName('upload', 'new')) {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/participant/add', 'reset=1&action=add&context=standalone'));
         } else {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$this->_contactID}&selectedChild=participant"));
         }
     } else {
         if ($buttonName == $this->getButtonName('upload', 'new')) {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/participant', "reset=1&action=add&context=participant&cid={$this->_contactID}"));
         }
     }
 }
Example #21
0
 /**
  * Gather values for contribution mail - this function has been created
  * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
  * Values related to the contribution in question are gathered
  *
  * @param array $input
  *   Input into function (probably from payment processor).
  * @param array $values
  * @param array $ids
  *   The set of ids related to the input.
  *
  * @return array
  */
 public function _gatherMessageValues($input, &$values, $ids = array())
 {
     // set display address of contributor
     if ($this->address_id) {
         $addressParams = array('id' => $this->address_id);
         $addressDetails = CRM_Core_BAO_Address::getValues($addressParams, FALSE, 'id');
         $addressDetails = array_values($addressDetails);
         $values['address'] = $addressDetails[0]['display'];
     }
     if ($this->_component == 'contribute') {
         if (isset($this->contribution_page_id)) {
             CRM_Contribute_BAO_ContributionPage::setValues($this->contribution_page_id, $values);
             if ($this->contribution_page_id) {
                 // CRM-8254 - override default currency if applicable
                 $config = CRM_Core_Config::singleton();
                 $config->defaultCurrency = CRM_Utils_Array::value('currency', $values, $config->defaultCurrency);
             }
         } else {
             // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
             $values['is_email_receipt'] = 1;
             $values['title'] = 'Contribution';
         }
         // set lineItem for contribution
         if ($this->id) {
             $lineItem = CRM_Price_BAO_LineItem::getLineItems($this->id, 'contribution', 1);
             if (!empty($lineItem)) {
                 $itemId = key($lineItem);
                 foreach ($lineItem as &$eachItem) {
                     if (is_array($this->_relatedObjects['membership']) && array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects['membership'])) {
                         $eachItem['join_date'] = CRM_Utils_Date::customFormat($this->_relatedObjects['membership'][$eachItem['membership_type_id']]->join_date);
                         $eachItem['start_date'] = CRM_Utils_Date::customFormat($this->_relatedObjects['membership'][$eachItem['membership_type_id']]->start_date);
                         $eachItem['end_date'] = CRM_Utils_Date::customFormat($this->_relatedObjects['membership'][$eachItem['membership_type_id']]->end_date);
                     }
                 }
                 $values['lineItem'][0] = $lineItem;
                 $values['priceSetID'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $lineItem[$itemId]['price_field_id'], 'price_set_id');
             }
         }
         $relatedContact = CRM_Contribute_BAO_Contribution::getOnbehalfIds($this->id, $this->contact_id);
         // if this is onbehalf of contribution then set related contact
         if (!empty($relatedContact['individual_id'])) {
             $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
         }
     } else {
         // event
         $eventParams = array('id' => $this->_relatedObjects['event']->id);
         $values['event'] = array();
         CRM_Event_BAO_Event::retrieve($eventParams, $values['event']);
         // add custom fields for event
         $eventGroupTree = CRM_Core_BAO_CustomGroup::getTree('Event', $this->_relatedObjects['event'], $this->_relatedObjects['event']->id);
         $eventCustomGroup = array();
         foreach ($eventGroupTree as $key => $group) {
             if ($key === 'info') {
                 continue;
             }
             foreach ($group['fields'] as $k => $customField) {
                 $groupLabel = $group['title'];
                 if (!empty($customField['customValue'])) {
                     foreach ($customField['customValue'] as $customFieldValues) {
                         $eventCustomGroup[$groupLabel][$customField['label']] = CRM_Utils_Array::value('data', $customFieldValues);
                     }
                 }
             }
         }
         $values['event']['customGroup'] = $eventCustomGroup;
         //get participant details
         $participantParams = array('id' => $this->_relatedObjects['participant']->id);
         $values['participant'] = array();
         CRM_Event_BAO_Participant::getValues($participantParams, $values['participant'], $participantIds);
         // add custom fields for event
         $participantGroupTree = CRM_Core_BAO_CustomGroup::getTree('Participant', $this->_relatedObjects['participant'], $this->_relatedObjects['participant']->id);
         $participantCustomGroup = array();
         foreach ($participantGroupTree as $key => $group) {
             if ($key === 'info') {
                 continue;
             }
             foreach ($group['fields'] as $k => $customField) {
                 $groupLabel = $group['title'];
                 if (!empty($customField['customValue'])) {
                     foreach ($customField['customValue'] as $customFieldValues) {
                         $participantCustomGroup[$groupLabel][$customField['label']] = CRM_Utils_Array::value('data', $customFieldValues);
                     }
                 }
             }
         }
         $values['participant']['customGroup'] = $participantCustomGroup;
         //get location details
         $locationParams = array('entity_id' => $this->_relatedObjects['event']->id, 'entity_table' => 'civicrm_event');
         $values['location'] = CRM_Core_BAO_Location::getValues($locationParams);
         $ufJoinParams = array('entity_table' => 'civicrm_event', 'entity_id' => $ids['event'], 'module' => 'CiviEvent');
         list($custom_pre_id, $custom_post_ids) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
         $values['custom_pre_id'] = $custom_pre_id;
         $values['custom_post_id'] = $custom_post_ids;
         // set lineItem for event contribution
         if ($this->id) {
             $participantIds = CRM_Event_BAO_Participant::getParticipantIds($this->id);
             if (!empty($participantIds)) {
                 foreach ($participantIds as $pIDs) {
                     $lineItem = CRM_Price_BAO_LineItem::getLineItems($pIDs);
                     if (!CRM_Utils_System::isNull($lineItem)) {
                         $values['lineItem'][] = $lineItem;
                     }
                 }
             }
         }
     }
     $groupTree = CRM_Core_BAO_CustomGroup::getTree('Contribution', $this, $this->id);
     $customGroup = array();
     foreach ($groupTree as $key => $group) {
         if ($key === 'info') {
             continue;
         }
         foreach ($group['fields'] as $k => $customField) {
             $groupLabel = $group['title'];
             if (!empty($customField['customValue'])) {
                 foreach ($customField['customValue'] as $customFieldValues) {
                     $customGroup[$groupLabel][$customField['label']] = CRM_Utils_Array::value('data', $customFieldValues);
                 }
             }
         }
     }
     $values['customGroup'] = $customGroup;
     return $values;
 }
 /**
  * Process the PDf and email with activity and attachment.
  * on click of Print Invoices
  *
  * @param array $contribIDs
  *   Contribution Id.
  * @param array $params
  *   Associated array of submitted values.
  * @param array $contactIds
  *   Contact Id.
  * @param CRM_Core_Form $form
  *   Form object.
  */
 public static function printPDF($contribIDs, &$params, $contactIds, &$form)
 {
     // get all the details needed to generate a invoice
     $messageInvoice = array();
     $invoiceTemplate = CRM_Core_Smarty::singleton();
     $invoiceElements = CRM_Contribute_Form_Task_PDF::getElements($contribIDs, $params, $contactIds);
     // gives the status id when contribution status is 'Refunded'
     $contributionStatusID = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
     $refundedStatusId = CRM_Utils_Array::key('Refunded', $contributionStatusID);
     // getting data from admin page
     $prefixValue = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings');
     foreach ($invoiceElements['details'] as $contribID => $detail) {
         $input = $ids = $objects = array();
         if (in_array($detail['contact'], $invoiceElements['excludeContactIds'])) {
             continue;
         }
         $input['component'] = $detail['component'];
         $ids['contact'] = $detail['contact'];
         $ids['contribution'] = $contribID;
         $ids['contributionRecur'] = NULL;
         $ids['contributionPage'] = NULL;
         $ids['membership'] = CRM_Utils_Array::value('membership', $detail);
         $ids['participant'] = CRM_Utils_Array::value('participant', $detail);
         $ids['event'] = CRM_Utils_Array::value('event', $detail);
         if (!$invoiceElements['baseIPN']->validateData($input, $ids, $objects, FALSE)) {
             CRM_Core_Error::fatal();
         }
         $contribution =& $objects['contribution'];
         $input['amount'] = $contribution->total_amount;
         $input['invoice_id'] = $contribution->invoice_id;
         $input['receive_date'] = $contribution->receive_date;
         $input['contribution_status_id'] = $contribution->contribution_status_id;
         $input['organization_name'] = $contribution->_relatedObjects['contact']->organization_name;
         $objects['contribution']->receive_date = CRM_Utils_Date::isoToMysql($objects['contribution']->receive_date);
         $addressParams = array('contact_id' => $contribution->contact_id);
         $addressDetails = CRM_Core_BAO_Address::getValues($addressParams);
         // to get billing address if present
         $billingAddress = array();
         foreach ($addressDetails as $key => $address) {
             if (isset($address['is_billing']) && $address['is_billing'] == 1 && (isset($address['is_primary']) && $address['is_primary'] == 1) && $address['contact_id'] == $contribution->contact_id) {
                 $billingAddress[$address['contact_id']] = $address;
                 break;
             } elseif ($address['is_billing'] == 0 && $address['is_primary'] == 1 || isset($address['is_billing']) && $address['is_billing'] == 1 && $address['contact_id'] == $contribution->contact_id) {
                 $billingAddress[$address['contact_id']] = $address;
             }
         }
         if (!empty($billingAddress[$contribution->contact_id]['state_province_id'])) {
             $stateProvinceAbbreviation = CRM_Core_PseudoConstant::stateProvinceAbbreviation($billingAddress[$contribution->contact_id]['state_province_id']);
         } else {
             $stateProvinceAbbreviation = '';
         }
         if ($contribution->contribution_status_id == $refundedStatusId) {
             $creditNoteId = CRM_Utils_Array::value('credit_notes_prefix', $prefixValue) . "" . $contribution->id;
         }
         $invoiceId = CRM_Utils_Array::value('invoice_prefix', $prefixValue) . "" . $contribution->id;
         //to obtain due date for PDF invoice
         $contributionReceiveDate = date('F j,Y', strtotime(date($input['receive_date'])));
         $invoiceDate = date("F j, Y");
         $dueDate = date('F j ,Y', strtotime($contributionReceiveDate . "+" . $prefixValue['due_date'] . "" . $prefixValue['due_date_period']));
         if ($input['component'] == 'contribute') {
             $eid = $contribID;
             $etable = 'contribution';
             $lineItem = CRM_Price_BAO_LineItem::getLineItems($eid, $etable, NULL, TRUE, TRUE);
         } else {
             $eid = $contribution->_relatedObjects['participant']->id;
             $etable = 'participant';
             $lineItem = CRM_Price_BAO_LineItem::getLineItems($eid, $etable);
         }
         //TO DO: Need to do changes for partially paid to display amount due on PDF invoice
         $amountDue = $input['amount'] - $input['amount'];
         // retreiving the subtotal and sum of same tax_rate
         $dataArray = array();
         $subTotal = 0;
         foreach ($lineItem as $entity_id => $taxRate) {
             if (isset($dataArray[(string) $taxRate['tax_rate']])) {
                 $dataArray[(string) $taxRate['tax_rate']] = $dataArray[(string) $taxRate['tax_rate']] + CRM_Utils_Array::value('tax_amount', $taxRate);
             } else {
                 $dataArray[(string) $taxRate['tax_rate']] = CRM_Utils_Array::value('tax_amount', $taxRate);
             }
             $subTotal += CRM_Utils_Array::value('subTotal', $taxRate);
         }
         // to email the invoice
         $mailDetails = array();
         $values = array();
         if ($contribution->_component == 'event') {
             $daoName = 'CRM_Event_DAO_Event';
             $pageId = $contribution->_relatedObjects['event']->id;
             $mailElements = array('title', 'confirm_from_name', 'confirm_from_email', 'cc_confirm', 'bcc_confirm');
             CRM_Core_DAO::commonRetrieveAll($daoName, 'id', $pageId, $mailDetails, $mailElements);
             $values['title'] = CRM_Utils_Array::value('title', $mailDetails[$contribution->_relatedObjects['event']->id]);
             $values['confirm_from_name'] = CRM_Utils_Array::value('confirm_from_name', $mailDetails[$contribution->_relatedObjects['event']->id]);
             $values['confirm_from_email'] = CRM_Utils_Array::value('confirm_from_email', $mailDetails[$contribution->_relatedObjects['event']->id]);
             $values['cc_confirm'] = CRM_Utils_Array::value('cc_confirm', $mailDetails[$contribution->_relatedObjects['event']->id]);
             $values['bcc_confirm'] = CRM_Utils_Array::value('bcc_confirm', $mailDetails[$contribution->_relatedObjects['event']->id]);
             $title = CRM_Utils_Array::value('title', $mailDetails[$contribution->_relatedObjects['event']->id]);
         } elseif ($contribution->_component == 'contribute') {
             $daoName = 'CRM_Contribute_DAO_ContributionPage';
             $pageId = $contribution->contribution_page_id;
             $mailElements = array('title', 'receipt_from_name', 'receipt_from_email', 'cc_receipt', 'bcc_receipt');
             CRM_Core_DAO::commonRetrieveAll($daoName, 'id', $pageId, $mailDetails, $mailElements);
             $values['title'] = CRM_Utils_Array::value('title', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
             $values['receipt_from_name'] = CRM_Utils_Array::value('receipt_from_name', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
             $values['receipt_from_email'] = CRM_Utils_Array::value('receipt_from_email', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
             $values['cc_receipt'] = CRM_Utils_Array::value('cc_receipt', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
             $values['bcc_receipt'] = CRM_Utils_Array::value('bcc_receipt', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
             $title = CRM_Utils_Array::value('title', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
         }
         $source = $contribution->source;
         $config = CRM_Core_Config::singleton();
         if (!isset($params['forPage'])) {
             $config->doNotAttachPDFReceipt = 1;
         }
         // get organization address
         $domain = CRM_Core_BAO_Domain::getDomain();
         $locParams = array('contact_id' => $domain->id);
         $locationDefaults = CRM_Core_BAO_Location::getValues($locParams);
         if (isset($locationDefaults['address'][1]['state_province_id'])) {
             $stateProvinceAbbreviationDomain = CRM_Core_PseudoConstant::stateProvinceAbbreviation($locationDefaults['address'][1]['state_province_id']);
         } else {
             $stateProvinceAbbreviationDomain = '';
         }
         if (isset($locationDefaults['address'][1]['country_id'])) {
             $countryDomain = CRM_Core_PseudoConstant::country($locationDefaults['address'][1]['country_id']);
         } else {
             $countryDomain = '';
         }
         // parameters to be assign for template
         $tplParams = array('title' => $title, 'component' => $input['component'], 'id' => $contribution->id, 'source' => $source, 'invoice_id' => $invoiceId, 'resourceBase' => $config->userFrameworkResourceURL, 'defaultCurrency' => $config->defaultCurrency, 'amount' => $contribution->total_amount, 'amountDue' => $amountDue, 'invoice_date' => $invoiceDate, 'dueDate' => $dueDate, 'notes' => CRM_Utils_Array::value('notes', $prefixValue), 'display_name' => $contribution->_relatedObjects['contact']->display_name, 'lineItem' => $lineItem, 'dataArray' => $dataArray, 'refundedStatusId' => $refundedStatusId, 'contribution_status_id' => $contribution->contribution_status_id, 'subTotal' => $subTotal, 'street_address' => CRM_Utils_Array::value('street_address', CRM_Utils_Array::value($contribution->contact_id, $billingAddress)), 'supplemental_address_1' => CRM_Utils_Array::value('supplemental_address_1', CRM_Utils_Array::value($contribution->contact_id, $billingAddress)), 'supplemental_address_2' => CRM_Utils_Array::value('supplemental_address_2', CRM_Utils_Array::value($contribution->contact_id, $billingAddress)), 'city' => CRM_Utils_Array::value('city', CRM_Utils_Array::value($contribution->contact_id, $billingAddress)), 'stateProvinceAbbreviation' => $stateProvinceAbbreviation, 'postal_code' => CRM_Utils_Array::value('postal_code', CRM_Utils_Array::value($contribution->contact_id, $billingAddress)), 'is_pay_later' => $contribution->is_pay_later, 'organization_name' => $contribution->_relatedObjects['contact']->organization_name, 'domain_organization' => $domain->name, 'domain_street_address' => CRM_Utils_Array::value('street_address', CRM_Utils_Array::value('1', $locationDefaults['address'])), 'domain_supplemental_address_1' => CRM_Utils_Array::value('supplemental_address_1', CRM_Utils_Array::value('1', $locationDefaults['address'])), 'domain_supplemental_address_2' => CRM_Utils_Array::value('supplemental_address_2', CRM_Utils_Array::value('1', $locationDefaults['address'])), 'domain_city' => CRM_Utils_Array::value('city', CRM_Utils_Array::value('1', $locationDefaults['address'])), 'domain_postal_code' => CRM_Utils_Array::value('postal_code', CRM_Utils_Array::value('1', $locationDefaults['address'])), 'domain_state' => $stateProvinceAbbreviationDomain, 'domain_country' => $countryDomain, 'domain_email' => CRM_Utils_Array::value('email', CRM_Utils_Array::value('1', $locationDefaults['email'])), 'domain_phone' => CRM_Utils_Array::value('phone', CRM_Utils_Array::value('1', $locationDefaults['phone'])));
         if (isset($creditNoteId)) {
             $tplParams['creditnote_id'] = $creditNoteId;
         }
         $sendTemplateParams = array('groupName' => 'msg_tpl_workflow_contribution', 'valueName' => 'contribution_invoice_receipt', 'contactId' => $contribution->contact_id, 'tplParams' => $tplParams, 'PDFFilename' => 'Invoice.pdf');
         $session = CRM_Core_Session::singleton();
         $contactID = $session->get('userID');
         //CRM-16319 - we dont store in userID in case the user is doing multiple
         //transactions etc
         if (empty($contactID)) {
             $contactID = $session->get('transaction.userID');
         }
         $contactEmails = CRM_Core_BAO_Email::allEmails($contactID);
         $emails = array();
         $fromDisplayName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'display_name');
         foreach ($contactEmails as $emailId => $item) {
             $email = $item['email'];
             if ($email) {
                 $emails[$emailId] = '"' . $fromDisplayName . '" <' . $email . '> ';
             }
         }
         $fromEmail = CRM_Utils_Array::crmArrayMerge($emails, CRM_Core_OptionGroup::values('from_email_address'));
         // from email address
         if (isset($params['from_email_address'])) {
             $fromEmailAddress = CRM_Utils_Array::value($params['from_email_address'], $fromEmail);
         }
         // condition to check for download PDF Invoice or email Invoice
         if ($invoiceElements['createPdf']) {
             list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
             if (isset($params['forPage'])) {
                 return $html;
             } else {
                 $mail = array('subject' => $subject, 'body' => $message, 'html' => $html);
                 if ($mail['html']) {
                     $messageInvoice[] = $mail['html'];
                 } else {
                     $messageInvoice[] = nl2br($mail['body']);
                 }
             }
         } elseif ($contribution->_component == 'contribute') {
             $email = CRM_Contact_BAO_Contact::getPrimaryEmail($contribution->contact_id);
             $sendTemplateParams['tplParams'] = array_merge($tplParams, array('email_comment' => $invoiceElements['params']['email_comment']));
             $sendTemplateParams['from'] = $fromEmailAddress;
             $sendTemplateParams['toEmail'] = $email;
             $sendTemplateParams['cc'] = CRM_Utils_Array::value('cc_receipt', $values);
             $sendTemplateParams['bcc'] = CRM_Utils_Array::value('bcc_receipt', $values);
             list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
             // functions call for adding activity with attachment
             $fileName = self::putFile($html);
             self::addActivities($subject, $contribution->contact_id, $fileName, $params);
         } elseif ($contribution->_component == 'event') {
             $email = CRM_Contact_BAO_Contact::getPrimaryEmail($contribution->contact_id);
             $sendTemplateParams['tplParams'] = array_merge($tplParams, array('email_comment' => $invoiceElements['params']['email_comment']));
             $sendTemplateParams['from'] = $fromEmailAddress;
             $sendTemplateParams['toEmail'] = $email;
             $sendTemplateParams['cc'] = CRM_Utils_Array::value('cc_confirm', $values);
             $sendTemplateParams['bcc'] = CRM_Utils_Array::value('bcc_confirm', $values);
             list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
             // functions call for adding activity with attachment
             $fileName = self::putFile($html);
             self::addActivities($subject, $contribution->contact_id, $fileName, $params);
         }
         CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_Contribution', $contribution->id, 'invoice_id', $invoiceId);
         if ($contribution->contribution_status_id == $refundedStatusId) {
             CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_Contribution', $contribution->id, 'creditnote_id', $creditNoteId);
         }
         $invoiceTemplate->clearTemplateVars();
     }
     if ($invoiceElements['createPdf']) {
         if (isset($params['forPage'])) {
             return $html;
         } else {
             CRM_Utils_PDF_Utils::html2pdf($messageInvoice, 'Invoice.pdf', FALSE, array('margin_top' => 10, 'margin_left' => 65, 'metric' => 'px'));
             // functions call for adding activity with attachment
             $fileName = self::putFile($html);
             self::addActivities($subject, $contactIds, $fileName, $params);
             CRM_Utils_System::civiExit();
         }
     } else {
         if ($invoiceElements['suppressedEmails']) {
             $status = ts('Email was NOT sent to %1 contacts (no email address on file, or communication preferences specify DO NOT EMAIL, or contact is deceased).', array(1 => $invoiceElements['suppressedEmails']));
             $msgTitle = ts('Email Error');
             $msgType = 'error';
         } else {
             $status = ts('Your mail has been sent.');
             $msgTitle = ts('Sent');
             $msgType = 'success';
         }
         CRM_Core_Session::setStatus($status, $msgTitle, $msgType);
     }
 }
Example #23
0
 /**
  * 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('&nbsp;', '', $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}"));
     }
 }
Example #24
0
 function getLocBlock()
 {
     // i wish i could retrieve loc block info based on loc_block_id,
     // Anyway, lets retrieve an event which has loc_block_id set to 'lbid'.
     if ($_POST['lbid']) {
         $params = array('1' => array($_POST['lbid'], 'Integer'));
         $eventId = CRM_Core_DAO::singleValueQuery('SELECT id FROM civicrm_event WHERE loc_block_id=%1 LIMIT 1', $params);
     }
     // now lets use the event-id obtained above, to retrieve loc block information.
     if ($eventId) {
         $params = array('entity_id' => $eventId, 'entity_table' => 'civicrm_event');
         require_once 'CRM/Core/BAO/Location.php';
         // second parameter is of no use, but since required, lets use the same variable.
         $location = CRM_Core_BAO_Location::getValues($params, $params);
     }
     $result = array();
     require_once 'CRM/Core/BAO/Preferences.php';
     $addressOptions = CRM_Core_BAO_Preferences::valueOptions('address_options', true, null, true);
     // lets output only required fields.
     foreach ($addressOptions as $element => $isSet) {
         if ($isSet && !in_array($element, array('im', 'openid'))) {
             if (in_array($element, array('country', 'state_province', 'county'))) {
                 $element .= '_id';
             } else {
                 if ($element == 'address_name') {
                     $element = 'name';
                 }
             }
             $fld = "address[1][{$element}]";
             $value = CRM_Utils_Array::value($element, $location['address'][1]);
             $value = $value ? $value : "";
             $result[str_replace(array('][', '[', "]"), array('_', '_', ''), $fld)] = $value;
         }
     }
     foreach (array('email', 'phone_type_id', 'phone') as $element) {
         $block = $element == 'phone_type_id' ? 'phone' : $element;
         for ($i = 1; $i < 3; $i++) {
             $fld = "{$block}[{$i}][{$element}]";
             $value = CRM_Utils_Array::value($element, $location[$block][$i]);
             $value = $value ? $value : "";
             $result[str_replace(array('][', '[', "]"), array('_', '_', ''), $fld)] = $value;
         }
     }
     // set the message if loc block is being used by more than one event.
     require_once 'CRM/Event/BAO/Event.php';
     $result['count_loc_used'] = CRM_Event_BAO_Event::countEventsUsingLocBlockId($_POST['lbid']);
     echo json_encode($result);
     exit;
 }
Example #25
0
 /**
  * Form submission of new/edit contact is processed.
  *
  * @access public
  * @return None
  */
 public function postProcess()
 {
     // check if dedupe button, if so return.
     $buttonName = $this->controller->getButtonName();
     if ($buttonName == $this->_dedupeButtonName) {
         return;
     }
     //get the submitted values in an array
     $params = $this->controller->exportValues($this->_name);
     //get the related id for shared / current employer
     if (CRM_Utils_Array::value('shared_household_id', $params)) {
         $params['shared_household'] = $params['shared_household_id'];
     }
     if (is_numeric(CRM_Utils_Array::value('current_employer_id', $params)) && CRM_Utils_Array::value('current_employer', $params)) {
         $params['current_employer'] = $params['current_employer_id'];
     }
     // don't carry current_employer_id field,
     // since we don't want to directly update DAO object without
     // handling related business logic ( eg related membership )
     if (isset($params['current_employer_id'])) {
         unset($params['current_employer_id']);
     }
     $params['contact_type'] = $this->_contactType;
     if ($this->_contactId) {
         $params['contact_id'] = $this->_contactId;
     }
     //make deceased date null when is_deceased = false
     if ($this->_contactType == 'Individual' && CRM_Utils_Array::value('Demographics', $this->_editOptions) && !CRM_Utils_Array::value('is_deceased', $params)) {
         $params['is_deceased'] = false;
         $params['deceased_date'] = null;
     }
     if ($this->_contactSubType && $this->_action & CRM_Core_Action::ADD) {
         $params['contact_sub_type'] = $this->_contactSubType;
     }
     // action is taken depending upon the mode
     require_once 'CRM/Utils/Hook.php';
     if ($this->_action & CRM_Core_Action::UPDATE) {
         CRM_Utils_Hook::pre('edit', $params['contact_type'], $params['contact_id'], $params);
     } else {
         CRM_Utils_Hook::pre('create', $params['contact_type'], null, $params);
     }
     require_once 'CRM/Core/BAO/CustomField.php';
     $customFields = CRM_Core_BAO_CustomField::getFields($params['contact_type'], false, true);
     $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $customFields, $this->_contactId, $params['contact_type'], true);
     if (array_key_exists('CommunicationPreferences', $this->_editOptions)) {
         // this is a chekbox, so mark false if we dont get a POST value
         $params['is_opt_out'] = CRM_Utils_Array::value('is_opt_out', $params, false);
     }
     // copy household address, if use_household_address option (for individual form) is checked
     if ($this->_contactType == 'Individual') {
         if (CRM_Utils_Array::value('use_household_address', $params) && CRM_Utils_Array::value('shared_household', $params)) {
             if (is_numeric($params['shared_household'])) {
                 CRM_Contact_Form_Edit_Individual::copyHouseholdAddress($params);
             }
             CRM_Contact_Form_Edit_Individual::createSharedHousehold($params);
         } else {
             $params['mail_to_household_id'] = 'null';
         }
     } else {
         $params['mail_to_household_id'] = 'null';
     }
     if (!array_key_exists('TagsAndGroups', $this->_editOptions)) {
         unset($params['group']);
     }
     if (CRM_Utils_Array::value('contact_id', $params) && $this->_action & CRM_Core_Action::UPDATE) {
         // cleanup unwanted location blocks
         require_once 'CRM/Core/BAO/Location.php';
         CRM_Core_BAO_Location::cleanupContactLocations($params);
         // figure out which all groups are intended to be removed
         if (!empty($params['group'])) {
             $contactGroupList =& CRM_Contact_BAO_GroupContact::getContactGroup($params['contact_id'], 'Added');
             if (is_array($contactGroupList)) {
                 foreach ($contactGroupList as $key) {
                     if ($params['group'][$key['group_id']] != 1) {
                         $params['group'][$key['group_id']] = -1;
                     }
                 }
             }
         }
     }
     require_once 'CRM/Contact/BAO/Contact.php';
     $contact =& CRM_Contact_BAO_Contact::create($params, true, false);
     if ($this->_contactType == 'Individual' && CRM_Utils_Array::value('use_household_address', $params) && CRM_Utils_Array::value('mail_to_household_id', $params)) {
         // add/edit/delete the relation of individual with household, if use-household-address option is checked/unchecked.
         CRM_Contact_Form_Edit_Individual::handleSharedRelation($contact->id, $params);
     }
     if ($this->_contactType == 'Household' && $this->_action & CRM_Core_Action::UPDATE) {
         //TO DO: commented because of schema changes
         require_once 'CRM/Contact/Form/Edit/Household.php';
         CRM_Contact_Form_Edit_Household::synchronizeIndividualAddresses($contact->id);
     }
     if (array_key_exists('TagsAndGroups', $this->_editOptions)) {
         //add contact to tags
         require_once 'CRM/Core/BAO/EntityTag.php';
         CRM_Core_BAO_EntityTag::create($params['tag'], $params['contact_id']);
     }
     // here we replace the user context with the url to view this contact
     $session =& CRM_Core_Session::singleton();
     CRM_Core_Session::setStatus(ts('Your %1 contact record has been saved.', array(1 => $contact->contact_type_display)));
     $buttonName = $this->controller->getButtonName();
     if ($buttonName == $this->getButtonName('next', 'new') || $buttonName == $this->getButtonName('upload', 'new')) {
         require_once 'CRM/Utils/Recent.php';
         // add the recently viewed contact
         $displayName = CRM_Contact_BAO_Contact::displayName($contact->id);
         CRM_Utils_Recent::add($displayName, CRM_Utils_System::url('civicrm/contact/view', 'reset=1&cid=' . $contact->id), $contact->id, $this->_contactType, $contact->id, $displayName);
         $resetStr = "reset=1&ct={$contact->contact_type}";
         $resetStr .= $this->_contactSubType ? "&cst={$this->_contactSubType}" : '';
         $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/add', $resetStr));
     } else {
         $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view', 'reset=1&cid=' . $contact->id));
     }
     // now invoke the post hook
     if ($this->_action & CRM_Core_Action::UPDATE) {
         CRM_Utils_Hook::post('edit', $params['contact_type'], $contact->id, $contact);
     } else {
         CRM_Utils_Hook::post('create', $params['contact_type'], $contact->id, $contact);
     }
 }
 /**
  * Return the primary location type of a contact.
  *
  * $params int     $contactId contact_id
  * $params boolean $isPrimaryExist if true, return primary contact location type otherwise null
  * $params boolean $skipDefaultPriamry if true, return primary contact location type otherwise null
  *
  * @param int $contactId
  * @param bool $skipDefaultPriamry
  * @param null $block
  *
  * @return int
  *   $locationType location_type_id
  */
 public static function getPrimaryLocationType($contactId, $skipDefaultPriamry = FALSE, $block = NULL)
 {
     if ($block) {
         $entityBlock = array('contact_id' => $contactId);
         $blocks = CRM_Core_BAO_Location::getValues($entityBlock);
         foreach ($blocks[$block] as $key => $value) {
             if (!empty($value['is_primary'])) {
                 $locationType = CRM_Utils_Array::value('location_type_id', $value);
             }
         }
     } else {
         $query = "\nSELECT\n IF ( civicrm_email.location_type_id IS NULL,\n    IF ( civicrm_address.location_type_id IS NULL,\n        IF ( civicrm_phone.location_type_id IS NULL,\n           IF ( civicrm_im.location_type_id IS NULL,\n               IF ( civicrm_openid.location_type_id IS NULL, null, civicrm_openid.location_type_id)\n           ,civicrm_im.location_type_id)\n        ,civicrm_phone.location_type_id)\n     ,civicrm_address.location_type_id)\n  ,civicrm_email.location_type_id)  as locationType\nFROM civicrm_contact\n     LEFT JOIN civicrm_email   ON ( civicrm_email.is_primary   = 1 AND civicrm_email.contact_id = civicrm_contact.id )\n     LEFT JOIN civicrm_address ON ( civicrm_address.is_primary = 1 AND civicrm_address.contact_id = civicrm_contact.id)\n     LEFT JOIN civicrm_phone   ON ( civicrm_phone.is_primary   = 1 AND civicrm_phone.contact_id = civicrm_contact.id)\n     LEFT JOIN civicrm_im      ON ( civicrm_im.is_primary      = 1 AND civicrm_im.contact_id = civicrm_contact.id)\n     LEFT JOIN civicrm_openid  ON ( civicrm_openid.is_primary  = 1 AND civicrm_openid.contact_id = civicrm_contact.id)\nWHERE  civicrm_contact.id = %1 ";
         $params = array(1 => array($contactId, 'Integer'));
         $dao = CRM_Core_DAO::executeQuery($query, $params);
         $locationType = NULL;
         if ($dao->fetch()) {
             $locationType = $dao->locationType;
         }
     }
     if (isset($locationType)) {
         return $locationType;
     } elseif ($skipDefaultPriamry) {
         // if there is no primary contact location then return null
         return NULL;
     } else {
         // if there is no primart contact location, then return default
         // location type of the system
         $defaultLocationType = CRM_Core_BAO_LocationType::getDefault();
         return $defaultLocationType->id;
     }
 }
Example #27
0
 /**
  * GetValues() method
  * get the values of various location elements
  */
 public function testLocBlockgetValues()
 {
     $contactId = $this->individualCreate();
     //create various element of location block
     //like address, phone, email, openid, im.
     $params = array('address' => array('1' => array('street_address' => 'Saint Helier St', 'supplemental_address_1' => 'Hallmark Ct', 'supplemental_address_2' => 'Jersey Village', 'city' => 'Newark', 'postal_code' => '01903', 'country_id' => 1228, 'state_province_id' => 1029, 'geo_code_1' => '18.219023', 'geo_code_2' => '-105.00973', 'is_primary' => 1, 'location_type_id' => 1)), 'email' => array('1' => array('email' => '*****@*****.**', 'is_primary' => 1, 'location_type_id' => 1)), 'phone' => array('1' => array('phone_type_id' => 1, 'phone' => '303443689', 'is_primary' => 1, 'location_type_id' => 1), '2' => array('phone_type_id' => 2, 'phone' => '9833910234', 'location_type_id' => 1)), 'openid' => array('1' => array('openid' => 'http://civicrm.org/', 'location_type_id' => 1, 'is_primary' => 1)), 'im' => array('1' => array('name' => 'jane.doe', 'provider_id' => 1, 'location_type_id' => 1, 'is_primary' => 1)));
     $params['contact_id'] = $contactId;
     //create location elements.
     CRM_Core_BAO_Location::create($params);
     //get the values from DB
     $values = CRM_Core_BAO_Location::getValues($params);
     //Now check values of address
     $this->assertAttributesEquals(CRM_Utils_Array::value('1', $params['address']), CRM_Utils_Array::value('1', $values['address']));
     //Now check values of email
     $this->assertAttributesEquals(CRM_Utils_Array::value('1', $params['email']), CRM_Utils_Array::value('1', $values['email']));
     //Now check values of phone
     $this->assertAttributesEquals(CRM_Utils_Array::value('1', $params['phone']), CRM_Utils_Array::value('1', $values['phone']));
     //Now check values of mobile
     $this->assertAttributesEquals(CRM_Utils_Array::value('2', $params['phone']), CRM_Utils_Array::value('2', $values['phone']));
     //Now check values of openid
     $this->assertAttributesEquals(CRM_Utils_Array::value('1', $params['openid']), CRM_Utils_Array::value('1', $values['openid']));
     //Now check values of im
     $this->assertAttributesEquals(CRM_Utils_Array::value('1', $params['im']), CRM_Utils_Array::value('1', $values['im']));
     $this->contactDelete($contactId);
 }
Example #28
0
 /**
  * browse all events
  * 
  * @return void
  */
 function browse()
 {
     $this->_sortByCharacter = CRM_Utils_Request::retrieve('sortByCharacter', 'String', $this);
     if ($this->_sortByCharacter == 1 || !empty($_POST)) {
         $this->_sortByCharacter = '';
         $this->set('sortByCharacter', '');
     }
     $this->_force = null;
     $this->_searchResult = null;
     $this->search();
     $config =& CRM_Core_Config::singleton();
     $params = array();
     $this->_force = CRM_Utils_Request::retrieve('force', 'Boolean', $this, false);
     $this->_searchResult = CRM_Utils_Request::retrieve('searchResult', 'Boolean', $this);
     $whereClause = $this->whereClause($params, false, $this->_force);
     $this->pagerAToZ($whereClause, $params);
     $params = array();
     $whereClause = $this->whereClause($params, true, $this->_force);
     $whereClause .= ' AND (is_template = 0 OR is_template IS NULL)';
     // because is_template != 1 would be to simple
     $this->pager($whereClause, $params);
     list($offset, $rowCount) = $this->_pager->getOffsetAndRowCount();
     // get all custom groups sorted by weight
     $manageEvent = array();
     $query = "\n  SELECT *\n    FROM civicrm_event\n   WHERE {$whereClause}\nORDER BY start_date desc\n   LIMIT {$offset}, {$rowCount}";
     $dao = CRM_Core_DAO::executeQuery($query, $params, true, 'CRM_Event_DAO_Event');
     $permissions = CRM_Event_BAO_Event::checkPermission();
     while ($dao->fetch()) {
         if (in_array($dao->id, $permissions[CRM_Core_Permission::VIEW])) {
             $manageEvent[$dao->id] = array();
             CRM_Core_DAO::storeValues($dao, $manageEvent[$dao->id]);
             // form all action links
             $action = array_sum(array_keys($this->links()));
             if ($dao->is_active) {
                 $action -= CRM_Core_Action::ENABLE;
             } else {
                 $action -= CRM_Core_Action::DISABLE;
             }
             if (!in_array($dao->id, $permissions[CRM_Core_Permission::DELETE])) {
                 $action -= CRM_Core_Action::DELETE;
             }
             if (!in_array($dao->id, $permissions[CRM_Core_Permission::EDIT])) {
                 $action -= CRM_Core_Action::UPDATE;
             }
             $manageEvent[$dao->id]['action'] = CRM_Core_Action::formLink(self::links(), $action, array('id' => $dao->id));
             $params = array('entity_id' => $dao->id, 'entity_table' => 'civicrm_event');
             require_once 'CRM/Core/BAO/Location.php';
             $defaults['location'] = CRM_Core_BAO_Location::getValues($params, true);
             if (isset($defaults['location']['address'][1]['city'])) {
                 $manageEvent[$dao->id]['city'] = $defaults['location']['address'][1]['city'];
             }
             if (isset($defaults['location']['address'][1]['state_province_id'])) {
                 $manageEvent[$dao->id]['state_province'] = CRM_Core_PseudoConstant::stateProvince($defaults['location']['address'][1]['state_province_id']);
             }
         }
     }
     $this->assign('rows', $manageEvent);
 }
Example #29
0
 /**
  * Set variables up before form is built.
  */
 public function preProcess()
 {
     $this->_eventId = CRM_Utils_Request::retrieve('id', 'Positive', $this, TRUE);
     $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE);
     //CRM-4320
     $this->_participantId = CRM_Utils_Request::retrieve('participantId', 'Positive', $this);
     // 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');
     $this->_lineItem = $this->get('lineItem');
     $this->_isEventFull = $this->get('isEventFull');
     $this->_lineItemParticipantsCount = $this->get('lineItemParticipants');
     if (!is_array($this->_lineItem)) {
         $this->_lineItem = array();
     }
     if (!is_array($this->_lineItemParticipantsCount)) {
         $this->_lineItemParticipantsCount = array();
     }
     $this->_availableRegistrations = $this->get('availableRegistrations');
     $this->_participantIDS = $this->get('participantIDs');
     //check if participant allow to walk registration wizard.
     $this->_allowConfirmation = $this->get('allowConfirmation');
     // check for Approval
     $this->_requireApproval = $this->get('requireApproval');
     // check for waitlisting.
     $this->_allowWaitlist = $this->get('allowWaitlist');
     $this->_forcePayement = $this->get('forcePayement');
     //get the additional participant ids.
     $this->_additionalParticipantIds = $this->get('additionalParticipantIds');
     $config = CRM_Core_Config::singleton();
     if (!$this->_values) {
         // create redirect URL to send folks back to event info page is registration not available
         $infoUrl = CRM_Utils_System::url('civicrm/event/info', "reset=1&id={$this->_eventId}", FALSE, NULL, FALSE, TRUE);
         // this is the first time we are hitting this, so check for permissions here
         if (!CRM_Core_Permission::event(CRM_Core_Permission::EDIT, $this->_eventId, 'register for events')) {
             CRM_Core_Error::statusBounce(ts('You do not have permission to register for this event'), $infoUrl);
         }
         // get all the values from the dao object
         $this->_values = $this->_fields = array();
         $this->_forcePayement = FALSE;
         //retrieve event information
         $params = array('id' => $this->_eventId);
         CRM_Event_BAO_Event::retrieve($params, $this->_values['event']);
         // check for is_monetary status
         $isMonetary = CRM_Utils_Array::value('is_monetary', $this->_values['event']);
         // check for ability to add contributions of type
         if ($isMonetary && CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus() && !CRM_Core_Permission::check('add contributions of type ' . CRM_Contribute_PseudoConstant::financialType($this->_values['event']['financial_type_id']))) {
             CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
         }
         $this->checkValidEvent($infoUrl);
         // get the participant values, CRM-4320
         $this->_allowConfirmation = FALSE;
         if ($this->_participantId) {
             $this->processFirstParticipant($this->_participantId);
         }
         //check for additional participants.
         if ($this->_allowConfirmation && $this->_values['event']['is_multiple_registrations']) {
             $additionalParticipantIds = CRM_Event_BAO_Participant::getAdditionalParticipantIds($this->_participantId);
             $cnt = 1;
             foreach ($additionalParticipantIds as $additionalParticipantId) {
                 $this->_additionalParticipantIds[$cnt] = $additionalParticipantId;
                 $cnt++;
             }
             $this->set('additionalParticipantIds', $this->_additionalParticipantIds);
         }
         $eventFull = CRM_Event_BAO_Participant::eventFull($this->_eventId, FALSE, CRM_Utils_Array::value('has_waitlist', $this->_values['event']));
         $this->_allowWaitlist = $this->_isEventFull = FALSE;
         if ($eventFull && !$this->_allowConfirmation) {
             $this->_isEventFull = TRUE;
             //lets redirecting to info only when to waiting list.
             $this->_allowWaitlist = CRM_Utils_Array::value('has_waitlist', $this->_values['event']);
             if (!$this->_allowWaitlist) {
                 CRM_Utils_System::redirect($infoUrl);
             }
         }
         $this->set('isEventFull', $this->_isEventFull);
         $this->set('allowWaitlist', $this->_allowWaitlist);
         //check for require requires approval.
         $this->_requireApproval = FALSE;
         if (!empty($this->_values['event']['requires_approval']) && !$this->_allowConfirmation) {
             $this->_requireApproval = TRUE;
         }
         $this->set('requireApproval', $this->_requireApproval);
         if (isset($this->_values['event']['default_role_id'])) {
             $participant_role = CRM_Core_OptionGroup::values('participant_role');
             $this->_values['event']['participant_role'] = $participant_role["{$this->_values['event']['default_role_id']}"];
         }
         $isPayLater = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $this->_eventId, 'is_pay_later');
         //check for various combinations for paylater, payment
         //process with paid event.
         if ($isMonetary && (!$isPayLater || !empty($this->_values['event']['payment_processor']))) {
             $this->_paymentProcessorIDs = explode(CRM_Core_DAO::VALUE_SEPARATOR, CRM_Utils_Array::value('payment_processor', $this->_values['event']));
             $this->assignPaymentProcessor($isPayLater);
         }
         //init event fee.
         self::initEventFee($this, $this->_eventId);
         // get the profile ids
         $ufJoinParams = array('entity_table' => 'civicrm_event', 'module' => 'CiviEvent', 'entity_id' => $this->_eventId);
         list($this->_values['custom_pre_id'], $this->_values['custom_post_id']) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
         // set profiles for additional participants
         if ($this->_values['event']['is_multiple_registrations']) {
             // CRM-4377: CiviEvent for the main participant, CiviEvent_Additional for additional participants
             $ufJoinParams['module'] = 'CiviEvent_Additional';
             list($this->_values['additional_custom_pre_id'], $this->_values['additional_custom_post_id'], $preActive, $postActive) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
             // CRM-4377: we need to maintain backward compatibility, hence if there is profile for main contact
             // set same profile for additional contacts.
             if ($this->_values['custom_pre_id'] && !$this->_values['additional_custom_pre_id']) {
                 $this->_values['additional_custom_pre_id'] = $this->_values['custom_pre_id'];
             }
             if ($this->_values['custom_post_id'] && !$this->_values['additional_custom_post_id']) {
                 $this->_values['additional_custom_post_id'] = $this->_values['custom_post_id'];
             }
             // now check for no profile condition, in that case is_active = 0
             if (isset($preActive) && !$preActive) {
                 unset($this->_values['additional_custom_pre_id']);
             }
             if (isset($postActive) && !$postActive) {
                 unset($this->_values['additional_custom_post_id']);
             }
         }
         $this->assignBillingType();
         if ($this->_values['event']['is_monetary']) {
             CRM_Core_Payment_Form::setPaymentFieldsByProcessor($this, $this->_paymentProcessor);
         }
         $params = array('entity_id' => $this->_eventId, 'entity_table' => 'civicrm_event');
         $this->_values['location'] = CRM_Core_BAO_Location::getValues($params, TRUE);
         $this->set('values', $this->_values);
         $this->set('fields', $this->_fields);
         $this->_availableRegistrations = CRM_Event_BAO_Participant::eventFull($this->_values['event']['id'], TRUE, CRM_Utils_Array::value('has_waitlist', $this->_values['event']));
         $this->set('availableRegistrations', $this->_availableRegistrations);
     }
     $this->assign_by_ref('paymentProcessor', $this->_paymentProcessor);
     // check if this is a paypal auto return and redirect accordingly
     if (CRM_Core_Payment::paypalRedirect($this->_paymentProcessor)) {
         $url = CRM_Utils_System::url('civicrm/event/register', "_qf_ThankYou_display=1&qfKey={$this->controller->_key}");
         CRM_Utils_System::redirect($url);
     }
     // The concept of contributeMode is deprecated.
     $this->_contributeMode = $this->get('contributeMode');
     $this->assign('contributeMode', $this->_contributeMode);
     // setting CMS page title
     CRM_Utils_System::setTitle($this->_values['event']['title']);
     $this->assign('title', $this->_values['event']['title']);
     $this->assign('paidEvent', $this->_values['event']['is_monetary']);
     // we do not want to display recently viewed items on Registration pages
     $this->assign('displayRecent', FALSE);
     // Registration page values are cleared from session, so can't use normal Printer Friendly view.
     // Use Browser Print instead.
     $this->assign('browserPrint', TRUE);
     $isShowLocation = CRM_Utils_Array::value('is_show_location', $this->_values['event']);
     $this->assign('isShowLocation', $isShowLocation);
     // Handle PCP
     $pcpId = CRM_Utils_Request::retrieve('pcpId', 'Positive', $this);
     if ($pcpId) {
         $pcp = CRM_PCP_BAO_PCP::handlePcp($pcpId, 'event', $this->_values['event']);
         $this->_pcpId = $pcp['pcpId'];
         $this->_values['event']['intro_text'] = CRM_Utils_Array::value('intro_text', $pcp['pcpInfo']);
     }
     // assign all event properties so wizard templates can display event info.
     $this->assign('event', $this->_values['event']);
     $this->assign('location', $this->_values['location']);
     $this->assign('bltID', $this->_bltID);
     $isShowLocation = CRM_Utils_Array::value('is_show_location', $this->_values['event']);
     $this->assign('isShowLocation', $isShowLocation);
     //CRM-6907
     $config->defaultCurrency = CRM_Utils_Array::value('currency', $this->_values['event'], $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['event']['campaign_id'] = $campID;
     }
     // Set the same value for is_billing_required as contribution page so code can be shared.
     $this->_values['is_billing_required'] = CRM_Utils_Array::value('is_billing_required', $this->_values['event']);
     // check if billing block is required for pay later
     // note that I have started removing the use of isBillingAddressRequiredForPayLater in favour of letting
     // the CRM_Core_Payment_Manual class handle it - but there are ~300 references to it in the code base so only
     // removing in very limited cases.
     if (CRM_Utils_Array::value('is_pay_later', $this->_values['event'])) {
         $this->_isBillingAddressRequiredForPayLater = CRM_Utils_Array::value('is_billing_required', $this->_values['event']);
         $this->assign('isBillingAddressRequiredForPayLater', $this->_isBillingAddressRequiredForPayLater);
     }
 }
Example #30
0
 /**
  * Create a new forward event, create a new contact if necessary
  */
 static function &forward($job_id, $queue_id, $hash, $forward_email, $fromEmail = null, $comment = null)
 {
     $q =& CRM_Mailing_Event_BAO_Queue::verify($job_id, $queue_id, $hash);
     $successfulForward = false;
     if (!$q) {
         return $successfulForward;
     }
     /* Find the email address/contact, if it exists */
     $contact = CRM_Contact_BAO_Contact::getTableName();
     $location = CRM_Core_BAO_Location::getTableName();
     $email = CRM_Core_BAO_Email::getTableName();
     $queueTable = CRM_Mailing_Event_BAO_Queue::getTableName();
     $job = CRM_Mailing_BAO_Job::getTableName();
     $mailing = CRM_Mailing_BAO_Mailing::getTableName();
     $forward = self::getTableName();
     $domain =& CRM_Core_BAO_Domain::getDomain();
     $dao =& new CRM_Core_Dao();
     $dao->query("\n                SELECT      {$contact}.id as contact_id,\n                            {$email}.id as email_id,\n                            {$contact}.do_not_email as do_not_email,\n                            {$queueTable}.id as queue_id\n                FROM        ({$email}, {$job} as temp_job)\n                INNER JOIN  {$contact}\n                        ON  {$email}.contact_id = {$contact}.id\n                LEFT JOIN   {$queueTable}\n                        ON  {$email}.id = {$queueTable}.email_id\n                LEFT JOIN   {$job}\n                        ON  {$queueTable}.job_id = {$job}.id\n                        AND temp_job.mailing_id = {$job}.mailing_id\n                WHERE       {$queueTable}.job_id = {$job_id}\n                    AND     {$email}.email = '" . CRM_Utils_Type::escape($forward_email, 'String') . "'");
     $dao->fetch();
     require_once 'CRM/Core/Transaction.php';
     $transaction = new CRM_Core_Transaction();
     if (isset($dao->queue_id) || $dao->do_not_email == 1) {
         /* We already sent this mailing to $forward_email, or we should
          * never email this contact.  Give up. */
         return $successfulForward;
     }
     require_once 'api/v2/Contact.php';
     $contact_params = array('email' => $forward_email);
     $count = civicrm_contact_search_count($contact_params);
     if ($count == 0) {
         require_once 'CRM/Core/BAO/LocationType.php';
         /* If the contact does not exist, create one. */
         $formatted = array('contact_type' => 'Individual');
         $locationType = CRM_Core_BAO_LocationType::getDefault();
         $value = array('email' => $forward_email, 'location_type_id' => $locationType->id);
         _civicrm_add_formatted_param($value, $formatted);
         require_once 'CRM/Import/Parser.php';
         $formatted['onDuplicate'] = CRM_Import_Parser::DUPLICATE_SKIP;
         $formatted['fixAddress'] = true;
         $contact =& civicrm_contact_format_create($formatted);
         if (civicrm_error($contact, CRM_Core_Error)) {
             return $successfulForward;
         }
         $contact_id = $contact['id'];
     }
     $email =& new CRM_Core_DAO_Email();
     $email->email = $forward_email;
     $email->find(true);
     $email_id = $email->id;
     if (!$contact_id) {
         $contact_id = $email->contact_id;
     }
     /* Create a new queue event */
     $queue_params = array('email_id' => $email_id, 'contact_id' => $contact_id, 'job_id' => $job_id);
     $queue =& CRM_Mailing_Event_BAO_Queue::create($queue_params);
     $forward =& new CRM_Mailing_Event_BAO_Forward();
     $forward->time_stamp = date('YmdHis');
     $forward->event_queue_id = $queue_id;
     $forward->dest_queue_id = $queue->id;
     $forward->save();
     $dao->reset();
     $dao->query("   SELECT  {$job}.mailing_id as mailing_id \n                        FROM    {$job}\n                        WHERE   {$job}.id = " . CRM_Utils_Type::escape($job_id, 'Integer'));
     $dao->fetch();
     $mailing_obj =& new CRM_Mailing_BAO_Mailing();
     $mailing_obj->id = $dao->mailing_id;
     $mailing_obj->find(true);
     $config =& CRM_Core_Config::singleton();
     $mailer =& $config->getMailer();
     $recipient = null;
     $attachments = null;
     $message =& $mailing_obj->compose($job_id, $queue->id, $queue->hash, $queue->contact_id, $forward_email, $recipient, false, null, $attachments, true, $fromEmail);
     //append comment if added while forwarding.
     if (count($comment)) {
         $message->_txtbody = $comment['body_text'] . $message->_txtbody;
         if (CRM_Utils_Array::value('body_html', $comment)) {
             $message->_htmlbody = $comment['body_html'] . '<br />---------------Original message---------------------<br />' . $message->_htmlbody;
         }
     }
     $body = $message->get();
     $headers = $message->headers();
     PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array('CRM_Core_Error', 'nullHandler'));
     $result = null;
     if (is_object($mailer)) {
         $result = $mailer->send($recipient, $headers, $body);
         CRM_Core_Error::setCallback();
     }
     $params = array('event_queue_id' => $queue->id, 'job_id' => $job_id, 'hash' => $queue->hash);
     if (is_a($result, PEAR_Error)) {
         /* Register the bounce event */
         $params = array_merge($params, CRM_Mailing_BAO_BouncePattern::match($result->getMessage()));
         CRM_Mailing_Event_BAO_Bounce::create($params);
     } else {
         $successfulForward = true;
         /* Register the delivery event */
         CRM_Mailing_Event_BAO_Delivered::create($params);
     }
     $transaction->commit();
     return $successfulForward;
 }