/**
  * create or update a Volunteer Commendation
  *
  * This function is invoked from within the web form layer
  *
  * @param array $params An assoc array of name/value pairs
  *  - aid: activity id of an existing commendation to update
  *  - cid: id of contact to be commended
  *  - vid: id of project for which contact is to be commended
  *  - details: text about the contact's exceptional volunteerism
  * @see self::requiredParamsArePresent for rules re required params
  * @return array Result of api.activity.create
  * @access public
  * @static
  */
 public static function create(array $params)
 {
     // check required params
     if (!self::requiredParamsArePresent($params)) {
         CRM_Core_Error::fatal('Not enough data to create commendation object.');
     }
     $activity_statuses = CRM_Activity_BAO_Activity::buildOptions('status_id', 'create');
     $api_params = array('activity_type_id' => self::getActivityTypeId(), 'status_id' => CRM_Utils_Array::key('Completed', $activity_statuses));
     $aid = CRM_Utils_Array::value('aid', $params);
     if ($aid) {
         $api_params['id'] = $aid;
     }
     $cid = CRM_Utils_Array::value('cid', $params);
     if ($cid) {
         $api_params['target_contact_id'] = $cid;
     }
     $vid = CRM_Utils_Array::value('vid', $params);
     if ($vid) {
         $project = CRM_Volunteer_BAO_Project::retrieveByID($vid);
         $api_params['subject'] = ts('Volunteer Commendation for %1', array('1' => $project->title, 'domain' => 'org.civicrm.volunteer'));
         $customFieldSpec = self::getCustomFields();
         $volunteer_project_id_field_name = $customFieldSpec['volunteer_project_id']['custom_n'];
         $api_params[$volunteer_project_id_field_name] = $vid;
     }
     if (array_key_exists('details', $params)) {
         $api_params['details'] = CRM_Utils_Array::value('details', $params);
     }
     return civicrm_api3('Activity', 'create', $api_params);
 }
 /**
  * Load needed JS, CSS and settings for the backend Volunteer Management UI
  */
 public static function addResources($entity_id, $entity_table)
 {
     static $loaded = FALSE;
     $ccr = CRM_Core_Resources::singleton();
     if ($loaded || $ccr->isAjaxMode()) {
         return;
     }
     $loaded = TRUE;
     $config = CRM_Core_Config::singleton();
     // Vendor libraries
     $ccr->addScriptFile('civicrm', 'packages/backbone/json2.js', 100, 'html-header', FALSE);
     $ccr->addScriptFile('civicrm', 'packages/backbone/backbone-min.js', 120, 'html-header', FALSE);
     $ccr->addScriptFile('civicrm', 'packages/backbone/backbone.marionette.min.js', 125, 'html-header', FALSE);
     // Our stylesheet
     $ccr->addStyleFile('org.civicrm.volunteer', 'css/volunteer_app.css');
     // Add all scripts for our js app
     $weight = 0;
     $baseDir = CRM_Extension_System::singleton()->getMapper()->keyToBasePath('org.civicrm.volunteer') . '/';
     // This glob pattern will recurse the js directory up to 4 levels deep
     foreach (glob($baseDir . 'js/backbone/{*,*/*,*/*/*,*/*/*/*}.js', GLOB_BRACE) as $file) {
         $fileName = substr($file, strlen($baseDir));
         $ccr->addScriptFile('org.civicrm.volunteer', $fileName, $weight++);
     }
     // Add our template
     CRM_Core_Smarty::singleton()->assign('isModulePermissionSupported', CRM_Core_Config::singleton()->userPermissionClass->isModulePermissionSupported());
     CRM_Core_Region::instance('page-header')->add(array('template' => 'CRM/Volunteer/Form/Manage.tpl'));
     // Fetch event so we can set the default start time for needs
     // FIXME: Not the greatest for supporting non-events
     $entity = civicrm_api3(str_replace('civicrm_', '', $entity_table), 'getsingle', array('id' => $entity_id));
     // Static variables
     $ccr->addSetting(array('pseudoConstant' => array('volunteer_need_visibility' => array_flip(CRM_Volunteer_BAO_Need::buildOptions('visibility_id', 'validate')), 'volunteer_role' => CRM_Volunteer_BAO_Need::buildOptions('role_id', 'get'), 'volunteer_status' => CRM_Activity_BAO_Activity::buildOptions('status_id', 'validate')), 'volunteer' => array('default_date' => CRM_Utils_Array::value('start_date', $entity)), 'config' => array('timeInputFormat' => $config->timeInputFormat), 'constants' => array('CRM_Core_Action' => array('NONE' => 0, 'ADD' => 1, 'UPDATE' => 2, 'VIEW' => 4, 'DELETE' => 8, 'BROWSE' => 16, 'ENABLE' => 32, 'DISABLE' => 64, 'EXPORT' => 128, 'BASIC' => 256, 'ADVANCED' => 512, 'PREVIEW' => 1024, 'FOLLOWUP' => 2048, 'MAP' => 4096, 'PROFILE' => 8192, 'COPY' => 16384, 'RENEW' => 32768, 'DETACH' => 65536, 'REVERT' => 131072, 'CLOSE' => 262144, 'REOPEN' => 524288, 'MAX_ACTION' => 1048575))));
     // Check for problems
     _volunteer_checkResourceUrl();
 }
Exemplo n.º 3
0
 /**
  * Load needed JS, CSS and settings for the backend Volunteer Management UI
  */
 public static function addResources($entity_id, $entity_table)
 {
     static $loaded = FALSE;
     if ($loaded) {
         return;
     }
     $loaded = TRUE;
     $config = CRM_Core_Config::singleton();
     $ccr = CRM_Core_Resources::singleton();
     // Vendor libraries
     $ccr->addScriptFile('civicrm', 'packages/backbone/json2.js', 100, 'html-header', FALSE);
     $ccr->addScriptFile('civicrm', 'packages/backbone/backbone-min.js', 120, 'html-header');
     $ccr->addScriptFile('civicrm', 'packages/backbone/backbone.marionette.min.js', 125, 'html-header', FALSE);
     // Our stylesheet
     $ccr->addStyleFile('org.civicrm.volunteer', 'css/volunteer_app.css');
     // Add all scripts for our js app
     $weight = 0;
     $baseDir = CRM_Extension_System::singleton()->getMapper()->keyToBasePath('org.civicrm.volunteer') . '/';
     // This glob pattern will recurse the js directory up to 4 levels deep
     foreach (glob($baseDir . 'js/{*,*/*,*/*/*,*/*/*/*}.js', GLOB_BRACE) as $file) {
         $fileName = substr($file, strlen($baseDir));
         $ccr->addScriptFile('org.civicrm.volunteer', $fileName, $weight++);
     }
     // Add our template
     CRM_Core_Smarty::singleton()->assign('isModulePermissionSupported', CRM_Core_Config::singleton()->userPermissionClass->isModulePermissionSupported());
     CRM_Core_Region::instance('page-header')->add(array('template' => 'CRM/Volunteer/Form/Manage.tpl'));
     // Fetch event so we can set the default start time for needs
     // FIXME: Not the greatest for supporting non-events
     $entity = civicrm_api3(str_replace('civicrm_', '', $entity_table), 'getsingle', array('id' => $entity_id));
     // Static variables
     $ccr->addSetting(array('pseudoConstant' => array('volunteer_need_visibility' => array_flip(CRM_Volunteer_BAO_Need::buildOptions('visibility_id', 'validate')), 'volunteer_role' => CRM_Volunteer_BAO_Need::buildOptions('role_id', 'get'), 'volunteer_status' => CRM_Activity_BAO_Activity::buildOptions('status_id', 'validate')), 'volunteer' => array('default_date' => CRM_Utils_Array::value('start_date', $entity)), 'config' => array('timeInputFormat' => $config->timeInputFormat)));
     // Check for problems
     _volunteer_civicrm_check_resource_url();
 }
Exemplo n.º 4
0
 /**
  * Process the form after the input has been submitted and validated.
  */
 public function postProcess()
 {
     $formparams = $this->exportValues();
     $caseId = $formparams['unclosed_case_id'];
     $filedActivities = 0;
     foreach ($this->_activityHolderIds as $key => $id) {
         $targetContactValues = $defaults = array();
         $params = array('id' => $id);
         CRM_Activity_BAO_Activity::retrieve($params, $defaults);
         if (CRM_Case_BAO_Case::checkPermission($id, 'File On Case', $defaults['activity_type_id'])) {
             if (!CRM_Utils_Array::crmIsEmptyArray($defaults['target_contact'])) {
                 $targetContactValues = array_combine(array_unique($defaults['target_contact']), explode(';', trim($defaults['target_contact_value'])));
                 $targetContactValues = implode(',', array_keys($targetContactValues));
             }
             $params = array('caseID' => $caseId, 'activityID' => $id, 'newSubject' => empty($defaults['subject']) ? '' : $defaults['subject'], 'targetContactIds' => $targetContactValues, 'mode' => 'file');
             $error_msg = CRM_Activity_Page_AJAX::_convertToCaseActivity($params);
             if (empty($error_msg['error_msg'])) {
                 $filedActivities++;
             } else {
                 CRM_Core_Session::setStatus($error_msg['error_msg'], ts("Error"), "error");
             }
         } else {
             CRM_Core_Session::setStatus(ts('Not permitted to file activity %1 %2.', array(1 => empty($defaults['subject']) ? '' : $defaults['subject'], 2 => $defaults['activity_date_time'])), ts("Error"), "error");
         }
     }
     CRM_Core_Session::setStatus($filedActivities, ts("Filed Activities"), "success");
     CRM_Core_Session::setStatus("", ts('Total Selected Activities: %1', array(1 => count($this->_activityHolderIds))), "info");
 }
Exemplo n.º 5
0
 static function &getFields()
 {
     $fields = array();
     $fields = CRM_Case_BAO_Case::exportableFields();
     // add activity related fields
     $fields = array_merge($fields, CRM_Activity_BAO_Activity::exportableFields('Case'));
     return $fields;
 }
/**
 * Adjust Metadata for Create action
 *
 * The metadata is used for setting defaults, documentation & validation
 * @param array $params array or parameters determined by getfields
 */
function _civicrm_api3_volunteer_assignment_create_spec(&$params)
{
    $params['volunteer_need_id']['api.required'] = 1;
    $params['assignee_contact_id']['api.required'] = 1;
    $params['assignee_contact_id']['api.aliases'] = array('contact_id');
    $volunteerStatus = CRM_Activity_BAO_Activity::buildOptions('status_id', 'validate');
    $params['status_id']['api.default'] = array_search('Scheduled', $volunteerStatus);
}
Exemplo n.º 7
0
 function setDefaultValues()
 {
     if (isset($this->_activityId)) {
         $params = array('id' => $this->_activityId);
         CRM_Activity_BAO_Activity::retrieve($params, $defaults);
         $defaults['html_message'] = $defaults['details'];
         return $defaults;
     }
 }
Exemplo n.º 8
0
 /**
  * Get fields.
  *
  * @param bool $excludeActivityFields
  *
  * @return array
  */
 public static function &getFields($excludeActivityFields = FALSE)
 {
     $fields = CRM_Case_BAO_Case::exportableFields();
     // add activity related fields
     if (!$excludeActivityFields) {
         $fields = array_merge($fields, CRM_Activity_BAO_Activity::exportableFields('Case'));
     }
     return $fields;
 }
Exemplo n.º 9
0
 static function &getFields()
 {
     require_once 'CRM/Case/BAO/Case.php';
     $fields = array();
     $fields = CRM_Case_BAO_Case::exportableFields();
     // add activity related fields
     require_once 'CRM/Activity/BAO/Activity.php';
     $fields = array_merge($fields, CRM_Activity_BAO_Activity::exportableFields('Case'));
     return $fields;
 }
Exemplo n.º 10
0
 /**
  * Set default values for the form.
  */
 public function setDefaultValues()
 {
     $defaults = array();
     if (isset($this->_activityId)) {
         $params = array('id' => $this->_activityId);
         CRM_Activity_BAO_Activity::retrieve($params, $defaults);
         $defaults['html_message'] = CRM_Utils_Array::value('details', $defaults);
     }
     $defaults = $defaults + CRM_Contact_Form_Task_PDFLetterCommon::setDefaultValues();
     return $defaults;
 }
Exemplo n.º 11
0
 /**
  * This function sets the default values for the form. For edit/view mode
  * the default values are retrieved from the database
  *
  * @access public
  *
  * @return None
  */
 function setDefaultValues()
 {
     $targetContactValues = $defaults = array();
     $params = array('id' => $this->_activityId);
     CRM_Activity_BAO_Activity::retrieve($params, $defaults);
     $defaults['case_activity_subject'] = $defaults['subject'];
     if (!CRM_Utils_Array::crmIsEmptyArray($defaults['target_contact'])) {
         $targetContactValues = array_combine(array_unique($defaults['target_contact']), explode(';', trim($defaults['target_contact_value'])));
     }
     $this->assign('targetContactValues', empty($targetContactValues) ? FALSE : $targetContactValues);
     return $defaults;
 }
Exemplo n.º 12
0
 /**
  * process the form after the input has been submitted and validated
  *
  * @access public
  *
  * @return void
  */
 public function postProcess()
 {
     $deletedActivities = 0;
     foreach ($this->_activityHolderIds as $activityId['id']) {
         $moveToTrash = CRM_Case_BAO_Case::isCaseActivity($activityId['id']);
         if (CRM_Activity_BAO_Activity::deleteActivity($activityId, $moveToTrash)) {
             $deletedActivities++;
         }
     }
     CRM_Core_Session::setStatus($deletedActivities, ts('Deleted Activities'), "success");
     CRM_Core_Session::setStatus("", ts('Total Selected Activities: %1', array(1 => count($this->_activityHolderIds))), "info");
 }
Exemplo n.º 13
0
 function setDefaultValues()
 {
     $defaults = array();
     if (isset($this->_activityId)) {
         $params = array('id' => $this->_activityId);
         CRM_Activity_BAO_Activity::retrieve($params, $defaults);
         $defaults['html_message'] = $defaults['details'];
     } else {
         $defaults['thankyou_update'] = 1;
     }
     $defaults = $defaults + CRM_Contact_Form_Task_PDFLetterCommon::setDefaultValues();
     return $defaults;
 }
Exemplo n.º 14
0
 /**
  * process the form after the input has been submitted and validated
  *
  * @access public
  * @return None
  */
 public function postProcess()
 {
     $deletedActivities = 0;
     foreach ($this->_activityHolderIds as $activityId['id']) {
         require_once 'CRM/Case/BAO/Case.php';
         $moveToTrash = CRM_Case_BAO_Case::isCaseActivity($activityId['id']);
         if (CRM_Activity_BAO_Activity::deleteActivity($activityId, $moveToTrash)) {
             $deletedActivities++;
         }
     }
     $status = array(ts('Deleted Activities: %1', array(1 => $deletedActivities)), ts('Total Selected Activities: %1', array(1 => count($this->_activityHolderIds))));
     CRM_Core_Session::setStatus($status);
 }
Exemplo n.º 15
0
 /**
  * Function to set variables up before form is built
  *
  * @return void
  * @access public
  */
 public function preProcess()
 {
     //get the activity values
     $activityId = CRM_Utils_Request::retrieve('id', 'Positive', $this);
     $context = CRM_Utils_Request::retrieve('context', 'String', $this);
     $cid = CRM_Utils_Request::retrieve('cid', 'Positive', $this);
     //check for required permissions, CRM-6264
     if ($activityId && !CRM_Activity_BAO_Activity::checkPermission($activityId, CRM_Core_Action::VIEW)) {
         CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
     }
     $session = CRM_Core_Session::singleton();
     if (!in_array($context, array('home', 'dashlet', 'dashletFullscreen'))) {
         $url = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$cid}&selectedChild=activity");
     } else {
         $url = CRM_Utils_System::url('civicrm/dashboard', 'reset=1');
     }
     $session->pushUserContext($url);
     $defaults = array();
     $params = array('id' => $activityId);
     CRM_Activity_BAO_Activity::retrieve($params, $defaults);
     //set activity type name and description to template
     list($activityTypeName, $activityTypeDescription) = CRM_Core_BAO_OptionValue::getActivityTypeDetails($defaults['activity_type_id']);
     $this->assign('activityTypeName', $activityTypeName);
     $this->assign('activityTypeDescription', $activityTypeDescription);
     if (CRM_Utils_Array::value('mailingId', $defaults)) {
         $this->_mailing_id = CRM_Utils_Array::value('source_record_id', $defaults);
         $mailingReport = CRM_Mailing_BAO_Mailing::report($this->_mailing_id, TRUE);
         CRM_Mailing_BAO_Mailing::getMailingContent($mailingReport, $this);
         $this->assign('mailingReport', $mailingReport);
         $full_open_report = CRM_Mailing_Event_BAO_Opened::getRows($this->_mailing_id, NULL, FALSE, NULL, NULL, NULL, $cid);
         $this->assign('openreport', $full_open_report);
         $click_thru_report = CRM_Mailing_Event_BAO_TrackableURLOpen::getRows($this->_mailing_id, NULL, FALSE, NULL, NULL, NULL, NULL, $cid);
         $this->assign('clickreport', $click_thru_report);
     }
     foreach ($defaults as $key => $value) {
         if (substr($key, -3) != '_id') {
             $values[$key] = $value;
         }
     }
     //get the campaign
     if ($campaignId = CRM_Utils_Array::value('campaign_id', $defaults)) {
         $campaigns = CRM_Campaign_BAO_Campaign::getCampaigns($campaignId);
         $values['campaign'] = $campaigns[$campaignId];
     }
     if ($engagementLevel = CRM_Utils_Array::value('engagement_level', $defaults)) {
         $engagementLevels = CRM_Campaign_PseudoConstant::engagementLevel();
         $values['engagement_level'] = CRM_Utils_Array::value($engagementLevel, $engagementLevels, $engagementLevel);
     }
     $values['attachment'] = CRM_Core_BAO_File::attachmentInfo('civicrm_activity', $activityId);
     $this->assign('values', $values);
 }
Exemplo n.º 16
0
/**
 * This function will return the needed pieces to load up the backbone/
 * marionette project backend from within an angular page.
 *
 * @param array $params
 *   Not presently used.
 * @return array
 *   Keyed with "css," "templates," "scripts," and "settings," this array
 *   contains the dependencies of the backbone-based volunteer app.
 *
 */
function civicrm_api3_volunteer_util_loadbackbone($params)
{
    $results = array("css" => array(), "templates" => array(), "scripts" => array(), "settings" => array());
    $ccr = CRM_Core_Resources::singleton();
    $config = CRM_Core_Config::singleton();
    $results['css'][] = $ccr->getUrl('org.civicrm.volunteer', 'css/volunteer_app.css');
    $baseDir = CRM_Extension_System::singleton()->getMapper()->keyToBasePath('org.civicrm.volunteer') . '/';
    // This glob pattern will recurse the js directory up to 4 levels deep
    foreach (glob($baseDir . 'js/{*,*/*,*/*/*,*/*/*/*}.js', GLOB_BRACE) as $file) {
        $fileName = substr($file, strlen($baseDir));
        $results['scripts'][] = $ccr->getUrl('org.civicrm.volunteer', $fileName);
    }
    $results['templates'][] = 'civicrm/volunteer/backbonetemplates';
    $results['settings'] = array('pseudoConstant' => array('volunteer_need_visibility' => array_flip(CRM_Volunteer_BAO_Need::buildOptions('visibility_id', 'validate')), 'volunteer_role' => CRM_Volunteer_BAO_Need::buildOptions('role_id', 'get'), 'volunteer_status' => CRM_Activity_BAO_Activity::buildOptions('status_id', 'validate')), 'volunteer' => array('default_date' => date("Y-m-d H:i:s", strtotime('tomorrow noon'))), 'config' => array('timeInputFormat' => $config->timeInputFormat), 'constants' => array('CRM_Core_Action' => array('NONE' => 0, 'ADD' => 1, 'UPDATE' => 2, 'VIEW' => 4, 'DELETE' => 8, 'BROWSE' => 16, 'ENABLE' => 32, 'DISABLE' => 64, 'EXPORT' => 128, 'BASIC' => 256, 'ADVANCED' => 512, 'PREVIEW' => 1024, 'FOLLOWUP' => 2048, 'MAP' => 4096, 'PROFILE' => 8192, 'COPY' => 16384, 'RENEW' => 32768, 'DETACH' => 65536, 'REVERT' => 131072, 'CLOSE' => 262144, 'REOPEN' => 524288, 'MAX_ACTION' => 1048575)));
    return civicrm_api3_create_success($results, "VolunteerUtil", "loadbackbone", $params);
}
Exemplo n.º 17
0
/**
 * Retrieve a set of Activities specific to given contact Id.
 * @param int $contactID.
 *
 * @return array (reference)  array of activities.
 * @access public
 */
function &_civicrm_activities_get($contactID, $type = 'all')
{
    $activities = CRM_Activity_BAO_Activity::getContactActivity($contactID);
    //get the custom data.
    if (is_array($activities) && !empty($activities)) {
        require_once 'api/v2/Activity.php';
        foreach ($activities as $activityId => $values) {
            $customParams = array('activity_id' => $activityId, 'activity_type_id' => CRM_Utils_Array::value('activity_type_id', $values));
            $customData = civicrm_activity_custom_get($customParams);
            if (is_array($customData) && !empty($customData)) {
                $activities[$activityId] = array_merge($activities[$activityId], $customData);
            }
        }
    }
    return $activities;
}
Exemplo n.º 18
0
 /**
  * Set default values for the form. For edit/view mode
  * the default values are retrieved from the database
  *
  *
  * @return array
  */
 public function setDefaultValues()
 {
     $defaults = array();
     $params = array('id' => $this->_activityId);
     CRM_Activity_BAO_Activity::retrieve($params, $defaults);
     $defaults['file_on_case_activity_subject'] = $defaults['subject'];
     $defaults['file_on_case_target_contact_id'] = $defaults['target_contact'];
     // If this contact has an open case, supply it as a default
     $cid = CRM_Utils_Request::retrieve('cid', 'Integer');
     if ($cid) {
         $cases = civicrm_api3('CaseContact', 'get', array('contact_id' => $cid, 'case_id' => array('!=' => $this->_currentCaseId), 'case_id.status_id' => array('!=' => "Closed"), 'case_id.is_deleted' => 0, 'case_id.end_date' => array('IS NULL' => 1), 'options' => array('limit' => 1), 'return' => 'case_id'));
         foreach ($cases['values'] as $record) {
             $defaults['file_on_case_unclosed_case_id'] = $record['case_id'];
             break;
         }
     }
     return $defaults;
 }
Exemplo n.º 19
0
 public function onChange(CRM_HRCaseUtils_Analyzer $analyzer, $objectRef)
 {
     if (isset($objectRef->activity_type_id)) {
         // Get activity type name & status of the activity being completed
         $activityTypeGroup = civicrm_api3('option_group', 'get', array('name' => 'activity_type'));
         $activityType = array('value' => $objectRef->activity_type_id, 'option_group_id' => $activityTypeGroup['id']);
         $activityTypeID = civicrm_api3('option_value', 'get', $activityType);
         $activityTypeID = $activityTypeID['values'][$activityTypeID['id']]['name'];
         $activityStatusGroup = civicrm_api3('option_group', 'get', array('name' => 'activity_status'));
         $activityStatus = array('value' => $objectRef->status_id, 'option_group_id' => $activityStatusGroup['id']);
         $activityStatusID = civicrm_api3('option_value', 'get', $activityStatus);
         $activityStatusID = $activityStatusID['values'][$activityStatusID['id']]['name'];
         // Schedule Interview Prospect activity
         if ($activityTypeID == 'Open Case' && $activityStatusID == 'Completed') {
             if ($analyzer->hasActivity($activityTypeID, $activityStatusID)) {
                 $nextActivity = 'Interview Prospect';
                 // Get the activity ID for Interview Prospect
                 $activityID = array('name' => $nextActivity, 'option_group_id' => $activityTypeGroup['id']);
                 $activityTypeID = civicrm_api3('option_value', 'get', $activityID);
                 $activityTypeID = $activityTypeID['values'][$activityTypeID['id']]['value'];
                 $params = self::buildParams($activityTypeID, $nextActivity, $objectRef);
             }
         } elseif ($activityTypeID == 'Interview Prospect' && $activityStatusID == 'Completed') {
             if ($analyzer->hasActivity($activityTypeID, $activityStatusID)) {
                 $nextActivity = 'Background Check';
                 // Get the activity ID for Background Check
                 $activityID = array('name' => $nextActivity, 'option_group_id' => $activityTypeGroup['id']);
                 $activityTypeID = civicrm_api3('option_value', 'get', $activityID);
                 $activityTypeID = $activityTypeID['values'][$activityTypeID['id']]['value'];
                 $params = self::buildParams($activityTypeID, $nextActivity, $objectRef);
             }
         } elseif ($activityTypeID == 'Background Check' && $activityStatusID == 'Completed') {
             return;
         }
         if (isset($params)) {
             $followupActivity = CRM_Activity_BAO_Activity::createFollowupActivity($objectRef->original_id, $params);
             if ($followupActivity) {
                 $caseParams = array('activity_id' => $followupActivity->id, 'case_id' => $objectRef->case_id);
                 CRM_Case_BAO_Case::processCaseActivity($caseParams);
                 $analyzer->flush();
             }
         }
     }
 }
Exemplo n.º 20
0
 /**
  * Process the form after the input has been submitted and validated.
  *
  *
  * @return void
  */
 public function postProcess()
 {
     $deleted = $failed = 0;
     foreach ($this->_activityHolderIds as $activityId['id']) {
         $moveToTrash = CRM_Case_BAO_Case::isCaseActivity($activityId['id']);
         if (CRM_Activity_BAO_Activity::deleteActivity($activityId, $moveToTrash)) {
             $deleted++;
         } else {
             $failed++;
         }
     }
     if ($deleted) {
         $msg = ts('%count activity deleted.', array('plural' => '%count activities deleted.', 'count' => $deleted));
         CRM_Core_Session::setStatus($msg, ts('Removed'), 'success');
     }
     if ($failed) {
         CRM_Core_Session::setStatus(ts('1 could not be deleted.', array('plural' => '%count could not be deleted.', 'count' => $failed)), ts('Error'), 'error');
     }
 }
Exemplo n.º 21
0
 /**
  * Set default values for the form. For edit/view mode
  * the default values are retrieved from the database
  *
  *
  * @return array
  */
 public function setDefaultValues()
 {
     $defaults = array();
     $params = array('id' => $this->_activityId);
     CRM_Activity_BAO_Activity::retrieve($params, $defaults);
     $defaults['file_on_case_activity_subject'] = $defaults['subject'];
     $defaults['file_on_case_target_contact_id'] = $defaults['target_contact'];
     // If this contact has an open case, supply it as a default
     $cid = CRM_Utils_Request::retrieve('cid', 'Integer');
     if ($cid) {
         $cases = CRM_Case_BAO_Case::getUnclosedCases(array('contact_id' => $cid), $this->_currentCaseId);
         foreach ($cases as $id => $details) {
             $defaults['file_on_case_unclosed_case_id'] = $id;
             $value = array('label' => $details['sort_name'] . ' - ' . $details['case_type'], 'extra' => array('contact_id' => $cid));
             $this->updateElementAttr('file_on_case_unclosed_case_id', array('data-value' => json_encode($value)));
             break;
         }
     }
     return $defaults;
 }
Exemplo n.º 22
0
 /**  
  * Function to set variables up before form is built  
  *                                                            
  * @return void  
  * @access public  
  */
 public function preProcess()
 {
     //get the activity values
     $activityId = CRM_Utils_Request::retrieve('id', 'Positive', $this);
     $context = CRM_Utils_Request::retrieve('context', 'String', $this);
     $cid = CRM_Utils_Request::retrieve('cid', 'Positive', $this);
     //check for required permissions, CRM-6264
     if ($activityId && !CRM_Activity_BAO_Activity::checkPermission($activityId, CRM_Core_Action::VIEW)) {
         CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
     }
     $session = CRM_Core_Session::singleton();
     if ($context != 'home') {
         $url = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$cid}&selectedChild=activity");
     } else {
         $url = CRM_Utils_System::url('civicrm/dashboard', 'reset=1');
     }
     $session->pushUserContext($url);
     $params = array('id' => $activityId);
     CRM_Activity_BAO_Activity::retrieve($params, $defaults);
     //set activity type name and description to template
     require_once 'CRM/Core/BAO/OptionValue.php';
     list($activityTypeName, $activityTypeDescription) = CRM_Core_BAO_OptionValue::getActivityTypeDetails($defaults['activity_type_id']);
     $this->assign('activityTypeName', $activityTypeName);
     $this->assign('activityTypeDescription', $activityTypeDescription);
     if (CRM_Utils_Array::value('mailingId', $defaults)) {
         $this->_mailing_id = CRM_Utils_Array::value('source_record_id', $defaults);
         require_once 'CRM/Mailing/BAO/Mailing.php';
         $mailingReport =& CRM_Mailing_BAO_Mailing::report($this->_mailing_id, true);
         CRM_Mailing_BAO_Mailing::getMailingContent($mailingReport, $this);
         $this->assign('mailingReport', $mailingReport);
     }
     foreach ($defaults as $key => $value) {
         if (substr($key, -3) != '_id') {
             $values[$key] = $value;
         }
     }
     require_once 'CRM/Core/BAO/File.php';
     $values['attachment'] = CRM_Core_BAO_File::attachmentInfo('civicrm_activity', $activityId);
     $this->assign('values', $values);
 }
Exemplo n.º 23
0
 /**
  * the initializer code, called before the processing
  *
  * @return void
  * @access public
  */
 function init()
 {
     $activityContact = CRM_Activity_BAO_ActivityContact::import();
     $activityTarget['target_contact_id'] = $activityContact['contact_id'];
     $fields = array_merge(CRM_Activity_BAO_Activity::importableFields(), $activityTarget);
     $fields = array_merge($fields, array('source_contact_id' => array('title' => ts('Source Contact'), 'headerPattern' => '/Source.Contact?/i'), 'activity_label' => array('title' => ts('Activity Type Label'), 'headerPattern' => '/(activity.)?type label?/i')));
     foreach ($fields as $name => $field) {
         $field['type'] = CRM_Utils_Array::value('type', $field, CRM_Utils_Type::T_INT);
         $field['dataPattern'] = CRM_Utils_Array::value('dataPattern', $field, '//');
         $field['headerPattern'] = CRM_Utils_Array::value('headerPattern', $field, '//');
         $this->addField($name, $field['title'], $field['type'], $field['headerPattern'], $field['dataPattern']);
     }
     $this->_newActivity = array();
     $this->setActiveFields($this->_mapperKeys);
     // FIXME: we should do this in one place together with Form/MapField.php
     $this->_contactIdIndex = -1;
     $this->_activityTypeIndex = -1;
     $this->_activityLabelIndex = -1;
     $this->_activityDateIndex = -1;
     $index = 0;
     foreach ($this->_mapperKeys as $key) {
         switch ($key) {
             case 'target_contact_id':
             case 'external_identifier':
                 $this->_contactIdIndex = $index;
                 break;
             case 'activity_label':
                 $this->_activityLabelIndex = $index;
                 break;
             case 'activity_type_id':
                 $this->_activityTypeIndex = $index;
                 break;
             case 'activity_date_time':
                 $this->_activityDateIndex = $index;
                 break;
         }
         $index++;
     }
 }
Exemplo n.º 24
0
 /**
  * the initializer code, called before the processing
  *
  * @return void
  * @access public
  */
 function init()
 {
     require_once 'CRM/Activity/BAO/Activity.php';
     require_once 'CRM/Activity/BAO/ActivityTarget.php';
     $fields = array_merge(CRM_Activity_BAO_Activity::importableFields(), CRM_Activity_BAO_ActivityTarget::import());
     $fields = array_merge($fields, array('activity_name' => array('title' => ts('Activity Type Label'), 'headerPattern' => '/(activity.)?type label?/i')));
     foreach ($fields as $name => $field) {
         $this->addField($name, $field['title'], $field['type'], $field['headerPattern'], $field['dataPattern']);
     }
     $this->_newActivity = array();
     $this->setActiveFields($this->_mapperKeys);
     // FIXME: we should do this in one place together with Form/MapField.php
     $this->_contactIdIndex = -1;
     $this->_activityTypeIndex = -1;
     $this->_activityNameIndex = -1;
     $this->_activityDateIndex = -1;
     $index = 0;
     foreach ($this->_mapperKeys as $key) {
         switch ($key) {
             case 'target_contact_id':
             case 'external_identifier':
                 $this->_contactIdIndex = $index;
                 break;
             case 'activity_name':
                 $this->_activityNameIndex = $index;
                 break;
             case 'activity_type_id':
                 $this->_activityTypeIndex = $index;
                 break;
             case 'activity_date_time':
                 $this->_activityDateIndex = $index;
                 break;
         }
         $index++;
     }
 }
Exemplo n.º 25
0
 /**
  * Get list of batches.
  *
  * @param array $params
  *   Associated array for params.
  *
  * @return array
  */
 public static function getBatchList(&$params)
 {
     $whereClause = self::whereClause($params);
     if (!empty($params['rowCount']) && is_numeric($params['rowCount']) && is_numeric($params['offset']) && $params['rowCount'] > 0) {
         $limit = " LIMIT {$params['offset']}, {$params['rowCount']} ";
     }
     $orderBy = ' ORDER BY batch.id desc';
     if (!empty($params['sort'])) {
         $orderBy = ' ORDER BY ' . CRM_Utils_Type::escape($params['sort'], 'String');
     }
     $query = "\n      SELECT batch.*, c.sort_name created_by\n      FROM  civicrm_batch batch\n      INNER JOIN civicrm_contact c ON batch.created_id = c.id\n    WHERE {$whereClause}\n    {$orderBy}\n    {$limit}";
     $object = CRM_Core_DAO::executeQuery($query, $params, TRUE, 'CRM_Batch_DAO_Batch');
     if (!empty($params['context'])) {
         $links = self::links($params['context']);
     } else {
         $links = self::links();
     }
     $batchTypes = CRM_Core_PseudoConstant::get('CRM_Batch_DAO_Batch', 'type_id');
     $batchStatus = CRM_Core_PseudoConstant::get('CRM_Batch_DAO_Batch', 'status_id');
     $batchStatusByName = CRM_Core_PseudoConstant::get('CRM_Batch_DAO_Batch', 'status_id', array('labelColumn' => 'name'));
     $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
     $results = array();
     while ($object->fetch()) {
         $values = array();
         $newLinks = $links;
         CRM_Core_DAO::storeValues($object, $values);
         $action = array_sum(array_keys($newLinks));
         if ($values['status_id'] == array_search('Closed', $batchStatusByName) && $params['context'] != 'financialBatch') {
             $newLinks = array();
         } elseif ($params['context'] == 'financialBatch') {
             $values['check'] = "<input type='checkbox' id='check_" . $object->id . "' name='check_" . $object->id . "' value='1'  data-status_id='" . $values['status_id'] . "' class='select-row'></input>";
             switch ($batchStatusByName[$values['status_id']]) {
                 case 'Open':
                     CRM_Utils_Array::remove($newLinks, 'reopen', 'download');
                     break;
                 case 'Closed':
                     CRM_Utils_Array::remove($newLinks, 'close', 'edit', 'download');
                     break;
                 case 'Exported':
                     CRM_Utils_Array::remove($newLinks, 'close', 'edit', 'reopen', 'export');
             }
         }
         if (!empty($values['type_id'])) {
             $values['batch_type'] = $batchTypes[$values['type_id']];
         }
         $values['batch_status'] = $batchStatus[$values['status_id']];
         $values['created_by'] = $object->created_by;
         $values['payment_instrument'] = '';
         if (!empty($object->payment_instrument_id)) {
             $values['payment_instrument'] = $paymentInstrument[$object->payment_instrument_id];
         }
         $tokens = array('id' => $object->id, 'status' => $values['status_id']);
         if ($values['status_id'] == array_search('Exported', $batchStatusByName)) {
             $aid = CRM_Core_OptionGroup::getValue('activity_type', 'Export Accounting Batch');
             $activityParams = array('source_record_id' => $object->id, 'activity_type_id' => $aid);
             $exportActivity = CRM_Activity_BAO_Activity::retrieve($activityParams, $val);
             $fid = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_EntityFile', $exportActivity->id, 'file_id', 'entity_id');
             $tokens = array_merge(array('eid' => $exportActivity->id, 'fid' => $fid), $tokens);
         }
         $values['action'] = CRM_Core_Action::formLink($newLinks, $action, $tokens, ts('more'), FALSE, 'batch.selector.row', 'Batch', $object->id);
         $results[$object->id] = $values;
     }
     return $results;
 }
Exemplo n.º 26
0
 /**
  * Process the view.
  *
  *
  * @return void
  */
 public function preProcess()
 {
     $contactID = CRM_Utils_Request::retrieve('cid', 'Integer', $this, TRUE);
     $activityID = CRM_Utils_Request::retrieve('aid', 'Integer', $this, TRUE);
     $revs = CRM_Utils_Request::retrieve('revs', 'Boolean', CRM_Core_DAO::$_nullObject);
     $caseID = CRM_Utils_Request::retrieve('caseID', 'Boolean', CRM_Core_DAO::$_nullObject);
     $activitySubject = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity', $activityID, 'subject');
     //check for required permissions, CRM-6264
     if ($activityID && !CRM_Activity_BAO_Activity::checkPermission($activityID, CRM_Core_Action::VIEW)) {
         CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
     }
     $this->assign('contactID', $contactID);
     $this->assign('caseID', $caseID);
     // CRM-9145
     $this->assign('activityID', $activityID);
     $xmlProcessor = new CRM_Case_XMLProcessor_Report();
     $report = $xmlProcessor->getActivityInfo($contactID, $activityID, TRUE);
     $attachmentUrl = CRM_Core_BAO_File::attachmentInfo('civicrm_activity', $activityID);
     if ($attachmentUrl) {
         $report['fields'][] = array('label' => 'Attachment(s)', 'value' => $attachmentUrl, 'type' => 'Link');
     }
     $tags = CRM_Core_BAO_EntityTag::getTag($activityID, 'civicrm_activity');
     if (!empty($tags)) {
         $allTag = CRM_Core_PseudoConstant::get('CRM_Core_DAO_EntityTag', 'tag_id', array('onlyActive' => FALSE));
         foreach ($tags as $tid) {
             $tags[$tid] = $allTag[$tid];
         }
         $report['fields'][] = array('label' => 'Tags', 'value' => implode('<br />', $tags), 'type' => 'String');
     }
     $this->assign('report', $report);
     $latestRevisionID = CRM_Activity_BAO_Activity::getLatestActivityId($activityID);
     $viewPriorActivities = array();
     $priorActivities = CRM_Activity_BAO_Activity::getPriorAcitivities($activityID);
     foreach ($priorActivities as $activityId => $activityValues) {
         if (CRM_Case_BAO_Case::checkPermission($activityId, 'view', NULL, $contactID)) {
             $viewPriorActivities[$activityId] = $activityValues;
         }
     }
     if ($revs) {
         CRM_Utils_System::setTitle(ts('Activity Revision History'));
         $this->assign('revs', $revs);
         $this->assign('result', $viewPriorActivities);
         $this->assign('subject', $activitySubject);
         $this->assign('latestRevisionID', $latestRevisionID);
     } else {
         if (count($viewPriorActivities) > 1) {
             $this->assign('activityID', $activityID);
         }
         if ($latestRevisionID != $activityID) {
             $this->assign('latestRevisionID', $latestRevisionID);
         }
     }
     $parentID = CRM_Activity_BAO_Activity::getParentActivity($activityID);
     if ($parentID) {
         $this->assign('parentID', $parentID);
     }
     //viewing activity should get diplayed in recent list.CRM-4670
     $activityTypeID = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity', $activityID, 'activity_type_id');
     $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
     $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
     $activityTargetContacts = CRM_Activity_BAO_ActivityContact::retrieveContactIdsByActivityId($activityID, $targetID);
     if (!empty($activityTargetContacts)) {
         $recentContactId = $activityTargetContacts[0];
     } else {
         $recentContactId = $contactID;
     }
     if (!isset($caseID)) {
         $caseID = CRM_Core_DAO::getFieldValue('CRM_Case_DAO_CaseActivity', $activityID, 'case_id', 'activity_id');
     }
     $url = CRM_Utils_System::url('civicrm/case/activity/view', "reset=1&aid={$activityID}&cid={$recentContactId}&caseID={$caseID}&context=home");
     $recentContactDisplay = CRM_Contact_BAO_Contact::displayName($recentContactId);
     // add the recently created Activity
     $activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, TRUE);
     $title = "";
     if (isset($activitySubject)) {
         $title = $activitySubject . ' - ';
     }
     $title = $title . $recentContactDisplay . ' (' . $activityTypes[$activityTypeID] . ')';
     $recentOther = array();
     if (CRM_Case_BAO_Case::checkPermission($activityID, 'edit')) {
         $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/case/activity', "reset=1&action=update&id={$activityID}&cid={$recentContactId}&caseid={$caseID}&context=home");
     }
     if (CRM_Case_BAO_Case::checkPermission($activityID, 'delete')) {
         $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/case/activity', "reset=1&action=delete&id={$activityID}&cid={$recentContactId}&caseid={$caseID}&context=home");
     }
     CRM_Utils_Recent::add($title, $url, $activityID, 'Activity', $recentContactId, $recentContactDisplay, $recentOther);
 }
Exemplo n.º 27
0
 /**
  * Delete membership.
  *
  * @param int $membershipId
  *   Membership id that needs to be deleted.
  *
  * @return int
  *   Id of deleted Membership on success, false otherwise.
  */
 public static function deleteMembership($membershipId)
 {
     // CRM-12147, retrieve membership data before we delete it for hooks
     $params = array('id' => $membershipId);
     $memValues = array();
     $memberships = self::getValues($params, $memValues);
     $membership = $memberships[$membershipId];
     CRM_Utils_Hook::pre('delete', 'Membership', $membershipId, $memValues);
     $transaction = new CRM_Core_Transaction();
     $results = NULL;
     //delete activity record
     $activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, FALSE, FALSE, 'name');
     $params = array();
     $deleteActivity = FALSE;
     $membershipActivities = array('Membership Signup', 'Membership Renewal', 'Change Membership Status', 'Change Membership Type', 'Membership Renewal Reminder');
     foreach ($membershipActivities as $membershipActivity) {
         $activityId = array_search($membershipActivity, $activityTypes);
         if ($activityId) {
             $params['activity_type_id'][] = $activityId;
             $deleteActivity = TRUE;
         }
     }
     if ($deleteActivity) {
         $params['source_record_id'] = $membershipId;
         CRM_Activity_BAO_Activity::deleteActivity($params);
     }
     self::deleteMembershipPayment($membershipId);
     $results = $membership->delete();
     $transaction->commit();
     CRM_Utils_Hook::post('delete', 'Membership', $membership->id, $membership);
     // delete the recently created Membership
     $membershipRecent = array('id' => $membershipId, 'type' => 'Membership');
     CRM_Utils_Recent::del($membershipRecent);
     return $results;
 }
Exemplo n.º 28
0
 /**
  * @param $from
  * @param $body
  * @param null $to
  * @param int $trackID
  *
  * @return self|null|object
  * @throws CRM_Core_Exception
  */
 public function processInbound($from, $body, $to = NULL, $trackID = NULL)
 {
     $formatFrom = $this->formatPhone($this->stripPhone($from), $like, "like");
     $escapedFrom = CRM_Utils_Type::escape($formatFrom, 'String');
     $fromContactID = CRM_Core_DAO::singleValueQuery('SELECT contact_id FROM civicrm_phone JOIN civicrm_contact ON civicrm_contact.id = civicrm_phone.contact_id WHERE !civicrm_contact.is_deleted AND phone LIKE "%' . $escapedFrom . '"');
     if (!$fromContactID) {
         // unknown mobile sender -- create new contact
         // use fake @mobile.sms email address for new contact since civi
         // requires email or name for all contacts
         $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
         $phoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id');
         $phoneloc = array_search('Home', $locationTypes);
         $phonetype = array_search('Mobile', $phoneTypes);
         $stripFrom = $this->stripPhone($from);
         $contactparams = array('contact_type' => 'Individual', 'email' => array(1 => array('location_type_id' => $phoneloc, 'email' => $stripFrom . '@mobile.sms')), 'phone' => array(1 => array('phone_type_id' => $phonetype, 'location_type_id' => $phoneloc, 'phone' => $stripFrom)));
         $fromContact = CRM_Contact_BAO_Contact::create($contactparams, FALSE, TRUE, FALSE);
         $fromContactID = $fromContact->id;
     }
     if ($to) {
         $to = CRM_Utils_Type::escape($to, 'String');
         $toContactID = CRM_Core_DAO::singleValueQuery('SELECT contact_id FROM civicrm_phone JOIN civicrm_contact ON civicrm_contact.id = civicrm_phone.contact_id WHERE !civicrm_contact.is_deleted AND phone LIKE "%' . $to . '"');
     } else {
         $toContactID = $fromContactID;
     }
     if ($fromContactID) {
         $actStatusIDs = array_flip(CRM_Core_OptionGroup::values('activity_status'));
         $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type', 'Inbound SMS', 'name');
         // note: lets not pass status here, assuming status will be updated by callback
         $activityParams = array('source_contact_id' => $toContactID, 'target_contact_id' => $fromContactID, 'activity_type_id' => $activityTypeID, 'activity_date_time' => date('YmdHis'), 'status_id' => $actStatusIDs['Completed'], 'details' => $body, 'phone_number' => $from);
         if ($trackID) {
             $trackID = CRM_Utils_Type::escape($trackID, 'String');
             $activityParams['result'] = $trackID;
         }
         $result = CRM_Activity_BAO_Activity::create($activityParams);
         CRM_Core_Error::debug_log_message("Inbound SMS recorded for cid={$fromContactID}.");
         return $result;
     }
 }
Exemplo n.º 29
0
 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");
 }
Exemplo n.º 30
0
 /**
  * Process the form after the input has been submitted and validated.
  *
  *
  * @param CRM_Core_Form $form
  *
  * @return void
  */
 public static function postProcess(&$form)
 {
     // check and ensure that
     $thisValues = $form->controller->exportValues($form->getName());
     $fromSmsProviderId = $thisValues['sms_provider_id'];
     // process message template
     if (!empty($thisValues['saveTemplate']) || !empty($thisValues['updateTemplate'])) {
         $messageTemplate = array('msg_text' => $thisValues['sms_text_message'], 'is_active' => TRUE);
         if (!empty($thisValues['saveTemplate'])) {
             $messageTemplate['msg_title'] = $thisValues['saveTemplateName'];
             CRM_Core_BAO_MessageTemplate::add($messageTemplate);
         }
         if (!empty($thisValues['template']) && !empty($thisValues['updateTemplate'])) {
             $messageTemplate['id'] = $thisValues['template'];
             unset($messageTemplate['msg_title']);
             CRM_Core_BAO_MessageTemplate::add($messageTemplate);
         }
     }
     // format contact details array to handle multiple sms from same contact
     $formattedContactDetails = array();
     $tempPhones = array();
     foreach ($form->_contactIds as $key => $contactId) {
         $phone = $form->_toContactPhone[$key];
         if ($phone) {
             $phoneKey = "{$contactId}::{$phone}";
             if (!in_array($phoneKey, $tempPhones)) {
                 $tempPhones[] = $phoneKey;
                 if (!empty($form->_contactDetails[$contactId])) {
                     $formattedContactDetails[] = $form->_contactDetails[$contactId];
                 }
             }
         }
     }
     // $smsParams carries all the arguments provided on form (or via hooks), to the provider->send() method
     // this gives flexibity to the users / implementors to add their own args via hooks specific to their sms providers
     $smsParams = $thisValues;
     unset($smsParams['sms_text_message']);
     $smsParams['provider_id'] = $fromSmsProviderId;
     $contactIds = array_keys($form->_contactDetails);
     $allContactIds = array_keys($form->_allContactDetails);
     list($sent, $activityId, $countSuccess) = CRM_Activity_BAO_Activity::sendSMS($formattedContactDetails, $thisValues, $smsParams, $contactIds);
     if ($countSuccess > 0) {
         CRM_Core_Session::setStatus(ts('One message was sent successfully.', array('plural' => '%count messages were sent successfully.', 'count' => $countSuccess)), ts('Message Sent', array('plural' => 'Messages Sent', 'count' => $countSuccess)), 'success');
     }
     if (is_array($sent)) {
         // At least one PEAR_Error object was generated.
         // Display the error messages to the user.
         $status = '<ul>';
         foreach ($sent as $errMsg) {
             $status .= '<li>' . $errMsg . '</li>';
         }
         $status .= '</ul>';
         CRM_Core_Session::setStatus($status, ts('One Message Not Sent', array('count' => count($sent), 'plural' => '%count Messages Not Sent')), 'info');
     } else {
         //Display the name and number of contacts for those sms is not sent.
         $smsNotSent = array_diff_assoc($allContactIds, $contactIds);
         if (!empty($smsNotSent)) {
             $not_sent = array();
             foreach ($smsNotSent as $index => $contactId) {
                 $displayName = $form->_allContactDetails[$contactId]['display_name'];
                 $phone = $form->_allContactDetails[$contactId]['phone'];
                 $contactViewUrl = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$contactId}");
                 $not_sent[] = "<a href='{$contactViewUrl}' title='{$phone}'>{$displayName}</a>";
             }
             $status = '(' . ts('because no phone number on file or communication preferences specify DO NOT SMS or Contact is deceased');
             if (CRM_Utils_System::getClassName($form) == 'CRM_Activity_Form_Task_SMS') {
                 $status .= ' ' . ts("or the contact is not part of the activity '%1'", array(1 => self::RECIEVED_SMS_ACTIVITY_SUBJECT));
             }
             $status .= ')<ul><li>' . implode('</li><li>', $not_sent) . '</li></ul>';
             CRM_Core_Session::setStatus($status, ts('One Message Not Sent', array('count' => count($smsNotSent), 'plural' => '%count Messages Not Sent')), 'info');
         }
     }
 }