예제 #1
0
 /**
  * Set variables up before form is built.
  *
  * @return void
  */
 public function preProcess()
 {
     parent::preProcess();
     $setTab = CRM_Utils_Request::retrieve('setTab', 'Int', $this, FALSE, 0);
     $mapping = CRM_Utils_Array::first(CRM_Core_BAO_ActionSchedule::getMappings(array('id' => $this->_isTemplate ? CRM_Event_ActionMapping::EVENT_TPL_MAPPING_ID : CRM_Event_ActionMapping::EVENT_NAME_MAPPING_ID)));
     $reminderList = CRM_Core_BAO_ActionSchedule::getList(FALSE, $mapping, $this->_id);
     if ($reminderList && is_array($reminderList)) {
         // Add action links to each of the reminders
         foreach ($reminderList as &$format) {
             $action = CRM_Core_Action::UPDATE + CRM_Core_Action::DELETE;
             if ($format['is_active']) {
                 $action += CRM_Core_Action::DISABLE;
             } else {
                 $action += CRM_Core_Action::ENABLE;
             }
             $scheduleReminder = new CRM_Admin_Page_ScheduleReminders();
             $links = $scheduleReminder->links();
             $links[CRM_Core_Action::DELETE]['qs'] .= "&context=event&compId={$this->_id}";
             $links[CRM_Core_Action::UPDATE]['qs'] .= "&context=event&compId={$this->_id}";
             $format['action'] = CRM_Core_Action::formLink($links, $action, array('id' => $format['id']), ts('more'), FALSE, 'actionSchedule.manage.action', 'ActionSchedule', $this->_id);
         }
     }
     $this->assign('rows', $reminderList);
     $this->assign('setTab', $setTab);
     $this->assign('component', 'event');
     // Update tab "disabled" css class
     $this->ajaxResponse['tabValid'] = is_array($reminderList) && count($reminderList) > 0;
     $this->setPageTitle(ts('Scheduled Reminder'));
 }
예제 #2
0
/**
 * HRJobContract.get API
 *
 * @param array $params
 * @return array API result descriptor
 * @throws API_Exception
 */
function civicrm_api3_h_r_job_contract_get($params)
{
    $returnFields = array();
    if (!empty($params['return'])) {
        if (is_array($params['return'])) {
            $returnFields = $params['return'];
        } else {
            $returnFields = explode(',', $params['return']);
        }
    }
    $contracts = _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
    foreach ($contracts['values'] as $key => $contract) {
        $isCurrent = true;
        $contractDetails = civicrm_api3('HRJobDetails', 'get', array('sequential' => 1, 'jobcontract_id' => $contract['id']));
        $details = CRM_Utils_Array::first($contractDetails['values']);
        if (!empty($details['period_end_date'])) {
            if ($details['period_end_date'] < date('Y-m-d')) {
                $isCurrent = false;
            }
        }
        $contracts['values'][$key]['is_current'] = (int) $isCurrent;
        foreach ($returnFields as $returnField) {
            if (!empty($details[$returnField])) {
                $contracts['values'][$key][$returnField] = $details[$returnField];
            }
        }
    }
    return $contracts;
}
예제 #3
0
파일: OpenCase.php 프로젝트: kidaa30/yes
 /**
  * @param CRM_Core_Form $form
  */
 public static function preProcess(&$form)
 {
     //get multi client case configuration
     $xmlProcessorProcess = new CRM_Case_XMLProcessor_Process();
     $form->_allowMultiClient = (bool) $xmlProcessorProcess->getAllowMultipleCaseClients();
     if ($form->_context == 'caseActivity') {
         $contactID = CRM_Utils_Request::retrieve('cid', 'Positive', $form);
         $atype = CRM_Core_OptionGroup::getValue('activity_type', 'Change Case Start Date', 'name');
         $caseId = CRM_Utils_Array::first($form->_caseId);
         $form->assign('changeStartURL', CRM_Utils_System::url('civicrm/case/activity', "action=add&reset=1&cid={$contactID}&caseid={$caseId}&atype={$atype}"));
         return;
     }
     $form->_context = CRM_Utils_Request::retrieve('context', 'String', $form);
     $form->_contactID = CRM_Utils_Request::retrieve('cid', 'Positive', $form);
     $form->assign('context', $form->_context);
     // check if the case type id passed in url is a valid one
     $caseTypeId = CRM_Utils_Request::retrieve('ctype', 'Positive', $form);
     $caseTypes = CRM_Case_PseudoConstant::caseType();
     $form->_caseTypeId = array_key_exists($caseTypeId, $caseTypes) ? $caseTypeId : NULL;
     // check if the case status id passed in url is a valid one
     $caseStatusId = CRM_Utils_Request::retrieve('case_status_id', 'Positive', $form);
     $caseStatus = CRM_Case_PseudoConstant::caseStatus();
     $form->_caseStatusId = array_key_exists($caseStatusId, $caseStatus) ? $caseStatusId : NULL;
     // Add attachments
     CRM_Core_BAO_File::buildAttachment($form, 'civicrm_activity', $form->_activityId);
     $session = CRM_Core_Session::singleton();
     $session->pushUserContext(CRM_Utils_System::url('civicrm/case', 'reset=1'));
 }
예제 #4
0
 /**
  * Create a new HRJobDetails based on array-data
  *
  * @param array $params key-value pairs
  * @return CRM_HRJob_DAO_HRJobDetails|NULL
  *
  */
 public static function create($params)
 {
     $hook = empty($params['id']) ? 'create' : 'edit';
     $previousDetailsRevisionId = null;
     if ($hook == 'create') {
         $previousRevisionResult = civicrm_api3('HRJobContractRevision', 'getcurrentrevision', array('sequential' => 1, 'jobcontract_id' => $params['jobcontract_id']));
         if (!empty($previousRevisionResult['values']['details_revision_id'])) {
             $previousDetailsRevisionId = $previousRevisionResult['values']['details_revision_id'];
         }
     }
     $instance = parent::create($params);
     // setting 'effective_date' if it's not set:
     $revision = civicrm_api3('HRJobContractRevision', 'get', array('sequential' => 1, 'jobcontract_id' => $params['jobcontract_id'], 'id' => $instance->jobcontract_revision_id));
     if (!empty($revision['values'][0])) {
         $revisionData = array_shift($revision['values']);
         if (!$revisionData['effective_date']) {
             civicrm_api3('HRJobContractRevision', 'create', array('id' => $revisionData['id'], 'effective_date' => $instance->period_start_date));
         }
     }
     $revisionResult = civicrm_api3('HRJobContractRevision', 'get', array('sequential' => 1, 'id' => $instance->jobcontract_revision_id));
     $revision = CRM_Utils_Array::first($revisionResult['values']);
     $duplicate = CRM_Utils_Array::value('action', $params, $hook);
     if ($hook == 'create' && empty($revision['role_revision_id']) && $duplicate != 'duplicate' && empty($params['import'])) {
         //civicrm_api3('HRJobRole', 'create', array('jobcontract_id' => $revision['jobcontract_id'],'title' => $instance->title, 'location'=> $instance->location, 'percent_pay_role' => 100, 'jobcontract_revision_id' => $instance->jobcontract_revision_id));
         CRM_Hrjobcontract_BAO_HRJobRole::create(array('jobcontract_id' => $revision['jobcontract_id'], 'title' => $instance->title, 'location' => $instance->location, 'percent_pay_role' => 100, 'jobcontract_revision_id' => $instance->jobcontract_revision_id));
     }
     if ($previousDetailsRevisionId) {
         CRM_Core_BAO_File::copyEntityFile('civicrm_hrjobcontract_details', $previousDetailsRevisionId, 'civicrm_hrjobcontract_details', $revision['details_revision_id']);
     }
     $contract = new CRM_Hrjobcontract_DAO_HRJobContract();
     $contract->id = $revision['jobcontract_id'];
     $contract->find(true);
     CRM_Hrjobcontract_JobContractDates::setDates($contract->contact_id, $revision['jobcontract_id'], $instance->period_start_date, $instance->period_end_date);
     return $instance;
 }
예제 #5
0
 /**
  * Test Appraisals API flow including
  * - create Appraisal Cycle
  * - create Appraisals for Appraisal Cycle
  * - modify Appraisals and populate Appraisal Cycle Due Dates into Appraisal Due Dates.
  * - delete Appraisal Cycle and Appraisal
  */
 function testAppraisalsApiFlow()
 {
     $time = time();
     $expected = array();
     $this->quickCleanup(array('civicrm_contact', 'civicrm_appraisal_cycle', 'civicrm_appraisal'));
     ////////// Create Test Contacts ////////////////////////////////////////
     foreach ($this->_contacts as $key => $contact) {
         $result = civicrm_api3('Contact', 'create', array('sequential' => 1, 'contact_type' => "Individual", 'first_name' => $contact['first_name'], 'last_name' => "Appraisal Test Contact", 'email' => $contact['email']));
         $this->_contacts[$key]['id'] = $result['id'];
     }
     $cycleStartDate = $time;
     $cycleEndDate = $time + 30 * self::DAY;
     $selfAppraisalDue = $time + 5 * self::DAY;
     $managerAppraisalDue = $time + 15 * self::DAY;
     $gradeDue = $time + 25 * self::DAY;
     ////////// Create Test Appraisal Cycle 1: //////////////////////////////
     civicrm_api3('AppraisalCycle', 'create', array('sequential' => 1, 'name' => "Test Appraisal Cycle 1", 'cycle_start_date' => date('Y-m-d', $cycleStartDate), 'cycle_end_date' => date('Y-m-d', $cycleEndDate), 'self_appraisal_due' => date('Y-m-d', $selfAppraisalDue), 'manager_appraisal_due' => date('Y-m-d', $managerAppraisalDue), 'grade_due' => date('Y-m-d', $gradeDue), 'type_id' => 1));
     $expected['AppraisalCycle1'] = array('id' => 1, 'name' => "Test Appraisal Cycle 1", 'cycle_start_date' => date('Y-m-d', $cycleStartDate), 'cycle_end_date' => date('Y-m-d', $cycleEndDate), 'self_appraisal_due' => date('Y-m-d', $selfAppraisalDue), 'manager_appraisal_due' => date('Y-m-d', $managerAppraisalDue), 'grade_due' => date('Y-m-d', $gradeDue), 'type_id' => 1);
     $appraisalCycle1 = civicrm_api3('AppraisalCycle', 'get', array('sequential' => 1, 'id' => 1));
     $this->assertAPIArrayComparison(CRM_Utils_Array::first($appraisalCycle1['values']), $expected['AppraisalCycle1']);
     ////////// Create Test Appraisal Cycle 2: //////////////////////////////
     civicrm_api3('AppraisalCycle', 'create', array('sequential' => 1, 'name' => "Test Appraisal Cycle 2", 'cycle_start_date' => date('Y-m-d', $cycleStartDate + 30 * self::DAY), 'cycle_end_date' => date('Y-m-d', $cycleEndDate + 30 * self::DAY), 'self_appraisal_due' => date('Y-m-d', $selfAppraisalDue + 30 * self::DAY), 'manager_appraisal_due' => date('Y-m-d', $managerAppraisalDue + 30 * self::DAY), 'grade_due' => date('Y-m-d', $gradeDue + 30 * self::DAY), 'type_id' => 2));
     $expected['AppraisalCycle2'] = array('id' => 2, 'name' => "Test Appraisal Cycle 2", 'cycle_start_date' => date('Y-m-d', $cycleStartDate + 30 * self::DAY), 'cycle_end_date' => date('Y-m-d', $cycleEndDate + 30 * self::DAY), 'self_appraisal_due' => date('Y-m-d', $selfAppraisalDue + 30 * self::DAY), 'manager_appraisal_due' => date('Y-m-d', $managerAppraisalDue + 30 * self::DAY), 'grade_due' => date('Y-m-d', $gradeDue + 30 * self::DAY), 'type_id' => 2);
     $appraisalCycle2 = civicrm_api3('AppraisalCycle', 'get', array('sequential' => 1, 'id' => 2));
     $this->assertAPIArrayComparison(CRM_Utils_Array::first($appraisalCycle2['values']), $expected['AppraisalCycle2']);
     ////////// Create Test Appraisal 1 for Appraisal Cycle 1: //////////////
     civicrm_api3('Appraisal', 'create', array('sequential' => 1, 'appraisal_cycle_id' => 1, 'contact_id' => $this->_contacts[0]['id'], 'manager_id' => $this->_contacts[2]['id'], 'self_appraisal_file_id' => "", 'manager_appraisal_file_id' => "", 'self_appraisal_due' => "", 'manager_appraisal_due' => "", 'grade_due' => "", 'due_changed' => "0", 'meeting_date' => date('Y-m-d', $cycleEndDate - 2 * self::DAY), 'meeting_completed' => "0", 'approved_by_employee' => "0", 'grade' => "", 'notes' => "Test Notes of Test Appraisal 1", 'status_id' => 1));
     $expected['Appraisal1'] = array("id" => "1", "appraisal_cycle_id" => "1", "contact_id" => "{$this->_contacts[0]['id']}", "manager_id" => "{$this->_contacts[2]['id']}", "self_appraisal_due" => date('Y-m-d', $selfAppraisalDue), "manager_appraisal_due" => date('Y-m-d', $managerAppraisalDue), "grade_due" => date('Y-m-d', $gradeDue), "due_changed" => "0", "meeting_date" => date('Y-m-d', $cycleEndDate - 2 * self::DAY), "meeting_completed" => "0", "approved_by_employee" => "0", "notes" => "Test Notes of Test Appraisal 1", "status_id" => "1");
     $appraisal1 = civicrm_api3('Appraisal', 'get', array('sequential' => 1, 'id' => 1));
     $this->assertAPIArrayComparison(CRM_Utils_Array::first($appraisal1['values']), $expected['Appraisal1']);
     ////////// Create Test Appraisal 2 for Appraisal Cycle 1: //////////////
     civicrm_api3('Appraisal', 'create', array('sequential' => 1, 'appraisal_cycle_id' => 1, 'contact_id' => $this->_contacts[1]['id'], 'manager_id' => $this->_contacts[2]['id'], 'meeting_date' => date('Y-m-d', $cycleEndDate - 2 * self::DAY), 'notes' => "Test Notes of Test Appraisal 2"));
     $expected['Appraisal2'] = array("id" => "2", "appraisal_cycle_id" => "1", "contact_id" => $this->_contacts[1]['id'], "manager_id" => $this->_contacts[2]['id'], "self_appraisal_due" => date('Y-m-d', $selfAppraisalDue), "manager_appraisal_due" => date('Y-m-d', $managerAppraisalDue), "grade_due" => date('Y-m-d', $gradeDue), "due_changed" => "0", "meeting_date" => date('Y-m-d', $cycleEndDate - 2 * self::DAY), "meeting_completed" => "0", "approved_by_employee" => "0", "notes" => "Test Notes of Test Appraisal 2", "status_id" => "1");
     $appraisal2 = civicrm_api3('Appraisal', 'get', array('sequential' => 1, 'id' => 2));
     $this->assertAPIArrayComparison(CRM_Utils_Array::first($appraisal2['values']), $expected['Appraisal2']);
     ////////// Change 'grade_due' for Appraisal 2: /////////////////////////
     civicrm_api3('Appraisal', 'create', array('sequential' => 1, 'id' => 2, 'grade_due' => date('Y-m-d', $gradeDue + 1 * self::DAY)));
     ////////// Change Due Dates for Appraisal Cycle 1: /////////////////////
     civicrm_api3('AppraisalCycle', 'create', array('sequential' => 1, 'id' => 1, "self_appraisal_due" => date('Y-m-d', $selfAppraisalDue + 2 * self::DAY), "manager_appraisal_due" => date('Y-m-d', $managerAppraisalDue + 2 * self::DAY), 'grade_due' => date('Y-m-d', $gradeDue + 2 * self::DAY)));
     // Checking Due Dates for Appraisal 1.
     // They should be changed according to the AppraisalCycle create call above.
     $expected['Appraisal1DueDates'] = array('id' => "1", 'self_appraisal_due' => date('Y-m-d', $selfAppraisalDue + 2 * self::DAY), 'manager_appraisal_due' => date('Y-m-d', $managerAppraisalDue + 2 * self::DAY), 'grade_due' => date('Y-m-d', $gradeDue + 2 * self::DAY));
     $appraisal1DueDates = civicrm_api3('Appraisal', 'get', array('sequential' => 1, 'id' => 1, 'return' => "id,self_appraisal_due,manager_appraisal_due,grade_due"));
     $this->assertAPIArrayComparison(CRM_Utils_Array::first($appraisal1DueDates['values']), $expected['Appraisal1DueDates']);
     // Checking Due Dates for Appraisal 2.
     // They should be unchanged as we've modified individual 'grade_due' date.
     $expected['Appraisal2DueDates'] = array('id' => "2", 'self_appraisal_due' => date('Y-m-d', $selfAppraisalDue), 'manager_appraisal_due' => date('Y-m-d', $managerAppraisalDue), 'grade_due' => date('Y-m-d', $gradeDue + 1 * self::DAY));
     $appraisal2DueDates = civicrm_api3('Appraisal', 'get', array('sequential' => 1, 'id' => 2, 'return' => "id,self_appraisal_due,manager_appraisal_due,grade_due"));
     $this->assertAPIArrayComparison(CRM_Utils_Array::first($appraisal2DueDates['values']), $expected['Appraisal2DueDates']);
     ////////// Delete Appraisal 1: /////////////////////////////////////////
     civicrm_api3('Appraisal', 'delete', array('sequential' => 1, 'id' => 1));
     $this->assertAPIDeleted('Appraisal', 1);
     ////////// Delete Appraisal Cycle 2: /////////////////////////////////////////
     civicrm_api3('AppraisalCycle', 'delete', array('sequential' => 1, 'id' => 2));
     $this->assertAPIDeleted('AppraisalCycle', 2);
 }
예제 #6
0
/**
 * HRJobHour.create API
 *
 * @param array $params
 * @return array API result descriptor
 * @throws API_Exception
 */
function civicrm_api3_h_r_job_hour_create($params)
{
    $result = _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params);
    if (empty($result['is_error'])) {
        $row = CRM_Utils_Array::first($result['values']);
        $revision_id = $row['jobcontract_revision_id'];
        $revision = civicrm_api3('HRJobContractRevision', 'get', array('sequential' => 1, 'id' => $revision_id, 'options' => array('limit' => 1)));
        //CRM_Hrjobcontract_Estimator::updateEstimatesByRevision($revision);
    }
    return $result;
}
예제 #7
0
 /**
  * Create a new HRJobHour based on array-data
  *
  * @param array $params key-value pairs
  * @return CRM_HRJob_DAO_HRJobHour|NULL
  *
  */
 public static function create($params)
 {
     $hook = empty($params['id']) ? 'create' : 'edit';
     $instance = parent::create($params);
     $currentInstanceResult = civicrm_api3('HRJobHour', 'get', array('sequential' => 1, 'id' => $instance->id));
     $currentInstance = CRM_Utils_Array::first($currentInstanceResult['values']);
     $revisionResult = civicrm_api3('HRJobContractRevision', 'get', array('sequential' => 1, 'id' => $currentInstance['jobcontract_revision_id']));
     $revision = CRM_Utils_Array::first($revisionResult['values']);
     if ($hook == 'create' && empty($params['import'])) {
         $result = civicrm_api3('HRJobRole', 'get', array('sequential' => 1, 'jobcontract_revision_id' => $revision['role_revision_id'], 'options' => array('limit' => 1)));
         if (!empty($result['values'])) {
             $role = CRM_Utils_Array::first($result['values']);
             CRM_Hrjobcontract_BAO_HRJobRole::create(array('id' => $role['id'], 'hours' => $instance->hours_amount, 'role_hours_unit' => $instance->hours_unit));
         }
     }
     return $instance;
 }
예제 #8
0
 /**
  * Create a new HRJobPension based on array-data
  *
  * @param array $params key-value pairs
  * @return CRM_HRJob_DAO_HRJobPension|NULL
  * 
  */
 public static function create($params)
 {
     $hook = empty($params['id']) ? 'create' : 'edit';
     $previousPensionRevisionId = null;
     if ($hook == 'create') {
         $previousRevisionResult = civicrm_api3('HRJobContractRevision', 'getcurrentrevision', array('sequential' => 1, 'jobcontract_id' => $params['jobcontract_id']));
         if (!empty($previousRevisionResult['values']['pension_revision_id'])) {
             $previousPensionRevisionId = $previousRevisionResult['values']['pension_revision_id'];
         }
     }
     $instance = parent::create($params);
     $revisionResult = civicrm_api3('HRJobContractRevision', 'get', array('sequential' => 1, 'id' => $instance->jobcontract_revision_id));
     $revision = CRM_Utils_Array::first($revisionResult['values']);
     if ($previousPensionRevisionId) {
         CRM_Core_BAO_File::copyEntityFile('civicrm_hrjobcontract_pension', $previousPensionRevisionId, 'civicrm_hrjobcontract_pension', $revision['pension_revision_id']);
     }
     return $instance;
 }
예제 #9
0
 /**
  * Create a new HRJobHour based on array-data
  *
  * @param array $params key-value pairs
  * @return CRM_HRJob_DAO_HRJobHour|NULL
  *
  */
 public static function create($params)
 {
     $className = 'CRM_HRJob_DAO_HRJobHour';
     $entityName = 'HRJobHour';
     $hook = empty($params['id']) ? 'create' : 'edit';
     CRM_Utils_Hook::pre($hook, $entityName, CRM_Utils_Array::value('id', $params), $params);
     $instance = new $className();
     $instance->copyValues($params);
     $instance->save();
     if ($hook == 'create') {
         $result = civicrm_api3('HRJobRole', 'get', array('sequential' => 1, 'job_id' => $instance->job_id, 'options' => array('limit' => 1)));
         if (!empty($result['values'])) {
             $role = CRM_Utils_Array::first($result['values']);
             civicrm_api3('HRJobRole', 'update', array('id' => $role['id'], 'job_id' => $role['job_id'], 'hours' => $instance->hours_amount, 'role_hours_unit' => $instance->hours_unit));
         }
     }
     CRM_Utils_Hook::post($hook, $entityName, $instance->id, $instance);
     return $instance;
 }
예제 #10
0
 /**
  * Test whether Domain.create returns a correct value for domain_version.
  *
  * See CRM-17430.
  */
 public function testCreateDomainResult()
 {
     // First create a domain.
     $domain_result = $this->callAPISuccess('Domain', 'create', $this->params);
     $result_value = CRM_Utils_Array::first($domain_result['values']);
     // Check for domain_version in create result.
     $this->assertEquals($this->params['domain_version'], $result_value['domain_version']);
 }
예제 #11
0
 /**
  * Global validation rules for the form.
  *
  * @param array $values
  *   Posted values of the form.
  *
  * @param $files
  * @param CRM_Core_Form $form
  *
  * @return array
  *   list of errors to be posted back to the form
  */
 public static function formRule($values, $files, $form)
 {
     $errors = array();
     $linkCaseId = CRM_Utils_Array::value('link_to_case_id', $values);
     assert('is_numeric($linkCaseId)');
     if ($linkCaseId == CRM_Utils_Array::first($form->_caseId)) {
         $errors['link_to_case'] = ts('Please select some other case to link.');
     }
     // do check for existing related cases.
     $relatedCases = $form->get('relatedCases');
     if (is_array($relatedCases) && array_key_exists($linkCaseId, $relatedCases)) {
         $errors['link_to_case'] = ts('Selected case is already linked.');
     }
     return empty($errors) ? TRUE : $errors;
 }
예제 #12
0
 /**
  * Ensure that the return values comply with the whitelist's
  * "fields" policy.
  *
  * Most API's follow a convention where the result includes
  * a 'values' array (which in turn is a list of records). Unfortunately,
  * some don't. If the API result doesn't meet our expectation,
  * then we probably don't know what's going on, so we abort the
  * request.
  *
  * This will probably break some of the layered-sugar APIs (like
  * getsingle, getvalue). Just use the meat-and-potatoes API instead.
  * Or craft a suitably targeted patch.
  *
  * @param array $apiRequest
  *   API request.
  * @param array $apiResult
  *   API result.
  * @return array
  *   Modified API result.
  * @throws \API_Exception
  */
 public function filter($apiRequest, $apiResult)
 {
     if ($this->fields === '*') {
         return $apiResult;
     }
     if (isset($apiResult['values']) && empty($apiResult['values'])) {
         // No data; filtering doesn't matter.
         return $apiResult;
     }
     if (is_array($apiResult['values'])) {
         $firstRow = \CRM_Utils_Array::first($apiResult['values']);
         if (is_array($firstRow)) {
             $fields = $this->filterFields(array_keys($firstRow));
             $apiResult['values'] = \CRM_Utils_Array::filterColumns($apiResult['values'], $fields);
             return $apiResult;
         }
     }
     throw new \API_Exception(sprintf('Filtering failed for %s.%s. Unrecognized result format.', $apiRequest['entity'], $apiRequest['action']));
 }
예제 #13
0
/**
 * Implementation of hook_civicrm_uninstall
 *
 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_uninstall
 */
function hrjobcontract_civicrm_uninstall()
{
    $subTypeInfo = CRM_Contact_BAO_ContactType::subTypeInfo('Organization');
    $sub_type_name = array('Health Insurance Provider', 'Life Insurance Provider');
    foreach ($sub_type_name as $sub_type_name) {
        $subTypeName = ucfirst(CRM_Utils_String::munge($sub_type_name));
        $orid = array_key_exists($subTypeName, $subTypeInfo);
        if ($orid) {
            $id = $subTypeInfo[$subTypeName]['id'];
            CRM_Contact_BAO_ContactType::del($id);
        }
    }
    $jobContractMenu = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Navigation', 'job_contracts', 'id', 'name');
    if (!empty($jobContractMenu)) {
        CRM_Core_BAO_Navigation::processDelete($jobContractMenu);
    }
    CRM_Core_DAO::executeQuery("DELETE FROM civicrm_navigation WHERE name IN ('job_contracts', 'import_export_job_contracts', 'jobImport', 'hoursType', 'pay_scale','hours_location', 'hrjc_contact_type', 'hrjc_location', 'hrjc_pay_cycle', 'hrjc_benefit_name', 'hrjc_benefit_type', 'hrjc_deduction_name', 'hrjc_deduction_type', 'hrjc_health_provider', 'hrjc_life_provider', 'hrjc_pension_type', 'hrjc_revision_change_reason')");
    CRM_Core_BAO_Navigation::resetNavigation();
    //delete custom groups and field
    $customGroup = civicrm_api3('CustomGroup', 'get', array('name' => "HRJobContract_Summary"));
    $customGroupData = CRM_Utils_Array::first($customGroup['values']);
    if (!empty($customGroupData['id'])) {
        civicrm_api3('CustomGroup', 'delete', array('id' => $customGroupData['id']));
    }
    $customGroup = civicrm_api3('CustomGroup', 'get', array('name' => "HRJobContract_Summary"));
    $customGroupData = CRM_Utils_Array::first($customGroup['values']);
    if (!empty($customGroupData['id'])) {
        civicrm_api3('CustomGroup', 'delete', array('id' => $customGroupData['id']));
    }
    //delete all option group and values
    CRM_Core_DAO::executeQuery("DELETE FROM civicrm_option_group WHERE name IN ('job_contracts', 'hoursType', 'pay_scale','hours_location', 'hrjc_contact_type', 'hrjc_location', 'hrjc_pay_cycle', 'hrjc_benefit_name', 'hrjc_benefit_type', 'hrjc_deduction_name', 'hrjc_deduction_type', 'hrjc_health_provider', 'hrjc_life_provider', 'hrjc_pension_type', 'hrjc_revision_change_reason', 'hrjc_contract_type', 'hrjc_level_type', 'hrjc_department', 'hrjc_hours_type', 'hrjc_pay_grade', 'hrjc_health_provider', 'hrjc_life_provider', 'hrjc_location', 'hrjc_pension_type', 'hrjc_region', 'hrjc_pay_scale')");
    //delete job contract files to entities relations
    CRM_Core_DAO::executeQuery("DELETE FROM civicrm_entity_file WHERE entity_table LIKE 'civicrm_hrjobcontract_%'");
    return _hrjobcontract_civix_civicrm_uninstall();
}
예제 #14
0
/**
 * Sends a template.
 *
 * @param array $params
 */
function civicrm_api3_message_template_send($params)
{
    // Change external param names to internal ones
    $fieldSpec = array();
    _civicrm_api3_message_template_send_spec($fieldSpec);
    foreach ($fieldSpec as $field => $spec) {
        if (isset($spec['api.aliases']) && array_key_exists($field, $params)) {
            $params[CRM_Utils_Array::first($spec['api.aliases'])] = $params[$field];
            unset($params[$field]);
        }
    }
    if (empty($params['messageTemplateID'])) {
        if (empty($params['groupName']) || empty($params['valueName'])) {
            // Can't use civicrm_api3_verify_mandatory for this because it would give the wrong field names
            throw new API_Exception("Mandatory key(s) missing from params array: requires id or option_group_name + option_value_name", "mandatory_missing", array("fields" => array('id', 'option_group_name', 'option_value_name')));
        }
    }
    CRM_Core_BAO_MessageTemplate::sendTemplate($params);
}
예제 #15
0
/**
 * HRJobContract implementation of the "replace" action.
 *
 * Replace the old set of entities (matching some given keys) with a new set of
 * entities (matching the same keys).
 *
 * Note: This will verify that 'values' is present, but it does not directly verify
 * any other parameters.
 *
 * @param string $entity entity name
 * @param array $params params from civicrm_api, including:
 *   - 'values': an array of records to save
 *   - all other items: keys which identify new/pre-existing records
 * @return array|int
 */
function _civicrm_hrjobcontract_api3_replace($entity, $params, $forceRevisionId = null)
{
    $transaction = new CRM_Core_Transaction();
    try {
        if (!is_array($params['values'])) {
            throw new Exception("Mandatory key(s) missing from params array: values");
        }
        // Extract the keys -- somewhat scary, don't think too hard about it
        $baseParams = _civicrm_api3_generic_replace_base_params($params);
        // Lookup pre-existing records
        $preexisting = civicrm_api($entity, 'get', $baseParams, $params);
        if (civicrm_error($preexisting)) {
            $transaction->rollback();
            return $preexisting;
        }
        // Save the new/updated records
        $jobcontractRevisionId = null;
        $creates = array();
        foreach ($params['values'] as $replacement) {
            if (empty($replacement['id']) && empty($replacement['jobcontract_revision_id'])) {
                $replacement['jobcontract_revision_id'] = $jobcontractRevisionId;
            }
            if ($forceRevisionId) {
                $replacement['jobcontract_revision_id'] = $forceRevisionId;
            }
            // Sugar: Don't force clients to duplicate the 'key' data
            $replacement = array_merge($baseParams, $replacement);
            //$action      = (isset($replacement['id']) || isset($replacement[$entity . '_id'])) ? 'update' : 'create';
            $action = 'create';
            $create = civicrm_api($entity, $action, $replacement);
            if (civicrm_error($create)) {
                $transaction->rollback();
                return $create;
            }
            foreach ($create['values'] as $entity_id => $entity_value) {
                $creates[$entity_id] = $entity_value;
            }
            $entityData = CRM_Utils_Array::first($create['values']);
            $jobcontractRevisionId = $entityData['jobcontract_revision_id'];
        }
        // Remove stale records
        $staleIDs = array_diff(array_keys($preexisting['values']), array_keys($creates));
        foreach ($staleIDs as $staleID) {
            $delete = civicrm_api($entity, 'delete', array('version' => $params['version'], 'id' => $staleID));
            if (civicrm_error($delete)) {
                $transaction->rollback();
                return $delete;
            }
        }
        return civicrm_api3_create_success($creates, $params);
    } catch (PEAR_Exception $e) {
        $transaction->rollback();
        return civicrm_api3_create_error($e->getMessage());
    } catch (Exception $e) {
        $transaction->rollback();
        return civicrm_api3_create_error($e->getMessage());
    }
}
예제 #16
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);
 }
예제 #17
0
/**
 * Get function for query object api.
 *
 * This is a simple get function, but it should be usable for any kind of
 * entity. I created it to work around CRM-16036.
 *
 * @param string $dao_name
 *   Name of DAO
 * @param array $params
 *   As passed into api get function.
 * @param bool $isFillUniqueFields
 *   Do we need to ensure unique fields continue to be populated for this api? (backward compatibility).
 * @param CRM_Utils_SQL_Select|NULL $sqlFragment
 *
 * @return array
 */
function _civicrm_api3_get_using_utils_sql($dao_name, $params, $isFillUniqueFields, $sqlFragment)
{
    $dao = new $dao_name();
    $entity = _civicrm_api_get_entity_name_from_dao($dao);
    $custom_fields = _civicrm_api3_custom_fields_for_entity($entity);
    $options = _civicrm_api3_get_options_from_params($params);
    // Unset $params['options'] if they are api parameters (not options as a fieldname).
    if (!empty($params['options']) && is_array($params['options']) && array_intersect(array_keys($params['options']), array_keys($options))) {
        unset($params['options']);
    }
    $entity_field_names = _civicrm_api3_field_names(_civicrm_api3_build_fields_array($dao));
    $custom_field_names = array();
    $uniqueAliases = array();
    $getFieldsResult = civicrm_api3($entity, 'getfields', array('action' => 'get'));
    $getFieldsResult = $getFieldsResult['values'];
    foreach ($getFieldsResult as $getFieldKey => $getFieldSpec) {
        $uniqueAliases[$getFieldKey] = $getFieldSpec['name'];
        $uniqueAliases[$getFieldSpec['name']] = $getFieldSpec['name'];
    }
    // $select_fields maps column names to the field names of the result
    // values.
    $select_fields = array();
    // array with elements array('column', 'operator', 'value');
    $where_clauses = array();
    // Tables we need to join with to retrieve the custom values.
    $custom_value_tables = array();
    // ID's of custom fields that refer to a contact.
    $contact_reference_field_ids = array();
    // populate $select_fields
    $return_all_fields = empty($options['return']) || !is_array($options['return']);
    $return = $return_all_fields ? array_fill_keys($entity_field_names, 1) : $options['return'];
    // default fields
    foreach (array_keys($return) as $field_name) {
        if (!empty($uniqueAliases[$field_name]) && CRM_Core_BAO_CustomField::getKeyID($field_name) == FALSE) {
            // 'a.' is an alias for the entity table.
            $select_fields["a.{$uniqueAliases[$field_name]}"] = $uniqueAliases[$field_name];
        }
    }
    // custom fields
    foreach ($custom_fields as $cf_id => $custom_field) {
        $field_name = "custom_{$cf_id}";
        $custom_field_names[] = $field_name;
        if ($return_all_fields || !empty($options['return'][$field_name]) || !empty($options['return']['custom'])) {
            $table_name = $custom_field["table_name"];
            $column_name = $custom_field["column_name"];
            // remember that we will need to join the correct table.
            if (!in_array($table_name, $custom_value_tables)) {
                $custom_value_tables[] = $table_name;
            }
            if ($custom_field["data_type"] != "ContactReference") {
                // 'ordinary' custom field. We will select the value as custom_XX.
                $select_fields["{$table_name}.{$column_name}"] = $field_name;
            } else {
                // contact reference custom field. The ID will be stored in
                // custom_XX_id. custom_XX will contain the sort name of the
                // contact.
                $contact_reference_field_ids[] = $cf_id;
                $select_fields["{$table_name}.{$column_name}"] = $field_name . "_id";
                // We will call the contact table for the join c_XX.
                $select_fields["c_{$cf_id}.sort_name"] = $field_name;
            }
        }
    }
    if (!in_array("a.id", $select_fields)) {
        // Always select the ID.
        $select_fields["a.id"] = "id";
    }
    // build query
    $query = CRM_Utils_SQL_Select::from($dao->tableName() . " a");
    // populate $where_clauses
    foreach ($params as $key => $value) {
        $type = 'String';
        $table_name = NULL;
        $column_name = NULL;
        if (substr($key, 0, 7) == 'filter.') {
            // Legacy support for old filter syntax per the test contract.
            // (Convert the style to the later one & then deal with them).
            $filterArray = explode('.', $key);
            $value = array($filterArray[1] => $value);
            $key = 'filters';
        }
        // Legacy support for 'filter's construct.
        if ($key == 'filters') {
            foreach ($value as $filterKey => $filterValue) {
                if (substr($filterKey, -4, 4) == 'high') {
                    $key = substr($filterKey, 0, -5);
                    $value = array('<=' => $filterValue);
                }
                if (substr($filterKey, -3, 3) == 'low') {
                    $key = substr($filterKey, 0, -4);
                    $value = array('>=' => $filterValue);
                }
                if ($filterKey == 'is_current' || $filterKey == 'isCurrent') {
                    // Is current is almost worth creating as a 'sql filter' in the DAO function since several entities have the
                    // concept.
                    $todayStart = date('Ymd000000', strtotime('now'));
                    $todayEnd = date('Ymd235959', strtotime('now'));
                    $query->where(array("(a.start_date <= '{$todayStart}' OR a.start_date IS NULL) AND (a.end_date >= '{$todayEnd}' OR\n          a.end_date IS NULL)\n          AND a.is_active = 1\n        "));
                }
            }
        }
        if (array_key_exists($key, $getFieldsResult)) {
            $type = $getFieldsResult[$key]['type'];
            $key = $getFieldsResult[$key]['name'];
        }
        if ($key == _civicrm_api_get_entity_name_from_camel($entity) . '_id') {
            // The test contract enforces support of (eg) mailing_group_id if the entity is MailingGroup.
            $type = 'int';
            $key = 'id';
        }
        if (in_array($key, $entity_field_names)) {
            $table_name = 'a';
            $column_name = $key;
        } elseif (($cf_id = CRM_Core_BAO_CustomField::getKeyID($key)) != FALSE) {
            $table_name = $custom_fields[$cf_id]["table_name"];
            $column_name = $custom_fields[$cf_id]["column_name"];
            if (!in_array($table_name, $custom_value_tables)) {
                $custom_value_tables[] = $table_name;
            }
        }
        // I don't know why I had to specifically exclude 0 as a key - wouldn't the others have caught it?
        // We normally silently ignore null values passed in - if people want IS_NULL they can use acceptedSqlOperator syntax.
        if (!$table_name || empty($key) || is_null($value)) {
            // No valid filter field. This might be a chained call or something.
            // Just ignore this for the $where_clause.
            continue;
        }
        if (!is_array($value)) {
            $query->where(array("{$table_name}.{$column_name} = @value"), array("@value" => $value));
        } else {
            // We expect only one element in the array, of the form
            // "operator" => "rhs".
            $operator = CRM_Utils_Array::first(array_keys($value));
            if (!in_array($operator, CRM_Core_DAO::acceptedSQLOperators())) {
                $query->where(array("{$table_name}.{$column_name} = @value"), array("@value" => $value));
            } else {
                $query->where(CRM_Core_DAO::createSQLFilter("{$table_name}.{$column_name}", $value, $type));
            }
        }
    }
    $i = 0;
    if (!$options['is_count']) {
        foreach ($select_fields as $column => $alias) {
            ++$i;
            $query = $query->select("!column_{$i} as !alias_{$i}", array("!column_{$i}" => $column, "!alias_{$i}" => $alias));
        }
    } else {
        $query->select("count(*) as c");
    }
    // join with custom value tables
    foreach ($custom_value_tables as $table_name) {
        ++$i;
        $query = $query->join("!table_name_{$i}", "LEFT OUTER JOIN !table_name_{$i} ON !table_name_{$i}.entity_id = a.id", array("!table_name_{$i}" => $table_name));
    }
    // join with contact for contact reference fields
    foreach ($contact_reference_field_ids as $field_id) {
        ++$i;
        $query = $query->join("!contact_table_name{$i}", "LEFT OUTER JOIN civicrm_contact !contact_table_name_{$i} ON !contact_table_name_{$i}.id = !values_table_name_{$i}.!column_name_{$i}", array("!contact_table_name_{$i}" => "c_{$field_id}", "!values_table_name_{$i}" => $custom_fields[$field_id]["table_name"], "!column_name_{$i}" => $custom_fields[$field_id]["column_name"]));
    }
    foreach ($where_clauses as $clause) {
        ++$i;
        if (substr($clause[1], -4) == "NULL") {
            $query->where("!columnName_{$i} !nullThing_{$i}", array("!columnName_{$i}" => $clause[0], "!nullThing_{$i}" => $clause[1]));
        } else {
            $query->where("!columnName_{$i} !operator_{$i} @value_{$i}", array("!columnName_{$i}" => $clause[0], "!operator_{$i}" => $clause[1], "@value_{$i}" => $clause[2]));
        }
    }
    if (!empty($sqlFragment)) {
        $query->merge($sqlFragment);
    }
    // order by
    if (!empty($options['sort'])) {
        $sort_fields = array();
        foreach (explode(',', $options['sort']) as $sort_option) {
            $words = preg_split("/[\\s]+/", $sort_option);
            if (count($words) > 0 && in_array($words[0], array_values($select_fields))) {
                $tmp = $words[0];
                if (!empty($words[1]) && strtoupper($words[1]) == 'DESC') {
                    $tmp .= " DESC";
                }
                $sort_fields[] = $tmp;
            }
        }
        if (count($sort_fields) > 0) {
            $query->orderBy(implode(",", $sort_fields));
        }
    }
    // limit
    if (!empty($options['limit']) || !empty($options['offset'])) {
        $query->limit($options['limit'], $options['offset']);
    }
    $result_entities = array();
    $result_dao = CRM_Core_DAO::executeQuery($query->toSQL());
    while ($result_dao->fetch()) {
        if ($options['is_count']) {
            $result_dao->free();
            return (int) $result_dao->c;
        }
        $result_entities[$result_dao->id] = array();
        foreach ($select_fields as $column => $alias) {
            if (property_exists($result_dao, $alias) && $result_dao->{$alias} != NULL) {
                $result_entities[$result_dao->id][$alias] = $result_dao->{$alias};
            }
            // Backward compatibility on fields names.
            if ($isFillUniqueFields && !empty($getFieldsResult['values'][$column]['uniqueName'])) {
                $result_entities[$result_dao->id][$getFieldsResult['values'][$column]['uniqueName']] = $result_dao->{$alias};
            }
            foreach ($getFieldsResult as $returnName => $spec) {
                if (empty($result_entities[$result_dao->id][$returnName]) && !empty($result_entities[$result_dao->id][$spec['name']])) {
                    $result_entities[$result_dao->id][$returnName] = $result_entities[$result_dao->id][$spec['name']];
                }
            }
        }
    }
    $result_dao->free();
    return $result_entities;
}
예제 #18
0
 /**
  * @param int $mappingID
  * @param $recipientType
  *
  * @return array
  */
 public static function getRecipientListing($mappingID, $recipientType)
 {
     if (!$mappingID) {
         return array();
     }
     /** @var \Civi\ActionSchedule\Mapping $mapping */
     $mapping = CRM_Utils_Array::first(CRM_Core_BAO_ActionSchedule::getMappings(array('id' => $mappingID)));
     return $mapping->getRecipientListing($recipientType);
 }
예제 #19
0
 /**
  * Create a saved search, and test whether it can be used for a smart
  * group.
  */
 public function testCreateSavedSearchWithSmartGroup()
 {
     // First create a volunteer for the default organization
     $result = $this->callAPISuccess('Contact', 'create', array('first_name' => 'Joe', 'last_name' => 'Schmoe', 'contact_type' => 'Individual', 'api.Relationship.create' => array('contact_id_a' => '$value.id', 'contact_id_b' => 1, 'relationship_type_id' => 6, 'is_active' => 1)));
     $contact_id = $result['id'];
     // Now create our saved search, and chain the creation of a smart group.
     $params = $this->params;
     $params['api.Group.create'] = array('name' => 'my_smartgroup', 'title' => 'my smartgroup', 'description' => 'Volunteers for the default organization', 'saved_search_id' => '$value.id', 'is_active' => 1, 'visibility' => 'User and User Admin Only', 'is_hidden' => 0, 'is_reserved' => 0);
     $create_result = $this->callAPIAndDocument($this->_entity, 'create', $params, __FUNCTION__, __FILE__);
     $created_search = CRM_Utils_Array::first($create_result['values']);
     $group_id = $created_search['api.Group.create']['id'];
     // Search for contacts in our new smart group
     $get_result = $this->callAPISuccess('Contact', 'get', array('group' => $group_id), __FUNCTION__, __FILE__);
     // Expect our contact to be there.
     $this->assertEquals(1, $get_result['count']);
     $this->assertEquals($contact_id, $get_result['values'][$contact_id]['id']);
 }
예제 #20
0
 /**
  * Process the form submission.
  *
  *
  * @param CRM_Core_Form $form
  * @param array $params
  * @param $activity
  */
 public static function endPostProcess(&$form, &$params, $activity)
 {
     if (!$form->_caseId) {
         // always expecting a change, so case-id is a must.
         return;
     }
     $caseTypes = CRM_Case_PseudoConstant::caseType('name');
     $allCaseTypes = CRM_Case_PseudoConstant::caseType('title', FALSE);
     if (!empty($caseTypes[$params['case_type_id']])) {
         $caseType = $caseTypes[$params['case_type_id']];
     }
     if (!$form->_currentlyViewedContactId || !$form->_currentUserId || !$params['case_type_id'] || !$caseType) {
         CRM_Core_Error::fatal('Required parameter missing for ChangeCaseType - end post processing');
     }
     $params['status_id'] = CRM_Core_OptionGroup::getValue('activity_status', 'Completed', 'name');
     $activity->status_id = $params['status_id'];
     $params['priority_id'] = CRM_Core_OptionGroup::getValue('priority', 'Normal', 'name');
     $activity->priority_id = $params['priority_id'];
     if ($activity->subject == 'null') {
         $activity->subject = ts('Case type changed from %1 to %2', array(1 => CRM_Utils_Array::value($form->_defaults['case_type_id'], $allCaseTypes), 2 => CRM_Utils_Array::value($params['case_type_id'], $allCaseTypes)));
         $activity->save();
     }
     // 1. initiate xml processor
     $xmlProcessor = new CRM_Case_XMLProcessor_Process();
     $caseId = CRM_Utils_Array::first($form->_caseId);
     $xmlProcessorParams = array('clientID' => $form->_currentlyViewedContactId, 'creatorID' => $form->_currentUserId, 'standardTimeline' => 1, 'activityTypeName' => 'Change Case Type', 'activity_date_time' => CRM_Utils_Array::value('reset_date_time', $params), 'caseID' => $caseId, 'resetTimeline' => CRM_Utils_Array::value('is_reset_timeline', $params));
     $xmlProcessor->run($caseType, $xmlProcessorParams);
     // status msg
     $params['statusMsg'] = ts('Case Type changed successfully.');
 }
예제 #21
0
 static function getLeavesForPeriod($contactId, $startDate = null, $endDate = null)
 {
     $data = CRM_Hrjobcontract_BAO_HRJobLeave::createAbsenceArray();
     $jobContracts = civicrm_api3('HRJobContract', 'get', array('sequential' => 1, 'contact_id' => $contactId, 'deleted' => 0));
     foreach ($jobContracts['values'] as $jobContract) {
         $jobContractDetails = civicrm_api3('HRJobDetails', 'get', array('sequential' => 1, 'jobcontract_id' => $jobContract['id']));
         if (empty($jobContractDetails['values'])) {
             continue;
         }
         $details = CRM_Utils_Array::first($jobContractDetails['values']);
         $details['period_start_date'] = $details['period_start_date'] ? date('Y-m-d H:i:s', strtotime($details['period_start_date'])) : null;
         $details['period_end_date'] = $details['period_end_date'] ? date('Y-m-d H:i:s', strtotime($details['period_end_date'])) : null;
         if (CRM_Hrjobcontract_BAO_HRJobLeave::isJobDetailsInPeriod($details, $startDate, $endDate)) {
             $leaves = civicrm_api3('HRJobLeave', 'get', array('sequential' => 1, 'jobcontract_id' => $jobContract['id']));
             foreach ($leaves['values'] as $leave) {
                 $data[$leave['leave_type']] += $leave['leave_amount'];
             }
         }
     }
     return $data;
 }
예제 #22
0
 /**
  * Build & execute the query and return results array
  *
  * @return array
  * @throws \API_Exception
  * @throws \CRM_Core_Exception
  * @throws \Exception
  */
 public function run()
 {
     // $select_fields maps column names to the field names of the result values.
     $select_fields = $custom_fields = array();
     // populate $select_fields
     $return_all_fields = empty($this->options['return']) || !is_array($this->options['return']);
     $return = $return_all_fields ? array_fill_keys($this->entityFieldNames, 1) : $this->options['return'];
     // core return fields
     foreach ($return as $field_name => $include) {
         if ($include) {
             $field = $this->getField($field_name);
             if ($field && in_array($field['name'], $this->entityFieldNames)) {
                 // 'a.' is an alias for the entity table.
                 $select_fields["a.{$field['name']}"] = $field['name'];
             } elseif ($include && strpos($field_name, '.')) {
                 $fkField = $this->addFkField($field_name);
                 if ($fkField) {
                     $select_fields[implode('.', $fkField)] = $field_name;
                 }
             }
         }
     }
     // Do custom fields IF the params contain the word "custom" or we are returning *
     if ($return_all_fields || strpos(json_encode($this->params), 'custom')) {
         $custom_fields = _civicrm_api3_custom_fields_for_entity($this->entity);
         foreach ($custom_fields as $cf_id => $custom_field) {
             $field_name = "custom_{$cf_id}";
             if ($return_all_fields || !empty($this->options['return'][$field_name]) || !empty($this->options['return']['custom'])) {
                 list($table_name, $column_name) = $this->addCustomField($custom_field);
                 if ($custom_field["data_type"] != "ContactReference") {
                     // 'ordinary' custom field. We will select the value as custom_XX.
                     $select_fields["{$table_name}.{$column_name}"] = $field_name;
                 } else {
                     // contact reference custom field. The ID will be stored in custom_XX_id.
                     // custom_XX will contain the sort name of the contact.
                     $this->query->join("c_{$cf_id}", "LEFT JOIN civicrm_contact c_{$cf_id} ON c_{$cf_id}.id = `{$table_name}`.`{$column_name}`");
                     $select_fields["{$table_name}.{$column_name}"] = $field_name . "_id";
                     // We will call the contact table for the join c_XX.
                     $select_fields["c_{$cf_id}.sort_name"] = $field_name;
                 }
             }
         }
     }
     // Always select the ID.
     $select_fields["a.id"] = "id";
     // populate where_clauses
     foreach ($this->params as $key => $value) {
         $table_name = NULL;
         $column_name = NULL;
         if (substr($key, 0, 7) == 'filter.') {
             // Legacy support for old filter syntax per the test contract.
             // (Convert the style to the later one & then deal with them).
             $filterArray = explode('.', $key);
             $value = array($filterArray[1] => $value);
             $key = 'filters';
         }
         // Legacy support for 'filter's construct.
         if ($key == 'filters') {
             foreach ($value as $filterKey => $filterValue) {
                 if (substr($filterKey, -4, 4) == 'high') {
                     $key = substr($filterKey, 0, -5);
                     $value = array('<=' => $filterValue);
                 }
                 if (substr($filterKey, -3, 3) == 'low') {
                     $key = substr($filterKey, 0, -4);
                     $value = array('>=' => $filterValue);
                 }
                 if ($filterKey == 'is_current' || $filterKey == 'isCurrent') {
                     // Is current is almost worth creating as a 'sql filter' in the DAO function since several entities have the
                     // concept.
                     $todayStart = date('Ymd000000', strtotime('now'));
                     $todayEnd = date('Ymd235959', strtotime('now'));
                     $this->query->where(array("(a.start_date <= '{$todayStart}' OR a.start_date IS NULL) AND (a.end_date >= '{$todayEnd}' OR\n          a.end_date IS NULL)\n          AND a.is_active = 1\n        "));
                 }
             }
         }
         // Ignore the "options" param if it is referring to api options and not a field in this entity
         if ($key === 'options' && is_array($value) && !in_array(\CRM_Utils_Array::first(array_keys($value)), \CRM_Core_DAO::acceptedSQLOperators())) {
             continue;
         }
         $field = $this->getField($key);
         if ($field) {
             $key = $field['name'];
         }
         if (in_array($key, $this->entityFieldNames)) {
             $table_name = 'a';
             $column_name = $key;
         } elseif (($cf_id = \CRM_Core_BAO_CustomField::getKeyID($key)) != FALSE) {
             list($table_name, $column_name) = $this->addCustomField($custom_fields[$cf_id]);
         } elseif (strpos($key, '.')) {
             $fkInfo = $this->addFkField($key);
             if ($fkInfo) {
                 list($table_name, $column_name) = $fkInfo;
                 $this->validateNestedInput($key, $value);
             }
         }
         // I don't know why I had to specifically exclude 0 as a key - wouldn't the others have caught it?
         // We normally silently ignore null values passed in - if people want IS_NULL they can use acceptedSqlOperator syntax.
         if (!$table_name || empty($key) || is_null($value)) {
             // No valid filter field. This might be a chained call or something.
             // Just ignore this for the $where_clause.
             continue;
         }
         if (!is_array($value)) {
             $this->query->where(array("`{$table_name}`.`{$column_name}` = @value"), array("@value" => $value));
         } else {
             // We expect only one element in the array, of the form
             // "operator" => "rhs".
             $operator = \CRM_Utils_Array::first(array_keys($value));
             if (!in_array($operator, \CRM_Core_DAO::acceptedSQLOperators())) {
                 $this->query->where(array("{$table_name}.{$column_name} = @value"), array("@value" => $value));
             } else {
                 $this->query->where(\CRM_Core_DAO::createSQLFilter("{$table_name}.{$column_name}", $value));
             }
         }
     }
     if (!$this->options['is_count']) {
         foreach ($select_fields as $column => $alias) {
             $this->query->select("{$column} as `{$alias}`");
         }
     } else {
         $this->query->select("count(*) as c");
     }
     // order by
     if (!empty($this->options['sort'])) {
         $sort_fields = array();
         foreach (explode(',', $this->options['sort']) as $sort_option) {
             $words = preg_split("/[\\s]+/", $sort_option);
             if (count($words) > 0 && in_array($words[0], array_values($select_fields))) {
                 $tmp = $words[0];
                 if (!empty($words[1]) && strtoupper($words[1]) == 'DESC') {
                     $tmp .= " DESC";
                 }
                 $sort_fields[] = $tmp;
             }
         }
         if (count($sort_fields) > 0) {
             $this->query->orderBy(implode(",", $sort_fields));
         }
     }
     // limit
     if (!empty($this->options['limit']) || !empty($this->options['offset'])) {
         $this->query->limit($this->options['limit'], $this->options['offset']);
     }
     // ACLs
     $this->query->where($this->getAclClause('a'));
     $this->bao->free();
     $result_entities = array();
     $result_dao = \CRM_Core_DAO::executeQuery($this->query->toSQL());
     while ($result_dao->fetch()) {
         if ($this->options['is_count']) {
             $result_dao->free();
             return (int) $result_dao->c;
         }
         $result_entities[$result_dao->id] = array();
         foreach ($select_fields as $column => $alias) {
             $returnName = $alias;
             $alias = str_replace('.', '_', $alias);
             if (property_exists($result_dao, $alias) && $result_dao->{$alias} != NULL) {
                 $result_entities[$result_dao->id][$returnName] = $result_dao->{$alias};
             }
             // Backward compatibility on fields names.
             if ($this->isFillUniqueFields && !empty($this->apiFieldSpec[$alias]['uniqueName'])) {
                 $result_entities[$result_dao->id][$this->apiFieldSpec[$alias]['uniqueName']] = $result_dao->{$alias};
             }
             foreach ($this->apiFieldSpec as $returnName => $spec) {
                 if (empty($result_entities[$result_dao->id][$returnName]) && !empty($result_entities[$result_dao->id][$spec['name']])) {
                     $result_entities[$result_dao->id][$returnName] = $result_entities[$result_dao->id][$spec['name']];
                 }
             }
         }
     }
     $result_dao->free();
     return $result_entities;
 }
 /**
  * Process the form submission.
  *
  *
  * @param CRM_Core_Form $form
  * @param array $params
  * @param $activity
  */
 public static function endPostProcess(&$form, &$params, $activity)
 {
     if (!empty($params['start_date'])) {
         $params['start_date'] = CRM_Utils_Date::processDate($params['start_date'], $params['start_date_time']);
     }
     $caseType = CRM_Utils_Array::first($form->_caseType);
     $caseId = CRM_Utils_Array::first($form->_caseId);
     if (!$caseType && $caseId) {
         $caseType = CRM_Case_BAO_Case::getCaseType($caseId, 'title');
     }
     if (!$form->_currentlyViewedContactId || !$form->_currentUserId || !$caseId || !$caseType) {
         CRM_Core_Error::fatal('Required parameter missing for ChangeCaseType - end post processing');
     }
     $config = CRM_Core_Config::singleton();
     $params['status_id'] = CRM_Core_OptionGroup::getValue('activity_status', 'Completed', 'name');
     $activity->status_id = $params['status_id'];
     $params['priority_id'] = CRM_Core_OptionGroup::getValue('priority', 'Normal', 'name');
     $activity->priority_id = $params['priority_id'];
     // 1. save activity subject with new start date
     $currentStartDate = CRM_Utils_Date::customFormat(CRM_Core_DAO::getFieldValue('CRM_Case_DAO_Case', $caseId, 'start_date'), $config->dateformatFull);
     $newStartDate = CRM_Utils_Date::customFormat(CRM_Utils_Date::mysqlToIso($params['start_date']), $config->dateformatFull);
     $subject = 'Change Case Start Date from ' . $currentStartDate . ' to ' . $newStartDate;
     $activity->subject = $subject;
     $activity->save();
     // 2. initiate xml processor
     $xmlProcessor = new CRM_Case_XMLProcessor_Process();
     $xmlProcessorParams = array('clientID' => $form->_currentlyViewedContactId, 'creatorID' => $form->_currentUserId, 'standardTimeline' => 0, 'activity_date_time' => $params['start_date'], 'caseID' => $caseId, 'caseType' => $caseType, 'activityTypeName' => 'Change Case Start Date', 'activitySetName' => 'standard_timeline', 'resetTimeline' => 1);
     $xmlProcessor->run($caseType, $xmlProcessorParams);
     // 2.5 Update open case activity date
     // Multiple steps since revisioned
     if ($form->openCaseActivityId) {
         $abao = new CRM_Activity_BAO_Activity();
         $oldParams = array('id' => $form->openCaseActivityId);
         $oldActivityDefaults = array();
         $oldActivity = $abao->retrieve($oldParams, $oldActivityDefaults);
         // save the old values
         require_once 'api/v3/utils.php';
         $openCaseParams = array();
         //@todo calling api functions directly is not supported
         _civicrm_api3_object_to_array($oldActivity, $openCaseParams);
         // update existing revision
         $oldParams = array('id' => $form->openCaseActivityId, 'is_current_revision' => 0);
         $oldActivity = new CRM_Activity_DAO_Activity();
         $oldActivity->copyValues($oldParams);
         $oldActivity->save();
         // change some params for the new one
         unset($openCaseParams['id']);
         $openCaseParams['activity_date_time'] = $params['start_date'];
         $openCaseParams['target_contact_id'] = $oldActivityDefaults['target_contact'];
         $openCaseParams['assignee_contact_id'] = $oldActivityDefaults['assignee_contact'];
         $session = CRM_Core_Session::singleton();
         $openCaseParams['source_contact_id'] = $session->get('userID');
         // original_id always refers to the first activity, so only update if null (i.e. this is the second revision)
         $openCaseParams['original_id'] = $openCaseParams['original_id'] ? $openCaseParams['original_id'] : $form->openCaseActivityId;
         $newActivity = CRM_Activity_BAO_Activity::create($openCaseParams);
         if (is_a($newActivity, 'CRM_Core_Error')) {
             CRM_Core_Error::fatal('Unable to update Open Case activity');
         } else {
             // Create linkage to case
             $caseActivityParams = array('activity_id' => $newActivity->id, 'case_id' => $caseId);
             CRM_Case_BAO_Case::processCaseActivity($caseActivityParams);
             $caseActivityParams = array('activityID' => $form->openCaseActivityId, 'mainActivityId' => $newActivity->id);
             CRM_Activity_BAO_Activity::copyExtendedActivityData($caseActivityParams);
         }
     }
     // 3.status msg
     $params['statusMsg'] = ts('Case Start Date changed successfully.');
 }
예제 #24
0
 /**
  * Get available CKEditor plugin list.
  *
  * @return array
  */
 private function getCKPlugins()
 {
     $plugins = array();
     $pluginDir = Civi::paths()->getPath('[civicrm.root]/bower_components/ckeditor/plugins');
     foreach (glob($pluginDir . '/*', GLOB_ONLYDIR) as $dir) {
         $dir = rtrim(str_replace('\\', '/', $dir), '/');
         $name = substr($dir, strrpos($dir, '/') + 1);
         $dir = CRM_Utils_file::addTrailingSlash($dir, '/');
         if (is_file($dir . 'plugin.js')) {
             $plugins[$name] = array('id' => $name, 'text' => ucfirst($name), 'icon' => NULL);
             if (is_dir($dir . "icons")) {
                 if (is_file($dir . "icons/{$name}.png")) {
                     $plugins[$name]['icon'] = "bower_components/ckeditor/plugins/{$name}/icons/{$name}.png";
                 } elseif (glob($dir . "icons/*.png")) {
                     $icon = CRM_Utils_Array::first(glob($dir . "icons/*.png"));
                     $icon = rtrim(str_replace('\\', '/', $icon), '/');
                     $plugins[$name]['icon'] = "bower_components/ckeditor/plugins/{$name}/icons/" . substr($icon, strrpos($icon, '/') + 1);
                 }
             }
         }
     }
     return $plugins;
 }
예제 #25
0
 /**
  * Build the form object.
  *
  * @return void
  */
 public function preProcess()
 {
     $caseIds = CRM_Utils_Request::retrieve('caseid', 'String', $this);
     $this->_caseId = explode(',', $caseIds);
     $this->_context = CRM_Utils_Request::retrieve('context', 'String', $this);
     if (!$this->_context) {
         $this->_context = 'caseActivity';
     }
     $this->_crmDir = 'Case';
     $this->assign('context', $this->_context);
     $result = parent::preProcess();
     $scheduleStatusId = CRM_Core_OptionGroup::getValue('activity_status', 'Scheduled', 'name');
     $this->assign('scheduleStatusId', $scheduleStatusId);
     if (!$this->_caseId && $this->_activityId) {
         $this->_caseId = CRM_Core_DAO::getFieldValue('CRM_Case_DAO_CaseActivity', $this->_activityId, 'case_id', 'activity_id');
     }
     if ($this->_caseId) {
         $this->assign('caseId', $this->_caseId);
         $this->assign('countId', count($this->_caseId));
         $this->assign('caseID', CRM_Utils_Array::first($this->_caseId));
     }
     if (!$this->_caseId || !$this->_activityId && !$this->_activityTypeId) {
         CRM_Core_Error::fatal('required params missing.');
     }
     //check for case activity access.
     if (!CRM_Case_BAO_Case::accessCiviCase()) {
         CRM_Core_Error::fatal(ts('You are not authorized to access this page.'));
     }
     //validate case id.
     if ($this->_caseId && !CRM_Core_Permission::check('access all cases and activities')) {
         $session = CRM_Core_Session::singleton();
         $allCases = CRM_Case_BAO_Case::getCases(TRUE, $session->get('userID'), 'any');
         if (!array_key_exists($this->_caseId, $allCases)) {
             CRM_Core_Error::fatal(ts('You are not authorized to access this page.'));
         }
     }
     //validate case activity id.
     if ($this->_activityId && $this->_action & CRM_Core_Action::UPDATE) {
         $valid = CRM_Case_BAO_Case::checkPermission($this->_activityId, 'edit', $this->_activityTypeId);
         if (!$valid) {
             CRM_Core_Error::fatal(ts('You are not authorized to access this page.'));
         }
     }
     foreach ($this->_caseId as $casePos => $caseId) {
         $this->_caseType[$casePos] = CRM_Case_BAO_Case::getCaseType($caseId, 'name');
     }
     $this->assign('caseType', $this->_caseType);
     $xmlProcessorProcess = new CRM_Case_XMLProcessor_Process();
     $isMultiClient = $xmlProcessorProcess->getAllowMultipleCaseClients();
     $this->assign('multiClient', $isMultiClient);
     foreach ($this->_caseId as $casePos => $caseId) {
         $clients[] = CRM_Case_BAO_Case::getContactNames($caseId);
     }
     $this->assign('client_names', $clients);
     $caseIds = implode(',', $this->_caseId);
     // set context for pushUserContext and for statusBounce
     if ($this->_context == 'fulltext') {
         if ($this->_action == CRM_Core_Action::UPDATE || $this->_action == CRM_Core_Action::DELETE) {
             $url = CRM_Utils_System::url('civicrm/contact/view/case', "reset=1&action=view&cid={$this->_currentlyViewedContactId}&id={$caseIds}&show=1&context={$this->_context}");
         } else {
             $url = CRM_Utils_System::url('civicrm/contact/search/custom', 'force=1');
         }
     } else {
         $url = CRM_Utils_System::url('civicrm/contact/view/case', "reset=1&action=view&cid={$this->_currentlyViewedContactId}&id={$caseIds}&show=1");
     }
     if (!$this->_activityId) {
         $caseTypes = CRM_Case_PseudoConstant::caseType();
         if (empty($caseTypes) && $this->_activityTypeName == 'Change Case Type' && !$this->_caseId) {
             $url = CRM_Utils_System::url('civicrm/contact/view/case', "reset=1&action=view&cid={$this->_currentlyViewedContactId}&id={$caseIds}&show=1");
             $session = CRM_Core_Session::singleton();
             $session->pushUserContext($url);
             CRM_Core_Error::statusBounce(ts("You do not have any active Case Types"));
         }
         // check if activity count is within the limit
         $xmlProcessor = new CRM_Case_XMLProcessor_Process();
         foreach ($this->_caseId as $casePos => $caseId) {
             $caseType = $this->_caseType[$casePos];
             $activityInst = $xmlProcessor->getMaxInstance($caseType);
             // If not bounce back and also provide activity edit link
             if (isset($activityInst[$this->_activityTypeName])) {
                 $activityCount = CRM_Case_BAO_Case::getCaseActivityCount($caseId, $this->_activityTypeId);
                 if ($activityCount >= $activityInst[$this->_activityTypeName]) {
                     if ($activityInst[$this->_activityTypeName] == 1) {
                         $atArray = array('activity_type_id' => $this->_activityTypeId);
                         $activities = CRM_Case_BAO_Case::getCaseActivity($caseId, $atArray, $this->_currentUserId);
                         $activities = array_keys($activities);
                         $activities = $activities[0];
                         $editUrl = CRM_Utils_System::url('civicrm/case/activity', "reset=1&cid={$this->_currentlyViewedContactId}&caseid={$caseId}&action=update&id={$activities}");
                     }
                     CRM_Core_Error::statusBounce(ts("You can not add another '%1' activity to this case. %2", array(1 => $this->_activityTypeName, 2 => ts("Do you want to <a %1>edit the existing activity</a>?", array(1 => "href='{$editUrl}'")))), $url);
                 }
             }
         }
     }
     $session = CRM_Core_Session::singleton();
     $session->pushUserContext($url);
 }
예제 #26
0
 /**
  * Lower-level logic for rendering a custom field value
  *
  * @param string|array $value
  * @param array $field
  * @param int|null $entityId
  *
  * @return string
  */
 private static function formatDisplayValue($value, $field, $entityId = NULL)
 {
     if (self::isSerialized($field) && !is_array($value)) {
         $value = CRM_Utils_Array::explodePadded($value);
     }
     // CRM-12989 fix
     if ($field['html_type'] == 'CheckBox') {
         CRM_Utils_Array::formatArrayKeys($value);
     }
     $display = is_array($value) ? implode(', ', $value) : (string) $value;
     switch ($field['html_type']) {
         case 'Select':
         case 'Autocomplete-Select':
         case 'Radio':
         case 'Select Country':
         case 'Select State/Province':
         case 'CheckBox':
         case 'AdvMulti-Select':
         case 'Multi-Select':
         case 'Multi-Select State/Province':
         case 'Multi-Select Country':
             if ($field['data_type'] == 'ContactReference' && $value) {
                 $display = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $value, 'display_name');
             } elseif (is_array($value)) {
                 $v = array();
                 foreach ($value as $key => $val) {
                     $v[] = CRM_Utils_Array::value($val, $field['options']);
                 }
                 $display = implode(', ', $v);
             } else {
                 $display = CRM_Utils_Array::value($value, $field['options'], '');
             }
             break;
         case 'Select Date':
             $customFormat = NULL;
             // FIXME: Are there any legitimate reasons why $value would be an array?
             // Or should we throw an exception here if it is?
             $value = is_array($value) ? CRM_Utils_Array::first($value) : $value;
             $actualPHPFormats = CRM_Core_SelectValues::datePluginToPHPFormats();
             $format = CRM_Utils_Array::value('date_format', $field);
             if ($format) {
                 if (array_key_exists($format, $actualPHPFormats)) {
                     $customTimeFormat = (array) $actualPHPFormats[$format];
                     switch (CRM_Utils_Array::value('time_format', $field)) {
                         case 1:
                             $customTimeFormat[] = 'g:iA';
                             break;
                         case 2:
                             $customTimeFormat[] = 'G:i';
                             break;
                         default:
                             // if time is not selected remove time from value
                             $value = substr($value, 0, 10);
                     }
                     $customFormat = implode(" ", $customTimeFormat);
                 }
             }
             $display = CRM_Utils_Date::processDate($value, NULL, FALSE, $customFormat);
             break;
         case 'File':
             // In the context of displaying a profile, show file/image
             if ($value) {
                 if ($entityId) {
                     $url = self::getFileURL($entityId, $field['id']);
                     if ($url) {
                         $display = $url['file_url'];
                     }
                 } else {
                     // In other contexts show a paperclip icon
                     if (CRM_Utils_Rule::integer($value)) {
                         $icons = CRM_Core_BAO_File::paperIconAttachment('*', $value);
                         $display = $icons[$value];
                     } else {
                         //CRM-18396, if filename is passed instead
                         $display = $value;
                     }
                 }
             }
             break;
         case 'TextArea':
             $display = nl2br($display);
             break;
         case 'Text':
             if ($field['data_type'] == 'Money' && isset($value)) {
                 //$value can also be an array(while using IN operator from search builder or api).
                 foreach ((array) $value as $val) {
                     $disp[] = CRM_Utils_Money::format($val);
                 }
                 $display = implode(', ', $disp);
             }
             break;
     }
     return $display;
 }
 /**
  * @return array
  *   Contact record (per APIv3).
  */
 public function webtestGetLoggedInContact()
 {
     $result = $this->rest_civicrm_api('Contact', 'get', array('id' => 'user_contact_id'));
     $this->assertAPISuccess($result, 'Load logged-in contact');
     return CRM_Utils_Array::first($result['values']);
 }
예제 #28
0
 /**
  * make a copy of a Event, including
  * all the fields in the event Wizard
  *
  * @param int $id
  *   The event id to copy.
  *        boolean $afterCreate call to copy after the create function
  * @param null $newEvent
  * @param bool $afterCreate
  *
  * @return CRM_Event_DAO_Event
  */
 public static function copy($id, $newEvent = NULL, $afterCreate = FALSE)
 {
     $eventValues = array();
     //get the require event values.
     $eventParams = array('id' => $id);
     $returnProperties = array('loc_block_id', 'is_show_location', 'default_fee_id', 'default_discount_fee_id', 'is_template');
     CRM_Core_DAO::commonRetrieve('CRM_Event_DAO_Event', $eventParams, $eventValues, $returnProperties);
     // since the location is sharable, lets use the same loc_block_id.
     $locBlockId = CRM_Utils_Array::value('loc_block_id', $eventValues);
     $fieldsFix = $afterCreate ? array() : array('prefix' => array('title' => ts('Copy of') . ' '));
     if (empty($eventValues['is_show_location'])) {
         $fieldsFix['prefix']['is_show_location'] = 0;
     }
     if ($newEvent && is_a($newEvent, 'CRM_Event_DAO_Event')) {
         $copyEvent = $newEvent;
     }
     if (!isset($copyEvent)) {
         $copyEvent =& CRM_Core_DAO::copyGeneric('CRM_Event_DAO_Event', array('id' => $id), array('loc_block_id' => $locBlockId ? $locBlockId : NULL), $fieldsFix);
     }
     CRM_Price_BAO_PriceSet::copyPriceSet('civicrm_event', $id, $copyEvent->id);
     $copyUF =& CRM_Core_DAO::copyGeneric('CRM_Core_DAO_UFJoin', array('entity_id' => $id, 'entity_table' => 'civicrm_event'), array('entity_id' => $copyEvent->id));
     $copyTellFriend =& CRM_Core_DAO::copyGeneric('CRM_Friend_DAO_Friend', array('entity_id' => $id, 'entity_table' => 'civicrm_event'), array('entity_id' => $copyEvent->id));
     $copyPCP =& CRM_Core_DAO::copyGeneric('CRM_PCP_DAO_PCPBlock', array('entity_id' => $id, 'entity_table' => 'civicrm_event'), array('entity_id' => $copyEvent->id), array('replace' => array('target_entity_id' => $copyEvent->id)));
     $oldMapping = CRM_Utils_Array::first(CRM_Core_BAO_ActionSchedule::getMappings(array('id' => $eventValues['is_template'] ? CRM_Event_ActionMapping::EVENT_TPL_MAPPING_ID : CRM_Event_ActionMapping::EVENT_NAME_MAPPING_ID)));
     $copyMapping = CRM_Utils_Array::first(CRM_Core_BAO_ActionSchedule::getMappings(array('id' => $copyEvent->is_template == 1 ? CRM_Event_ActionMapping::EVENT_TPL_MAPPING_ID : CRM_Event_ActionMapping::EVENT_NAME_MAPPING_ID)));
     $copyReminder =& CRM_Core_DAO::copyGeneric('CRM_Core_DAO_ActionSchedule', array('entity_value' => $id, 'mapping_id' => $oldMapping->getId()), array('entity_value' => $copyEvent->id, 'mapping_id' => $copyMapping->getId()));
     if (!$afterCreate) {
         //copy custom data
         $extends = array('event');
         $groupTree = CRM_Core_BAO_CustomGroup::getGroupDetail(NULL, NULL, $extends);
         if ($groupTree) {
             foreach ($groupTree as $groupID => $group) {
                 $table[$groupTree[$groupID]['table_name']] = array('entity_id');
                 foreach ($group['fields'] as $fieldID => $field) {
                     $table[$groupTree[$groupID]['table_name']][] = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
                 }
             }
             foreach ($table as $tableName => $tableColumns) {
                 $insert = 'INSERT INTO ' . $tableName . ' (' . implode(', ', $tableColumns) . ') ';
                 $tableColumns[0] = $copyEvent->id;
                 $select = 'SELECT ' . implode(', ', $tableColumns);
                 $from = ' FROM ' . $tableName;
                 $where = " WHERE {$tableName}.entity_id = {$id}";
                 $query = $insert . $select . $from . $where;
                 $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
             }
         }
     }
     $copyEvent->save();
     CRM_Utils_System::flushCache();
     if (!$afterCreate) {
         CRM_Utils_Hook::copy('Event', $copyEvent);
     }
     return $copyEvent;
 }
예제 #29
0
 /**
  * Build the form object.
  */
 public function buildQuickForm()
 {
     parent::buildQuickForm();
     $this->_mappingID = $mappingID = NULL;
     $providersCount = CRM_SMS_BAO_Provider::activeProviderCount();
     $this->_context = CRM_Utils_Request::retrieve('context', 'String', $this);
     //CRM-16777: Don't provide access to administer schedule reminder page, with user that does not have 'administer CiviCRM' permission
     if (empty($this->_context) && !CRM_Core_Permission::check('administer CiviCRM')) {
         CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
     } else {
         $this->_compId = CRM_Utils_Request::retrieve('compId', 'Integer', $this);
         if (!CRM_Event_BAO_Event::checkPermission($this->_compId, CRM_Core_Permission::EDIT)) {
             CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
         }
     }
     if ($this->_action & CRM_Core_Action::DELETE) {
         $reminderName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_ActionSchedule', $this->_id, 'title');
         if ($this->_context == 'event') {
             $this->_compId = CRM_Utils_Request::retrieve('compId', 'Integer', $this);
         }
         $this->assign('reminderName', $reminderName);
         return;
     } elseif ($this->_action & CRM_Core_Action::UPDATE) {
         $this->_mappingID = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_ActionSchedule', $this->_id, 'mapping_id');
         if ($this->_context == 'event') {
             $this->_compId = CRM_Utils_Request::retrieve('compId', 'Integer', $this);
         }
     } elseif (!empty($this->_context)) {
         if ($this->_context == 'event') {
             $this->_compId = CRM_Utils_Request::retrieve('compId', 'Integer', $this);
             $isTemplate = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $this->_compId, 'is_template');
             $mapping = CRM_Utils_Array::first(CRM_Core_BAO_ActionSchedule::getMappings(array('id' => $isTemplate ? CRM_Event_ActionMapping::EVENT_TPL_MAPPING_ID : CRM_Event_ActionMapping::EVENT_NAME_MAPPING_ID)));
             if ($mapping) {
                 $this->_mappingID = $mapping->getId();
             } else {
                 CRM_Core_Error::fatal('Could not find mapping for event scheduled reminders.');
             }
         }
     }
     if (!empty($_POST) && !empty($_POST['entity']) && empty($this->_context)) {
         $mappingID = $_POST['entity'][0];
     } elseif ($this->_mappingID) {
         $mappingID = $this->_mappingID;
     }
     $this->add('text', 'title', ts('Title'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_ActionSchedule', 'title'), TRUE);
     $mappings = CRM_Core_BAO_ActionSchedule::getMappings();
     $selectedMapping = $mappings[$mappingID ? $mappingID : 1];
     $entityRecipientLabels = $selectedMapping->getRecipientTypes() + CRM_Core_BAO_ActionSchedule::getAdditionalRecipients();
     $this->assign('entityMapping', json_encode(CRM_Utils_Array::collectMethod('getEntity', $mappings)));
     $this->assign('recipientMapping', json_encode(array_combine(array_keys($entityRecipientLabels), array_keys($entityRecipientLabels))));
     if (empty($this->_context)) {
         $sel =& $this->add('hierselect', 'entity', ts('Entity'), array('name' => 'entity[0]', 'style' => 'vertical-align: top;'));
         $sel->setOptions(array(CRM_Utils_Array::collectMethod('getLabel', $mappings), CRM_Core_BAO_ActionSchedule::getAllEntityValueLabels(), CRM_Core_BAO_ActionSchedule::getAllEntityStatusLabels()));
         if (is_a($sel->_elements[1], 'HTML_QuickForm_select')) {
             // make second selector a multi-select -
             $sel->_elements[1]->setMultiple(TRUE);
             $sel->_elements[1]->setSize(5);
         }
         if (is_a($sel->_elements[2], 'HTML_QuickForm_select')) {
             // make third selector a multi-select -
             $sel->_elements[2]->setMultiple(TRUE);
             $sel->_elements[2]->setSize(5);
         }
     } else {
         // Dig deeper - this code is sublimely stupid.
         $allEntityStatusLabels = CRM_Core_BAO_ActionSchedule::getAllEntityStatusLabels();
         $options = $allEntityStatusLabels[$this->_mappingID][0];
         $attributes = array('multiple' => 'multiple', 'class' => 'crm-select2 huge', 'placeholder' => $options[0]);
         unset($options[0]);
         $this->add('select', 'entity', ts('Recipient(s)'), $options, TRUE, $attributes);
         $this->assign('context', $this->_context);
     }
     //get the frequency units.
     $this->_freqUnits = CRM_Core_SelectValues::getRecurringFrequencyUnits();
     $numericOptions = CRM_Core_SelectValues::getNumericOptions(0, 30);
     //reminder_interval
     $this->add('select', 'start_action_offset', ts('When'), $numericOptions);
     $isActive = ts('Send email');
     $recordActivity = ts('Record activity for automated email');
     if ($providersCount) {
         $this->assign('sms', $providersCount);
         $isActive = ts('Send email or SMS');
         $recordActivity = ts('Record activity for automated email or SMS');
         $options = CRM_Core_OptionGroup::values('msg_mode');
         $this->add('select', 'mode', ts('Send as'), $options);
         $providers = CRM_SMS_BAO_Provider::getProviders(NULL, NULL, TRUE, 'is_default desc');
         $providerSelect = array();
         foreach ($providers as $provider) {
             $providerSelect[$provider['id']] = $provider['title'];
         }
         $this->add('select', 'sms_provider_id', ts('SMS Provider'), $providerSelect, TRUE);
     }
     foreach ($this->_freqUnits as $val => $label) {
         $freqUnitsDisplay[$val] = ts('%1(s)', array(1 => $label));
     }
     $this->addDate('absolute_date', ts('Start Date'), FALSE, array('formatType' => 'mailing'));
     //reminder_frequency
     $this->add('select', 'start_action_unit', ts('Frequency'), $freqUnitsDisplay, TRUE);
     $condition = array('before' => ts('before'), 'after' => ts('after'));
     //reminder_action
     $this->add('select', 'start_action_condition', ts('Action Condition'), $condition);
     $this->add('select', 'start_action_date', ts('Date Field'), $selectedMapping->getDateFields(), TRUE);
     $this->addElement('checkbox', 'record_activity', $recordActivity);
     $this->addElement('checkbox', 'is_repeat', ts('Repeat'), NULL, array('onchange' => "return showHideByValue('is_repeat',true,'repeatFields','table-row','radio',false);"));
     $this->add('select', 'repetition_frequency_unit', ts('every'), $freqUnitsDisplay);
     $this->add('select', 'repetition_frequency_interval', ts('every'), $numericOptions);
     $this->add('select', 'end_frequency_unit', ts('until'), $freqUnitsDisplay);
     $this->add('select', 'end_frequency_interval', ts('until'), $numericOptions);
     $this->add('select', 'end_action', ts('Repetition Condition'), $condition, TRUE);
     $this->add('select', 'end_date', ts('Date Field'), $selectedMapping->getDateFields(), TRUE);
     $this->add('text', 'from_name', ts('From Name'));
     $this->add('text', 'from_email', ts('From Email'));
     $recipientListingOptions = array();
     if ($mappingID) {
         $mapping = CRM_Utils_Array::first(CRM_Core_BAO_ActionSchedule::getMappings(array('id' => $mappingID)));
     }
     $limitOptions = array('' => '-neither-', 1 => ts('Limit to'), 0 => ts('Also include'));
     $recipientLabels = array('activity' => ts('Recipients'), 'other' => ts('Limit or Add Recipients'));
     $this->assign('recipientLabels', $recipientLabels);
     $this->add('select', 'limit_to', ts('Limit Options'), $limitOptions, FALSE, array('onChange' => "showHideByValue('limit_to','','recipient', 'select','select',true);"));
     $this->add('select', 'recipient', $recipientLabels['other'], $entityRecipientLabels, FALSE, array('onchange' => "showHideByValue('recipient','manual','recipientManual','table-row','select',false); showHideByValue('recipient','group','recipientGroup','table-row','select',false);"));
     if (!empty($this->_submitValues['recipient_listing'])) {
         if (!empty($this->_context)) {
             $recipientListingOptions = CRM_Core_BAO_ActionSchedule::getRecipientListing($this->_mappingID, $this->_submitValues['recipient']);
         } else {
             $recipientListingOptions = CRM_Core_BAO_ActionSchedule::getRecipientListing($_POST['entity'][0], $_POST['recipient']);
         }
     } elseif (!empty($this->_values['recipient_listing'])) {
         $recipientListingOptions = CRM_Core_BAO_ActionSchedule::getRecipientListing($this->_values['mapping_id'], $this->_values['recipient']);
     }
     $this->add('select', 'recipient_listing', ts('Recipient Roles'), $recipientListingOptions, FALSE, array('multiple' => TRUE, 'class' => 'crm-select2 huge', 'placeholder' => TRUE));
     $this->addEntityRef('recipient_manual_id', ts('Manual Recipients'), array('multiple' => TRUE, 'create' => TRUE));
     $this->add('select', 'group_id', ts('Group'), CRM_Core_PseudoConstant::nestedGroup('Mailing'), FALSE, array('class' => 'crm-select2 huge'));
     // multilingual only options
     $multilingual = CRM_Core_I18n::isMultilingual();
     if ($multilingual) {
         $smarty = CRM_Core_Smarty::singleton();
         $smarty->assign('multilingual', $multilingual);
         $languages = CRM_Core_I18n::languages(TRUE);
         $languageFilter = $languages + array(CRM_Core_I18n::NONE => ts('Contacts with no preferred language'));
         $element = $this->add('select', 'filter_contact_language', ts('Recipients language'), $languageFilter, FALSE, array('multiple' => TRUE, 'class' => 'crm-select2', 'placeholder' => TRUE));
         $communicationLanguage = array('' => ts('System default language'), CRM_Core_I18n::AUTO => ts('Follow recipient preferred language'));
         $communicationLanguage = $communicationLanguage + $languages;
         $this->add('select', 'communication_language', ts('Communication language'), $communicationLanguage);
     }
     CRM_Mailing_BAO_Mailing::commonCompose($this);
     $this->add('text', 'subject', ts('Subject'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_ActionSchedule', 'subject'));
     $this->add('checkbox', 'is_active', $isActive);
     $this->addFormRule(array('CRM_Admin_Form_ScheduleReminders', 'formRule'), $this);
     $this->setPageTitle(ts('Scheduled Reminder'));
 }
예제 #30
0
 /**
  * @param CRM_Event_Form_ManageEvent $form
  *
  * @return array
  * @throws Exception
  */
 public static function process(&$form)
 {
     if ($form->getVar('_id') <= 0) {
         return NULL;
     }
     $default = array('link' => NULL, 'valid' => TRUE, 'active' => TRUE, 'current' => FALSE, 'class' => 'ajaxForm');
     $tabs = array();
     $tabs['settings'] = array('title' => ts('Info and Settings'), 'class' => 'ajaxForm livePage') + $default;
     $tabs['location'] = array('title' => ts('Event Location')) + $default;
     $tabs['fee'] = array('title' => ts('Fees')) + $default;
     $tabs['registration'] = array('title' => ts('Online Registration')) + $default;
     if (CRM_Core_Permission::check('administer CiviCRM') || CRM_Event_BAO_Event::checkPermission(NULL, CRM_Core_Permission::EDIT)) {
         $tabs['reminder'] = array('title' => ts('Schedule Reminders'), 'class' => 'livePage') + $default;
     }
     $tabs['conference'] = array('title' => ts('Conference Slots')) + $default;
     $tabs['friend'] = array('title' => ts('Tell a Friend')) + $default;
     $tabs['pcp'] = array('title' => ts('Personal Campaigns')) + $default;
     $tabs['repeat'] = array('title' => ts('Repeat')) + $default;
     // Repeat tab must refresh page when switching repeat mode so js & vars will get set-up
     if (!$form->_isRepeatingEvent) {
         unset($tabs['repeat']['class']);
     }
     // 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');
     if (!$enableCart) {
         unset($tabs['conference']);
     }
     $eventID = $form->getVar('_id');
     if ($eventID) {
         // disable tabs based on their configuration status
         $eventNameMapping = CRM_Utils_Array::first(CRM_Core_BAO_ActionSchedule::getMappings(array('id' => CRM_Event_ActionMapping::EVENT_NAME_MAPPING_ID)));
         $sql = "\nSELECT     e.loc_block_id as is_location, e.is_online_registration, e.is_monetary, taf.is_active, pcp.is_active as is_pcp, sch.id as is_reminder, re.id as is_repeating_event\nFROM       civicrm_event e\nLEFT JOIN  civicrm_tell_friend taf ON ( taf.entity_table = 'civicrm_event' AND taf.entity_id = e.id )\nLEFT JOIN  civicrm_pcp_block pcp   ON ( pcp.entity_table = 'civicrm_event' AND pcp.entity_id = e.id )\nLEFT JOIN  civicrm_action_schedule sch ON ( sch.mapping_id = %2 AND sch.entity_value = %1 )\nLEFT JOIN  civicrm_recurring_entity re ON ( e.id = re.entity_id AND re.entity_table = 'civicrm_event' )\nWHERE      e.id = %1\n";
         //Check if repeat is configured
         $eventHasParent = CRM_Core_BAO_RecurringEntity::getParentFor($eventID, 'civicrm_event');
         $params = array(1 => array($eventID, 'Integer'), 2 => array($eventNameMapping->getId(), 'Integer'));
         $dao = CRM_Core_DAO::executeQuery($sql, $params);
         if (!$dao->fetch()) {
             CRM_Core_Error::fatal();
         }
         if (!$dao->is_location) {
             $tabs['location']['valid'] = FALSE;
         }
         if (!$dao->is_online_registration) {
             $tabs['registration']['valid'] = FALSE;
         }
         if (!$dao->is_monetary) {
             $tabs['fee']['valid'] = FALSE;
         }
         if (!$dao->is_active) {
             $tabs['friend']['valid'] = FALSE;
         }
         if (!$dao->is_pcp) {
             $tabs['pcp']['valid'] = FALSE;
         }
         if (!$dao->is_reminder) {
             $tabs['reminder']['valid'] = FALSE;
         }
         if (!$dao->is_repeating_event) {
             $tabs['repeat']['valid'] = FALSE;
         }
     }
     // see if any other modules want to add any tabs
     // note: status of 'valid' flag of any injected tab, needs to be taken care in the hook implementation.
     CRM_Utils_Hook::tabset('civicrm/event/manage', $tabs, array('event_id' => $eventID));
     $fullName = $form->getVar('_name');
     $className = CRM_Utils_String::getClassName($fullName);
     $new = '';
     // hack for special cases.
     switch ($className) {
         case 'Event':
             $attributes = $form->getVar('_attributes');
             $class = strtolower(basename(CRM_Utils_Array::value('action', $attributes)));
             break;
         case 'EventInfo':
             $class = 'settings';
             break;
         case 'ScheduleReminders':
             $class = 'reminder';
             break;
         default:
             $class = strtolower($className);
             break;
     }
     if (array_key_exists($class, $tabs)) {
         $tabs[$class]['current'] = TRUE;
         $qfKey = $form->get('qfKey');
         if ($qfKey) {
             $tabs[$class]['qfKey'] = "&qfKey={$qfKey}";
         }
     }
     if ($eventID) {
         $reset = !empty($_GET['reset']) ? 'reset=1&' : '';
         foreach ($tabs as $key => $value) {
             if (!isset($tabs[$key]['qfKey'])) {
                 $tabs[$key]['qfKey'] = NULL;
             }
             $action = 'update';
             if ($key == 'reminder') {
                 $action = 'browse';
             }
             $link = "civicrm/event/manage/{$key}";
             $query = "{$reset}action={$action}&id={$eventID}&component=event{$tabs[$key]['qfKey']}";
             $tabs[$key]['link'] = isset($value['link']) ? $value['link'] : CRM_Utils_System::url($link, $query);
         }
     }
     return $tabs;
 }