/**
  * 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);
 }
 function testProjectRetrieveByID()
 {
     $project = CRM_Core_DAO::createTestObject('CRM_Volunteer_BAO_Project');
     $this->assertObjectHasAttribute('id', $project, 'Failed to prepopulate Volunteer Project');
     $projectRetrieved = CRM_Volunteer_BAO_Project::retrieveByID($project->id);
     // note: a strict comparison doesn't work: the first value is an int and the
     // second is a string; not sure where this occurs, but seems worth a look...
     $this->assertTrue($project->id == $projectRetrieved->id, 'CRM_Volunteer_BAO_Project::retrieveByID failed');
 }
 /**
  * Builds the page.
  */
 public function run()
 {
     $this->projectId = CRM_Utils_Request::retrieve('project_id', 'Positive', CRM_Core_DAO::$_nullObject, TRUE);
     $this->project = CRM_Volunteer_BAO_Project::retrieveByID($this->projectId);
     CRM_Utils_System::setTitle(ts('Volunteer Roster for %1', array(1 => $this->project->title, 'domain' => 'org.civicrm.volunteer')));
     $this->fetchAssignments();
     $sortedAssignments = $this->getAssignmentsGroupedByTime();
     $this->assign('sortedResults', $sortedAssignments);
     if (!count($sortedAssignments)) {
         CRM_Core_Session::setStatus(ts('No volunteers have been assigned to this project yet!', array('domain' => 'org.civicrm.volunteer')), '', 'no-popup');
     }
     $this->todaysDate = new DateTime();
     $this->todaysDate->setTime(0, 0, 0);
     // just the date.
     $this->assign('endDate', $this->todaysDate->format('Y-m-d'));
     CRM_Core_Resources::singleton()->addScriptFile('org.civicrm.volunteer', 'js/roster.js', 0, 'html-header');
     parent::run();
 }
/**
 * Callback for core Activity view and form
 *
 * Display user-friendly label for Need ID rather than an integer, or hide
 * the field altogether, depending on context.
 */
function _volunteer_civicrm_buildForm_CRM_Activity_Form_Activity($formName, &$form)
{
    // determine name that the Volunteer Need ID field would be given in this form
    $custom_group = CRM_Volunteer_BAO_Assignment::getCustomGroup();
    $custom_fields = CRM_Volunteer_BAO_Assignment::getCustomFields();
    $group_id = $custom_group['id'];
    $field_id = $custom_fields['volunteer_need_id']['id'];
    // element name varies depending on context
    $possible_element_names = array('custom_' . $field_id . '_1', 'custom_' . $field_id . '_-1');
    $element_name = NULL;
    foreach ($possible_element_names as $name) {
        if ($form->elementExists($name)) {
            $element_name = $name;
            break;
        }
    }
    // If it contains the Volunteer Need ID field, this is an edit form
    if (isset($element_name)) {
        $field = $form->getElement($element_name);
        $form->removeElement($element_name);
        // If need_id isn't set, do not re-add need_id field as a dropdown.
        // See http://issues.civicrm.org/jira/browse/VOL-24?focusedCommentId=53836#comment-53836
        if ($need_id = $field->_attributes['value']) {
            $need = civicrm_api3('VolunteerNeed', 'getsingle', array('id' => $need_id, 'return' => 'project_id'));
            $Project = CRM_Volunteer_BAO_Project::retrieveByID($need['project_id']);
            $needs = array();
            foreach ($Project->needs as $key => $value) {
                $needs[$key] = $value['role_label'] . ': ' . $value['display_time'];
            }
            asort($needs);
            $form->add('select', $element_name, $field->_label, $needs, TRUE);
        }
    } elseif (isset($form->_activityTypeName) && $form->_activityTypeName == 'Volunteer') {
        $custom = $form->get_template_vars('viewCustomData');
        if (!empty($custom[$group_id])) {
            $index = key($custom[$group_id]);
            if (!empty($custom[$group_id][$index]['fields'][$field_id]['field_value'])) {
                $value =& $custom[$group_id][$index]['fields'][$field_id]['field_value'];
                $need = civicrm_api3('VolunteerNeed', 'getsingle', array('id' => $value));
                $value = $need['role_label'] . ': ' . $need['display_time'];
                $form->assign('viewCustomData', $custom);
            }
        }
    }
}
 /**
  * Function to set variables up before form is built
  *
  * @access public
  */
 function preProcess()
 {
     // VOL-71: permissions check is moved from XML to preProcess function to support
     // permissions-challenged Joomla instances
     if (CRM_Core_Config::singleton()->userPermissionClass->isModulePermissionSupported() && !CRM_Volunteer_Permission::check('register to volunteer')) {
         CRM_Utils_System::permissionDenied();
     }
     $vid = CRM_Utils_Request::retrieve('vid', 'Positive', $this, TRUE);
     $this->_project = CRM_Volunteer_BAO_Project::retrieveByID($vid);
     $this->setDestination();
     $this->assign('vid', $this->_project->id);
     if (empty($this->_project->needs)) {
         CRM_Core_Error::fatal('Project has no public volunteer needs enabled');
     }
     $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE);
     // current mode
     $this->_mode = $this->_action == CRM_Core_Action::PREVIEW ? 'test' : 'live';
     // get profile id
     try {
         $this->_ufgroup_id = civicrm_api3('UFGroup', 'getvalue', array('name' => 'volunteer_sign_up', 'return' => 'id'));
     } catch (Exception $e) {
         CRM_Core_Error::fatal('CiviVolunteer custom profile could not be found');
     }
 }
 /**
  * Creates a volunteer activity
  *
  * Wrapper around activity create API. Volunteer field names are translated
  * to the custom_n format expected by the API. Key volunteer_need_id is
  * required in the params array.
  *
  * @param array $params An assoc array of name/value pairs
  * @return mixed Boolean FALSE on failure; activity_id on success
  */
 public static function createVolunteerActivity(array $params)
 {
     if (empty($params['id']) && empty($params['volunteer_need_id'])) {
         CRM_Core_Error::fatal('Mandatory key missing from params array: volunteer_need_id');
     }
     // Set default date role & duration if need is specified
     if (!empty($params['volunteer_need_id'])) {
         $need = civicrm_api3('volunteer_need', 'getsingle', array('id' => $params['volunteer_need_id']));
         $params['volunteer_role_id'] = CRM_Utils_Array::value('volunteer_role_id', $params, CRM_Utils_Array::value('role_id', $need));
         $params['time_scheduled_minutes'] = CRM_Utils_Array::value('time_scheduled_minutes', $params, CRM_Utils_Array::value('duration', $need));
         $projectContact = civicrm_api3('VolunteerProjectContact', 'get', array('project_id' => $need['project_id'], 'relationship_type_id' => 'volunteer_beneficiary'));
         foreach ($projectContact['values'] as $pc) {
             $params['target_contact_id'][] = $pc['contact_id'];
         }
         // Look up the base entity (e.g. event) as a fallback default
         if ((empty($need['start_time']) || empty($params['subject'])) && empty($params['id'])) {
             $project = CRM_Volunteer_BAO_Project::retrieveByID($need['project_id']);
             if (empty($params['activity_date_time']) && empty($params['id'])) {
                 // if the related entity doesn't provide a good default, use tomorrow
                 $tomorrow = date('Y-m-d H:i:s', strtotime('tomorrow'));
                 $params['activity_date_time'] = CRM_Utils_Array::value('start_time', $project->getEntityAttributes(), $tomorrow);
             }
             if (empty($params['subject']) && empty($params['id'])) {
                 $params['subject'] = $project->title;
             }
         }
     }
     // Might as well sync these, but seems redundant
     if (!isset($params['duration']) && isset($params['time_completed_minutes'])) {
         $params['duration'] = $params['time_completed_minutes'];
     }
     $params['activity_type_id'] = self::getActivityTypeId();
     foreach (self::getCustomFields() as $fieldName => $field) {
         if (isset($params[$fieldName])) {
             $params['custom_' . $field['id']] = $params[$fieldName];
             unset($params[$fieldName]);
         }
     }
     $activity = civicrm_api3('Activity', 'create', $params);
     if (!empty($activity['id'])) {
         return $activity['id'];
     }
     return FALSE;
 }
 /**
  * Set default values for the Activity about to be created/updated.
  *
  * Called from self::createVolunteerActivity(), which checks for the existence
  * of necessary params; thus, no such checks are performed here.
  *
  * @param array $params
  *   @see self::createVolunteerActivity()
  * @return array
  *   Default parameters to use for api.activity.create
  */
 private static function setActivityDefaults(array $params)
 {
     $defaults = array();
     $op = empty($params['id']) ? CRM_Core_Action::ADD : CRM_Core_Action::UPDATE;
     $need = civicrm_api3('volunteer_need', 'getsingle', array('id' => $params['volunteer_need_id']));
     $project = CRM_Volunteer_BAO_Project::retrieveByID($need['project_id']);
     $defaults['campaign_id'] = $project ? $project->campaign_id : '';
     // Force NULL campaign ids to be empty strings, since the API ignores NULL values.
     if (empty($defaults['campaign_id'])) {
         $defaults['campaign_id'] = '';
     }
     if ($op === CRM_Core_Action::ADD) {
         $defaults['volunteer_role_id'] = CRM_Utils_Array::value('role_id', $need);
         $defaults['time_scheduled_minutes'] = CRM_Utils_Array::value('duration', $need);
         $defaults['target_contact_id'] = CRM_Volunteer_BAO_Project::getContactsByRelationship($project->id, 'volunteer_beneficiary');
         // If the related entity doesn't provide a good default, use tomorrow.
         if (empty($params['activity_date_time'])) {
             $tomorrow = date('Y-m-d H:i:s', strtotime('tomorrow'));
             $defaults['activity_date_time'] = CRM_Utils_Array::value('start_time', $project->getEntityAttributes(), $tomorrow);
         }
         if (empty($params['subject'])) {
             $defaults['subject'] = $project->title;
         }
     }
     return $defaults;
 }
 /**
  * set variables up before form is built
  *
  * @access public
  */
 function preProcess()
 {
     // VOL-71: permissions check is moved from XML to preProcess function to support
     // permissions-challenged Joomla instances
     if (CRM_Core_Config::singleton()->userPermissionClass->isModulePermissionSupported() && !CRM_Volunteer_Permission::check('register to volunteer')) {
         CRM_Utils_System::permissionDenied();
     }
     $vid = CRM_Utils_Request::retrieve('vid', 'Positive', $this, TRUE);
     $this->_project = CRM_Volunteer_BAO_Project::retrieveByID($vid);
     $this->setDestination();
     $this->assign('vid', $this->_project->id);
     if (empty($this->_project->needs)) {
         CRM_Core_Error::fatal('Project has no public volunteer needs enabled');
     }
     $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE);
     // current mode
     $this->_mode = $this->_action == CRM_Core_Action::PREVIEW ? 'test' : 'live';
 }
 /**
  * Set $this->_destination, the URL to which the user should be redirected
  * after successfully submitting the sign-up form
  */
 protected function setDestination()
 {
     $path = $query = $fragment = NULL;
     $dest = CRM_Utils_Request::retrieve('dest', 'String', $this, FALSE);
     switch ($dest) {
         case 'event':
             // If only one project is associated with the form, send the user back
             // to that event form; otherwise, default to the vol opps page.
             if (count($this->projectIds) === 1) {
                 $eventId = CRM_Volunteer_BAO_Project::retrieveByID($this->projectIds[0])->entity_id;
                 $path = 'civicrm/event/info';
                 $query = "reset=1&id={$eventId}";
                 break;
             }
         case 'list':
         default:
             $path = 'civicrm/a/';
             $fragment = '/volunteer/opportunities';
     }
     $this->_destination = CRM_Utils_System::url($path, $query, FALSE, $fragment);
 }