/** * Implementation of hook_civicrm_install */ function hrvisa_civicrm_install() { if (!CRM_Core_OptionGroup::getValue('activity_type', 'Visa Expiration', 'name')) { // create activity_type 'Visa Expiration' $params = array('weight' => 1, 'label' => 'Visa Expiration', 'filter' => 0, 'is_active' => 1, 'is_default' => 0); $result = civicrm_api3('activity_type', 'create', $params); if (CRM_Utils_Array::value('is_error', $result, FALSE)) { CRM_Core_Error::debug_var("Failed to create activity type 'Visa Expiration'", $result); throw new CRM_Core_Exception('Failed to create activity type \'Visa Expiration\''); } $activityTypeId = $result['values'][$result['id']]['value']; } else { $activityTypeId = CRM_Core_OptionGroup::getValue('activity_type', 'Visa Expiration', 'name'); } // set weekly reminder for Visa Expiration activities (not active) // will be active when extension is enabled if (!empty($activityTypeId)) { $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name'); $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts); // schedule reminder for Visa Expiration Creation $result = civicrm_api3('action_schedule', 'get', array('name' => 'Visa Expiration Reminder')); if (empty($result['id'])) { $params = array('name' => 'Visa Expiration Reminder', 'title' => 'Visa Expiration Reminder', 'recipient' => $targetID, 'limit_to' => 1, 'entity_value' => $activityTypeId, 'entity_status' => CRM_Core_OptionGroup::getValue('activity_status', 'Scheduled', 'name'), 'start_action_offset' => 1, 'start_action_unit' => 'week', 'start_action_condition' => 'before', 'start_action_date' => 'activity_date_time', 'is_repeat' => 0, 'is_active' => 0, 'body_html' => '<p>Your latest visa expiries on {activity.activity_date_time}</p>', 'subject' => 'Reminder for Visa Expiration', 'record_activity' => 1, 'mapping_id' => CRM_Core_DAO::getFieldValue('CRM_Core_DAO_ActionMapping', 'activity_type', 'id', 'entity_value')); $result = civicrm_api3('action_schedule', 'create', $params); } } return _hrvisa_civix_civicrm_install(); }
/** * Build all the data structures needed to build the form. */ public function preProcess() { $this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this); // this mean it's a batch action if (!$this->_id) { if (!empty($_GET['batch_id'])) { // validate batch ids $batchIds = explode(',', $_GET['batch_id']); foreach ($batchIds as $batchId) { CRM_Utils_Type::validate($batchId, 'Positive'); } $this->_batchIds = $_GET['batch_id']; $this->set('batchIds', $this->_batchIds); } else { $this->_batchIds = $this->get('batchIds'); } if (!empty($_GET['export_format']) && in_array($_GET['export_format'], array('IIF', 'CSV'))) { $this->_exportFormat = $_GET['export_format']; } } else { $this->_batchIds = $this->_id; } $allBatchStatus = CRM_Core_PseudoConstant::get('CRM_Batch_DAO_Batch', 'status_id'); $this->_exportStatusId = CRM_Utils_Array::key('Exported', $allBatchStatus); // check if batch status is valid, do not allow exported batches to export again $batchStatus = CRM_Batch_BAO_Batch::getBatchStatuses($this->_batchIds); foreach ($batchStatus as $batchStatusId) { if ($batchStatusId == $this->_exportStatusId) { CRM_Core_Error::fatal(ts('You cannot exported the batches which were exported earlier.')); } } $session = CRM_Core_Session::singleton(); $session->replaceUserContext(CRM_Utils_System::url('civicrm/financial/financialbatches', "reset=1&batchStatus={$this->_exportStatusId}")); }
/** * Set defaults for the form. * * @return array */ public function setDefaultValues() { $defaults = parent::setDefaultValues(); if (!empty($defaults['preferred_language'])) { $languages = CRM_Contact_BAO_Contact::buildOptions('preferred_language'); $defaults['preferred_language'] = CRM_Utils_Array::key($defaults['preferred_language'], $languages); } // CRM-7119: set preferred_language to default if unset if (empty($defaults['preferred_language'])) { $config = CRM_Core_Config::singleton(); $defaults['preferred_language'] = $config->lcMessages; } // CRM-19135: where CRM_Core_BAO_Contact::getValues() set label as a default value instead of reserved 'value', // the code is to ensure we always set default to value instead of label if (!empty($defaults['preferred_mail_format'])) { $defaults['preferred_mail_format'] = array_search($defaults['preferred_mail_format'], CRM_Core_SelectValues::pmf()); } if (empty($defaults['communication_style_id'])) { $defaults['communication_style_id'] = array_pop(CRM_Core_OptionGroup::values('communication_style', TRUE, NULL, NULL, 'AND is_default = 1')); } foreach (CRM_Contact_BAO_Contact::$_greetingTypes as $greeting) { $name = "{$greeting}_display"; $this->assign($name, CRM_Utils_Array::value($name, $defaults)); } return $defaults; }
/** * Class constructor. */ public function __construct() { // don’t display the ‘Add these Contacts to Group’ button $this->_add2groupSupported = FALSE; $dsn = defined('CIVICRM_LOGGING_DSN') ? DB::parseDSN(CIVICRM_LOGGING_DSN) : DB::parseDSN(CIVICRM_DSN); $this->loggingDB = $dsn['database']; // used for redirect back to contact summary $this->cid = CRM_Utils_Request::retrieve('cid', 'Integer', CRM_Core_DAO::$_nullObject); $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name'); $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts); $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts); $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts); $this->_logTables = array('log_civicrm_contact' => array('fk' => 'id'), 'log_civicrm_email' => array('fk' => 'contact_id', 'log_type' => 'Contact'), 'log_civicrm_phone' => array('fk' => 'contact_id', 'log_type' => 'Contact'), 'log_civicrm_address' => array('fk' => 'contact_id', 'log_type' => 'Contact'), 'log_civicrm_note' => array('fk' => 'entity_id', 'entity_table' => TRUE, 'bracket_info' => array('table' => 'log_civicrm_note', 'column' => 'subject')), 'log_civicrm_note_comment' => array('fk' => 'entity_id', 'table_name' => 'log_civicrm_note', 'joins' => array('table' => 'log_civicrm_note', 'join' => "entity_log_civireport.entity_id = fk_table.id AND entity_log_civireport.entity_table = 'civicrm_note'"), 'entity_table' => TRUE, 'bracket_info' => array('table' => 'log_civicrm_note', 'column' => 'subject')), 'log_civicrm_group_contact' => array('fk' => 'contact_id', 'bracket_info' => array('entity_column' => 'group_id', 'table' => 'log_civicrm_group', 'column' => 'title'), 'action_column' => 'status', 'log_type' => 'Group'), 'log_civicrm_entity_tag' => array('fk' => 'entity_id', 'bracket_info' => array('entity_column' => 'tag_id', 'table' => 'log_civicrm_tag', 'column' => 'name'), 'entity_table' => TRUE), 'log_civicrm_relationship' => array('fk' => 'contact_id_a', 'bracket_info' => array('entity_column' => 'relationship_type_id', 'table' => 'log_civicrm_relationship_type', 'column' => 'label_a_b')), 'log_civicrm_activity_for_target' => array('fk' => 'contact_id', 'table_name' => 'log_civicrm_activity', 'joins' => array('table' => 'log_civicrm_activity_contact', 'join' => "(entity_log_civireport.id = fk_table.activity_id AND fk_table.record_type_id = {$targetID})"), 'bracket_info' => array('entity_column' => 'activity_type_id', 'options' => CRM_Core_PseudoConstant::activityType(TRUE, TRUE, FALSE, 'label', TRUE)), 'log_type' => 'Activity'), 'log_civicrm_activity_for_assignee' => array('fk' => 'contact_id', 'table_name' => 'log_civicrm_activity', 'joins' => array('table' => 'log_civicrm_activity_contact', 'join' => "entity_log_civireport.id = fk_table.activity_id AND fk_table.record_type_id = {$assigneeID}"), 'bracket_info' => array('entity_column' => 'activity_type_id', 'options' => CRM_Core_PseudoConstant::activityType(TRUE, TRUE, FALSE, 'label', TRUE)), 'log_type' => 'Activity'), 'log_civicrm_activity_for_source' => array('fk' => 'contact_id', 'table_name' => 'log_civicrm_activity', 'joins' => array('table' => 'log_civicrm_activity_contact', 'join' => "entity_log_civireport.id = fk_table.activity_id AND fk_table.record_type_id = {$sourceID}"), 'bracket_info' => array('entity_column' => 'activity_type_id', 'options' => CRM_Core_PseudoConstant::activityType(TRUE, TRUE, FALSE, 'label', TRUE)), 'log_type' => 'Activity'), 'log_civicrm_case' => array('fk' => 'contact_id', 'joins' => array('table' => 'log_civicrm_case_contact', 'join' => 'entity_log_civireport.id = fk_table.case_id'), 'bracket_info' => array('entity_column' => 'case_type_id', 'options' => CRM_Case_PseudoConstant::caseType('title', FALSE)))); $logging = new CRM_Logging_Schema(); // build _logTables for contact custom tables $customTables = $logging->entityCustomDataLogTables('Contact'); foreach ($customTables as $table) { $this->_logTables[$table] = array('fk' => 'entity_id', 'log_type' => 'Contact'); } // build _logTables for address custom tables $customTables = $logging->entityCustomDataLogTables('Address'); foreach ($customTables as $table) { $this->_logTables[$table] = array('fk' => 'contact_id', 'joins' => array('table' => 'log_civicrm_address', 'join' => 'entity_log_civireport.entity_id = fk_table.id'), 'log_type' => 'Contact'); } // Allow log tables to be extended via report hooks. CRM_Report_BAO_Hook::singleton()->alterLogTables($this, $this->_logTables); parent::__construct(); }
function postProcess() { $session = CRM_Core_Session::singleton(); $params = $this->exportValues(); $result = civicrm_api3('OptionValue', 'create', array('value' => $params['hour_value'], 'id' => CRM_Utils_Array::key($params['hour_type_select'], $this->_id))); $session->pushUserContext(CRM_Utils_System::url('civicrm/hour/editoption', "&value={$params['hour_value']}")); }
function diffsInTable($table, $contactID = null) { $diffs = array(); $params = array(1 => array($this->log_conn_id, 'Integer'), 2 => array($this->log_date, 'String')); $logging = new CRM_Logging_Schema(); $addressCustomTables = $logging->entityCustomDataLogTables('Address'); $contactIdClause = $join = ''; if ($contactID) { $params[3] = array($contactID, 'Integer'); switch ($table) { case 'civicrm_contact': $contactIdClause = "AND id = %3"; break; case 'civicrm_note': $contactIdClause = "AND (( entity_id = %3 AND entity_table = 'civicrm_contact' ) OR (entity_id IN (SELECT note.id FROM `{$this->db}`.log_civicrm_note note WHERE note.entity_id = %3 AND note.entity_table = 'civicrm_contact') AND entity_table = 'civicrm_note'))"; break; case 'civicrm_entity_tag': $contactIdClause = "AND entity_id = %3 AND entity_table = 'civicrm_contact'"; break; case 'civicrm_relationship': $contactIdClause = "AND (contact_id_a = %3 OR contact_id_b = %3)"; break; case 'civicrm_activity': $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name'); $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts); $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts); $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts); $join = "\nLEFT JOIN civicrm_activity_contact at ON at.activity_id = lt.id AND at.contact_id = %3 AND at.record_type_id = {$targetID}\nLEFT JOIN civicrm_activity_contact aa ON aa.activity_id = lt.id AND aa.contact_id = %3 AND aa.record_type_id = {$assigneeID}\nLEFT JOIN civicrm_activity_contact source ON source.activity_id = lt.id AND source.contact_id = %3 AND source.record_type_id = {$sourceID} "; $contactIdClause = "AND (at.id IS NOT NULL OR aa.id IS NOT NULL OR source.id IS NOT NULL)"; break; case 'civicrm_case': $contactIdClause = "AND id = (select case_id FROM civicrm_case_contact WHERE contact_id = %3 LIMIT 1)"; break; default: if (array_key_exists($table, $addressCustomTables)) { $join = "INNER JOIN `{$this->db}`.`log_civicrm_address` et ON et.id = lt.entity_id"; $contactIdClause = "AND contact_id = %3"; break; } // allow tables to be extended by report hook query objects list($contactIdClause, $join) = CRM_Report_BAO_Hook::singleton()->logDiffClause($this, $table); if (empty($contactIdClause)) { $contactIdClause = "AND contact_id = %3"; } if (strpos($table, 'civicrm_value') !== false) { $contactIdClause = "AND entity_id = %3"; } } } // find ids in this table that were affected in the given connection (based on connection id and a ±10 s time period around the date) $sql = "\nSELECT DISTINCT lt.id FROM `{$this->db}`.`log_{$table}` lt\n{$join}\nWHERE lt.log_conn_id = %1 AND\n lt.log_date BETWEEN DATE_SUB(%2, INTERVAL {$this->interval}) AND DATE_ADD(%2, INTERVAL {$this->interval})\n {$contactIdClause}"; $dao = CRM_Core_DAO::executeQuery($sql, $params); while ($dao->fetch()) { $diffs = array_merge($diffs, $this->diffsInTableForId($table, $dao->id)); } return $diffs; }
static function sync($contactId) { // get visa required value $getInfo = array('entity_id' => $contactId, 'return.Extended_Demographics:Is_Visa_Required' => 1); $isVisaRequired = civicrm_api3('custom_value', 'get', $getInfo); $isVisaRequired = $isVisaRequired['count'] ? $isVisaRequired['values']["{$isVisaRequired['id']}"][0] : 0; // this api call will get visa expiration date // of immigration records for the contact $getInfo = array('entity_id' => $contactId, 'return.Immigration:End_Date' => 1); $immigrationDateInfo = civicrm_api3('custom_value', 'get', $getInfo); $lastestVisaExpirationDate = NULL; if ($immigrationDateInfo['count'] > 0) { $lastestVisaExpirationDate = $immigrationDateInfo['values']["{$immigrationDateInfo['id']}"]['latest']; } // activity processing if immigration data found if ($immigrationDateInfo['count']) { // get 'Visa Expiration' activity for this contact $activityTypeId = CRM_Core_OptionGroup::getValue('activity_type', 'Visa Expiration', 'name'); $activityStatuses = CRM_Core_OptionGroup::values('activity_status', FALSE, FALSE, FALSE, NULL, 'name'); // to check if visa expiration activity exists for the input target_contact_id $activityGetParams = array('contact_id' => $contactId, 'activity_type_id' => $activityTypeId, 'sequential' => 1); // note : using filter 'activity_type_id' in combination with 'contact_id' filter doesn't work $activities = civicrm_api3('activity', 'get', $activityGetParams); $activityId = NULL; $count = 0; foreach ($activities['values'] as $val) { if ($val['activity_type_id'] != $activityTypeId || !array_key_exists('targets', $val)) { continue; } $activityId = $val['id']; $count++; } if ($count) { $activityParams = array(); $activityParams['status_id'] = $isVisaRequired ? CRM_Utils_Array::key('Scheduled', $activityStatuses) : CRM_Utils_Array::key('Cancelled', $activityStatuses); $activityParams['activity_date_time'] = $lastestVisaExpirationDate; // check if count is one, if not log a error if ($count > 1) { // update the last activity and log a error $logError = "Multiple 'Visa Expiration' activities exists for target contact with id : {$contactId}, so updating last activity with id : {$activityId}"; CRM_Core_Error::debug_log_message($logError); } $activityParams['id'] = $activityId; $result = civicrm_api3('activity', 'create', $activityParams); } else { // if no activity create a new one only if 'visa is required' if ($isVisaRequired) { $activityParams = array('target_contact_id' => $contactId, 'activity_type_id' => $activityTypeId, 'subject' => 'Visa Expiration', 'activity_date_time' => $lastestVisaExpirationDate, 'status_id' => CRM_Utils_Array::key('Scheduled', $activityStatuses), 'details' => 'Visa Expiration'); $result = civicrm_api3('activity', 'create', $activityParams); } } } // end of if for immgration info check }
/** * Get duration of absences, in minutes. * * @param array $absenceTypeNames * @param $periodId * * @return int */ private static function getAbsenceDuration($absenceTypeNames = array(), $periodId) { $absenceTypeIds = static::getActivityIdsForAbsenceTypeNames($absenceTypeNames, $periodId); $activityStatuses = CRM_HRAbsence_BAO_HRAbsenceType::getActivityStatus('name'); $sql = "\n SELECT SUM(a1.duration) duration\n FROM civicrm_activity a\n\n INNER JOIN civicrm_activity_contact ac\n ON a.id = ac.activity_id\n\n INNER JOIN civicrm_contact c\n ON (ac.contact_id = c.id AND c.contact_type = 'Individual')\n\n INNER JOIN civicrm_hrjobcontract jc\n ON c.id = jc.contact_id AND jc.is_primary = 1\n\n INNER JOIN civicrm_hrjobcontract_revision jcr\n ON (jc.id = jcr.jobcontract_id AND jcr.effective_date <= NOW())\n\n INNER JOIN civicrm_hrjobcontract_details jcd\n ON (jcr.id = jcd.jobcontract_revision_id AND (jcd.period_end_date >= NOW() OR jcd.period_end_date IS NULL))\n\n INNER JOIN civicrm_activity a1\n ON (a.id = a1.source_record_id AND a1.activity_type_id = %1 AND a1.status_id = %2)\n\n WHERE\n a.id IN (" . implode(',', $absenceTypeIds) . ")\n AND a.status_id = %2\n "; $params = array(1 => array(static::getAbsenceActivityTypeId(), 'Integer'), 2 => array(CRM_Utils_Array::key('Completed', $activityStatuses), 'Integer')); $duration = 0; $dao = CRM_Core_DAO::executeQuery($sql, $params); if ($dao->fetch()) { $duration = $dao->duration; } return $duration; }
/** * Activity.GetAbsences API * * This is a variation on Activity.get with additional filtering behavior suitable for activities. * * @param array $params * @return array API result descriptor * @see civicrm_api3_create_success * @see civicrm_api3_create_error * @throws API_Exception */ function civicrm_api3_activity_getabsences($params) { // activity_type_id: int|string|array(int|string) // period_id: int|array(int) // target_contact_id: int $activityTypes = CRM_Core_PseudoConstant::activityType(); // ****** Defaults ****** if (!isset($params['activity_type_id'])) { $params['activity_type_id'] = CRM_HRAbsence_BAO_HRAbsenceType::getActivityTypes(); } // ****** Build query ****** $select = new CRM_HRAbsence_DGWDIHTWT('civicrm_activity request'); $select->select('request.*')->groupBy('request.id')->join('absence', 'INNER JOIN civicrm_activity absence ON (absence.source_record_id = request.id AND absence.activity_type_id = #typeId)', array('#typeId' => array_search('Absence', $activityTypes))); if (!empty($params['period_id'])) { $periodIds = (array) $params['period_id']; $dateExprs = array(); // array(string $sqlExpression) foreach ($periodIds as $periodId) { $period = civicrm_api3('HRAbsencePeriod', 'getsingle', array('id' => $periodId)); $dateExprs[] = $select->interpolate('min(absence.activity_date_time) between @start and @end', array('@start' => $period['start_date'], '@end' => $period['end_date'])); } $select->having(implode(' or ', $dateExprs)); } if (!empty($params['activity_type_id'])) { $typeIds = (array) $params['activity_type_id']; foreach (array_keys($typeIds) as $key) { if (!is_numeric($typeIds[$key])) { $typeIds[$key] = array_search($typeIds[$key], $activityTypes); if ($typeIds[$key] === FALSE) { throw new API_Exception("Invalid activity type"); } } } $select->where('request.activity_type_id IN (#typeIds)', array('#typeIds' => $typeIds)); } if (!empty($params['target_contact_id'])) { $activityContactTypes = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name'); $select->join('tgt', 'INNER JOIN civicrm_activity_contact tgt ON tgt.activity_id = request.id AND tgt.record_type_id = #tgt AND tgt.contact_id IN (#targetIds)', array('#tgt' => CRM_Utils_Array::key('Activity Targets', $activityContactTypes), '#targetIds' => (array) $params['target_contact_id'])); } // ****** Execute query ****** $entity = _civicrm_api3_get_BAO(__FUNCTION__); $bao = CRM_Core_DAO::executeQuery($select->toSQL(), array(), TRUE, 'CRM_Activity_BAO_Activity'); $activities = _civicrm_api3_dao_to_array($bao, $params, FALSE, $entity, FALSE); $activities = _civicrm_api3_activity_get_formatResult($params, $activities); return civicrm_api3_create_success($activities, $params, $entity, 'getAbsences'); }
function from() { $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name'); $roleID = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup', 'volunteer_role', 'id', 'name'); $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts); $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts); $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts); $this->_from = "\n FROM civicrm_activity {$this->_aliases['civicrm_activity']}\n LEFT JOIN civicrm_activity_contact {$this->_aliases['civicrm_activity_target']}\n ON {$this->_aliases['civicrm_activity']}.id = {$this->_aliases['civicrm_activity_target']}.activity_id AND\n {$this->_aliases['civicrm_activity_target']}.record_type_id = {$targetID}\n LEFT JOIN {$this->customGroup['table_name']} cg\n ON {$this->_aliases['civicrm_activity']}.id = cg.entity_id\n LEFT JOIN civicrm_volunteer_need n\n ON n.id = cg.{$this->customFields['volunteer_need_id']['column_name']}\n LEFT JOIN civicrm_option_value {$this->_aliases['role']} ON ( {$this->_aliases['role']}.value = cg.{$this->customFields['volunteer_role_id']['column_name']} AND {$this->_aliases['role']}.option_group_id = {$roleID} )\n LEFT JOIN civicrm_volunteer_project {$this->_aliases['project']}\n ON {$this->_aliases['project']}.id = n.project_id\n LEFT JOIN civicrm_activity_contact {$this->_aliases['civicrm_activity_assignment']}\n ON {$this->_aliases['civicrm_activity']}.id = {$this->_aliases['civicrm_activity_assignment']}.activity_id AND\n {$this->_aliases['civicrm_activity_assignment']}.record_type_id = {$assigneeID}\n LEFT JOIN civicrm_activity_contact {$this->_aliases['civicrm_activity_source']}\n ON {$this->_aliases['civicrm_activity']}.id = {$this->_aliases['civicrm_activity_source']}.activity_id AND\n {$this->_aliases['civicrm_activity_source']}.record_type_id = {$sourceID}\n LEFT JOIN civicrm_contact contact_civireport\n ON {$this->_aliases['civicrm_activity_target']}.contact_id = contact_civireport.id\n LEFT JOIN civicrm_contact civicrm_contact_assignee_civireport\n ON {$this->_aliases['civicrm_activity_assignment']}.contact_id = civicrm_contact_assignee_civireport.id\n LEFT JOIN civicrm_contact civicrm_contact_source\n ON {$this->_aliases['civicrm_activity_source']}.contact_id = civicrm_contact_source.id\n {$this->_aclFrom}\n LEFT JOIN civicrm_option_value\n ON ( {$this->_aliases['civicrm_activity']}.activity_type_id = civicrm_option_value.value )\n LEFT JOIN civicrm_option_group\n ON civicrm_option_group.id = civicrm_option_value.option_group_id\n LEFT JOIN civicrm_case_activity case_activity_civireport\n ON case_activity_civireport.activity_id = {$this->_aliases['civicrm_activity']}.id\n LEFT JOIN civicrm_case\n ON case_activity_civireport.case_id = civicrm_case.id\n LEFT JOIN civicrm_case_contact\n ON civicrm_case_contact.case_id = civicrm_case.id "; if ($this->isTableSelected('civicrm_email')) { $this->_from .= "\n LEFT JOIN civicrm_email civicrm_email_source\n ON {$this->_aliases['civicrm_activity_source']}.contact_id = civicrm_email_source.contact_id AND\n civicrm_email_source.is_primary = 1\n\n LEFT JOIN civicrm_email civicrm_email_target\n ON {$this->_aliases['civicrm_activity_target']}.contact_id = civicrm_email_target.contact_id AND\n civicrm_email_target.is_primary = 1\n\n LEFT JOIN civicrm_email civicrm_email_assignee\n ON {$this->_aliases['civicrm_activity_assignment']}.contact_id = civicrm_email_assignee.contact_id AND\n civicrm_email_assignee.is_primary = 1 "; } if ($this->isTableSelected('civicrm_phone')) { $this->_from .= "\n LEFT JOIN civicrm_phone civicrm_phone_source\n ON {$this->_aliases['civicrm_activity_source']}.contact_id = civicrm_phone_source.contact_id AND\n civicrm_phone_source.is_primary = 1\n\n LEFT JOIN civicrm_phone civicrm_phone_target\n ON {$this->_aliases['civicrm_activity_target']}.contact_id = civicrm_phone_target.contact_id AND\n civicrm_phone_target.is_primary = 1\n\n LEFT JOIN civicrm_phone civicrm_phone_assignee\n ON {$this->_aliases['civicrm_activity_assignment']}.contact_id = civicrm_phone_assignee.contact_id AND\n civicrm_phone_assignee.is_primary = 1 "; } }
/** * build all the data structures needed to build the form * * @return void * @access public */ function preProcess() { parent::preProcess(); $rows = array(); // display name and activity details of all selected contacts $activityIDs = implode(',', $this->_activityHolderIds); $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name'); $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts); $query = "\n SELECT at.subject as subject,\n ov.label as activity_type,\n at.activity_date_time as activity_date,\n ct.display_name as display_name\n FROM civicrm_activity at\nLEFT JOIN civicrm_activity_contact ac ON ( ac.activity_id = at.id AND ac.record_type_id = {$sourceID} )\nINNER JOIN civicrm_contact ct ON ( ac.contact_id = ct.id )\n LEFT JOIN civicrm_option_group og ON ( og.name = 'activity_type' )\n LEFT JOIN civicrm_option_value ov ON (at.activity_type_id = ov.value AND og.id = ov.option_group_id )\n WHERE at.id IN ( {$activityIDs} )"; $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray); while ($dao->fetch()) { $rows[] = array('subject' => $dao->subject, 'activity_type' => $dao->activity_type, 'activity_date' => $dao->activity_date, 'display_name' => $dao->display_name); } $this->assign('rows', $rows); }
/** * Test create with scheduled dates. */ public function testActionScheduleWithScheduledDatesCreate() { $oldCount = CRM_Core_DAO::singleValueQuery('select count(*) from civicrm_action_schedule'); $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name'); $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts); $scheduledStatus = CRM_Core_OptionGroup::getValue('activity_status', 'Scheduled', 'name'); $activityTypeId = CRM_Core_OptionGroup::getValue('activity_type', "Meeting", 'name'); $title = "simpleActionSchedule" . substr(sha1(rand()), 0, 7); $params = array('title' => $title, 'recipient' => $assigneeID, 'limit_to' => 1, 'entity_value' => $activityTypeId, 'entity_status' => $scheduledStatus, 'is_active' => 1, 'record_activity' => 1, 'mapping_id' => CRM_Activity_ActionMapping::ACTIVITY_MAPPING_ID, 'start_action_offset' => 3, 'start_action_unit' => 'day', 'start_action_condition' => 'before', 'start_action_date' => 'activity_date_time', 'is_repeat' => 1, 'repetition_frequency_unit' => 'day', 'repetition_frequency_interval' => 3, 'end_frequency_unit' => 'hour', 'end_frequency_interval' => 0, 'end_action' => 'before', 'end_date' => 'activity_date_time', 'body_html' => 'Test description', 'subject' => 'Test subject'); $actionSchedule = $this->callAPISuccess('action_schedule', 'create', $params); $this->assertTrue(is_numeric($actionSchedule['id'])); $this->assertTrue($actionSchedule['id'] > 0); $this->assertEquals($actionSchedule['values'][$actionSchedule['id']]['start_action_offset'][0], $params['start_action_offset']); $newCount = CRM_Core_DAO::singleValueQuery('select count(*) from civicrm_action_schedule'); $this->assertEquals($oldCount + 1, $newCount); }
/** * set defaults for the form * * @return array * @access public */ public function setDefaultValues() { $defaults = parent::setDefaultValues(); if (!empty($defaults['preferred_language'])) { $languages = CRM_Contact_BAO_Contact::buildOptions('preferred_language'); $defaults['preferred_language'] = CRM_Utils_Array::key($defaults['preferred_language'], $languages); } // CRM-7119: set preferred_language to default if unset if (empty($defaults['preferred_language'])) { $config = CRM_Core_Config::singleton(); $defaults['preferred_language'] = $config->lcMessages; } foreach (CRM_Contact_BAO_Contact::$_greetingTypes as $greeting) { $name = "{$greeting}_display"; $this->assign($name, CRM_Utils_Array::value($name, $defaults)); } return $defaults; }
/** * Pre processing. * * @return void */ public function preProcess() { // Ensure user has permission to be here if (!CRM_Core_Permission::check('administer dedupe rules')) { CRM_Utils_System::permissionDenied(); CRM_Utils_System::civiExit(); } $this->_options = CRM_Core_SelectValues::getDedupeRuleTypes(); $this->_rgid = CRM_Utils_Request::retrieve('id', 'Positive', $this, FALSE, 0); $this->_contactType = CRM_Utils_Request::retrieve('contact_type', 'String', $this, FALSE, 0); if ($this->_rgid) { $rgDao = new CRM_Dedupe_DAO_RuleGroup(); $rgDao->id = $this->_rgid; $rgDao->find(TRUE); $this->_defaults['threshold'] = $rgDao->threshold; $this->_contactType = $rgDao->contact_type; $this->_defaults['used'] = CRM_Utils_Array::key($rgDao->used, $this->_options); $this->_defaults['title'] = $rgDao->title; $this->_defaults['name'] = $rgDao->name; $this->_defaults['is_reserved'] = $rgDao->is_reserved; $this->assign('isReserved', $rgDao->is_reserved); $this->assign('ruleName', $rgDao->name); $ruleDao = new CRM_Dedupe_DAO_Rule(); $ruleDao->dedupe_rule_group_id = $this->_rgid; $ruleDao->find(); $count = 0; while ($ruleDao->fetch()) { $this->_defaults["where_{$count}"] = "{$ruleDao->rule_table}.{$ruleDao->rule_field}"; $this->_defaults["length_{$count}"] = $ruleDao->rule_length; $this->_defaults["weight_{$count}"] = $ruleDao->rule_weight; $count++; } } $supported = CRM_Dedupe_BAO_RuleGroup::supportedFields($this->_contactType); if (is_array($supported)) { foreach ($supported as $table => $fields) { foreach ($fields as $field => $title) { $this->_fields["{$table}.{$field}"] = $title; } } } asort($this->_fields); }
function getSmartDebitPayments($referenceNumber) { $paymentProcessorType = CRM_Core_PseudoConstant::paymentProcessorType(false, null, 'name'); $paymentProcessorTypeId = CRM_Utils_Array::key('Smart Debit', $paymentProcessorType); $domainID = CRM_Core_Config::domainID(); $sql = " SELECT user_name "; $sql .= " , password "; $sql .= " , signature "; $sql .= " FROM civicrm_payment_processor "; $sql .= " WHERE payment_processor_type_id = %1"; $sql .= " AND is_test= %2 AND domain_id = %3"; $params = array(1 => array($paymentProcessorTypeId, 'Integer'), 2 => array('0', 'Int'), 3 => array($domainID, 'Int')); $dao = CRM_Core_DAO::executeQuery($sql, $params); if ($dao->fetch()) { $username = $dao->user_name; $password = $dao->password; $pslid = $dao->signature; } // Send payment POST to the target URL $url = "https://secure.ddprocessing.co.uk/api/data/dump?query[service_user][pslid]={$pslid}&query[report_format]=XML"; // Restrict to a single payer if we have a reference if ($referenceNumber) { $url .= "&query[reference_number]={$referenceNumber}"; } $response = self::requestPost($url, $username, $password); // Take action based upon the response status switch (strtoupper($response["Status"])) { case 'OK': $smartDebitArray = array(); // Cater for a single response if (isset($response['Data']['PayerDetails']['@attributes'])) { $smartDebitArray[] = $response['Data']['PayerDetails']['@attributes']; } else { foreach ($response['Data']['PayerDetails'] as $key => $value) { $smartDebitArray[] = $value['@attributes']; } } return $smartDebitArray; default: return false; } }
function from() { $this->_from = null; $allStatus = CRM_Contribute_PseudoConstant::contributionStatus(null, 'name'); $pendingStatus = array_search('Pending', $allStatus); foreach (array('Pending', 'In Progress', 'Overdue') as $statusKey) { if ($key = CRM_Utils_Array::key($statusKey, $allStatus)) { $unpaidStatus[] = $key; } } $statusIds = implode(', ', $unpaidStatus); $this->_from = "\n FROM civicrm_contact {$this->_aliases['civicrm_contact']} {$this->_aclFrom}\n INNER JOIN civicrm_pledge {$this->_aliases['civicrm_pledge']} \n ON ({$this->_aliases['civicrm_pledge']}.contact_id =\n {$this->_aliases['civicrm_contact']}.id) AND \n {$this->_aliases['civicrm_pledge']}.status_id IN ( {$statusIds} )\n LEFT JOIN civicrm_pledge_payment {$this->_aliases['civicrm_pledge_payment']}\n ON ({$this->_aliases['civicrm_pledge']}.id =\n {$this->_aliases['civicrm_pledge_payment']}.pledge_id AND {$this->_aliases['civicrm_pledge_payment']}.status_id = {$pendingStatus} ) "; // include address field if address column is to be included if ($this->_addressField) { $this->_from .= "\n LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']} \n ON ({$this->_aliases['civicrm_contact']}.id = \n {$this->_aliases['civicrm_address']}.contact_id) AND\n {$this->_aliases['civicrm_address']}.is_primary = 1\n"; } // include email field if email column is to be included if ($this->_emailField) { $this->_from .= "\n LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']} \n ON ({$this->_aliases['civicrm_contact']}.id = \n {$this->_aliases['civicrm_email']}.contact_id) AND \n {$this->_aliases['civicrm_email']}.is_primary = 1\n"; } }
function hrui_civicrm_buildForm($formName, &$form) { CRM_Core_Resources::singleton()->addStyleFile('org.civicrm.hrui', 'css/hrui.css')->addScriptFile('org.civicrm.hrui', 'js/hrui.js'); if ($form instanceof CRM_Contact_Form_Contact) { CRM_Core_Resources::singleton()->addSetting(array('formName' => 'contactForm')); //HR-358 - Set default values //set default value to phone location and type $locationId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_LocationType', 'Main', 'id', 'name'); $result = civicrm_api3('LocationType', 'create', array('id' => $locationId, 'is_default' => 1, 'is_active' => 1)); if ($form->elementExists('phone[2][phone_type_id]') && $form->elementExists('phone[2][phone_type_id]')) { $phoneType = $form->getElement('phone[2][phone_type_id]'); $phoneValue = CRM_Core_OptionGroup::values('phone_type'); $phoneKey = CRM_Utils_Array::key('Mobile', $phoneValue); $phoneType->setSelected($phoneKey); $phoneLocation = $form->getElement('phone[2][location_type_id]'); $phoneLocation->setSelected($locationId); } } $ogID = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup', 'type_20130502144049', 'id', 'name'); //HR-355 -- Add Government ID if ($formName == 'CRM_Contact_Form_Contact' && $ogID && $form->_contactType == 'Individual') { //add government fields $contactID = CRM_Utils_Request::retrieve('cid', 'Integer', $form); $templatePath = CRM_Extension_System::singleton()->getMapper()->keyToBasePath('org.civicrm.hrui') . '/templates'; $form->add('text', 'GovernmentId', ts('Government ID')); $form->addElement('select', "govTypeOptions", '', CRM_Core_BAO_OptionValue::getOptionValuesAssocArray($ogID)); CRM_Core_Region::instance('page-body')->add(array('template' => "{$templatePath}/CRM/HRUI/Form/contactField.tpl")); $action = CRM_Utils_Request::retrieve('action', 'String', $form); $govVal = CRM_HRIdent_Page_HRIdent::retreiveContactFieldValue($contactID); //set default to government type option $default = array(); $default['govTypeOptions'] = CRM_Core_BAO_CustomField::getOptionGroupDefault($ogID, 'select'); if ($action == CRM_Core_Action::UPDATE && !empty($govVal)) { //set key for updating specific record of contact id in custom value table $default['govTypeOptions'] = CRM_Utils_Array::value('type', $govVal); $default['GovernmentId'] = CRM_Utils_Array::value('typeNumber', $govVal); } $form->setDefaults($default); } }
/** * Returns all the rows in the given offset and rowCount. * * @param string $action * The action being performed. * @param int $offset * The row number to start from. * @param int $rowCount * The number of rows to return. * @param string $sort * The sql string that describes the sort order. * @param string $output * What should the result set include (web/email/csv). * * @return array * rows in the given offset and rowCount */ public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) { $result = $this->_query->searchQuery($offset, $rowCount, $sort, FALSE, FALSE, FALSE, FALSE, FALSE, $this->_activityClause); $rows = array(); $mailingIDs = CRM_Mailing_BAO_Mailing::mailingACLIDs(); $accessCiviMail = CRM_Core_Permission::check('access CiviMail'); //get all campaigns. $allCampaigns = CRM_Campaign_BAO_Campaign::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE); $engagementLevels = CRM_Campaign_PseudoConstant::engagementLevel(); $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name'); $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts); $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts); $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts); //get all activity types $activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, TRUE, FALSE, 'name', TRUE); while ($result->fetch()) { $row = array(); // ignore rows where we dont have an activity id if (empty($result->activity_id)) { continue; } // the columns we are interested in foreach (self::$_properties as $property) { if (isset($result->{$property})) { $row[$property] = $result->{$property}; } } $contactId = CRM_Utils_Array::value('contact_id', $row); if (!$contactId) { $contactId = CRM_Utils_Array::value('source_contact_id', $row); } $row['target_contact_name'] = CRM_Activity_BAO_ActivityContact::getNames($row['activity_id'], $targetID); $row['assignee_contact_name'] = CRM_Activity_BAO_ActivityContact::getNames($row['activity_id'], $assigneeID); list($row['source_contact_name'], $row['source_contact_id']) = CRM_Activity_BAO_ActivityContact::getNames($row['activity_id'], $sourceID, TRUE); $row['source_contact_name'] = implode(',', array_values($row['source_contact_name'])); $row['source_contact_id'] = implode(',', $row['source_contact_id']); if ($this->_context == 'search') { $row['checkbox'] = CRM_Core_Form::CB_PREFIX . $result->activity_id; } $row['contact_type'] = CRM_Contact_BAO_Contact_Utils::getImage($result->contact_sub_type ? $result->contact_sub_type : $result->contact_type, FALSE, $result->contact_id); $accessMailingReport = FALSE; $activityTypeId = $row['activity_type_id']; if ($row['activity_is_test']) { $row['activity_type'] = $row['activity_type'] . " (test)"; } $bulkActivityTypeID = CRM_Utils_Array::key('Bulk Email', $activityTypes); $row['mailingId'] = ''; if ($accessCiviMail && ($mailingIDs === TRUE || in_array($result->source_record_id, $mailingIDs)) && $bulkActivityTypeID == $activityTypeId) { $row['mailingId'] = CRM_Utils_System::url('civicrm/mailing/report', "mid={$result->source_record_id}&reset=1&cid={$contactId}&context=activitySelector"); $row['recipients'] = ts('(recipients)'); $row['target_contact_name'] = ''; $row['assignee_contact_name'] = ''; $accessMailingReport = TRUE; } $activityActions = new CRM_Activity_Selector_Activity($result->contact_id, NULL); $actionLinks = $activityActions->actionLinks($activityTypeId, CRM_Utils_Array::value('source_record_id', $row), $accessMailingReport, CRM_Utils_Array::value('activity_id', $row), $this->_key, $this->_compContext); $row['action'] = CRM_Core_Action::formLink($actionLinks, NULL, array('id' => $result->activity_id, 'cid' => $contactId, 'cxt' => $this->_context), ts('more'), FALSE, 'activity.selector.row', 'Activity', $result->activity_id); //carry campaign to selector. $row['campaign'] = CRM_Utils_Array::value($result->activity_campaign_id, $allCampaigns); $row['campaign_id'] = $result->activity_campaign_id; if ($engagementLevel = CRM_Utils_Array::value('activity_engagement_level', $row)) { $row['activity_engagement_level'] = CRM_Utils_Array::value($engagementLevel, $engagementLevels, $engagementLevel); } //Check if recurring activity $repeat = CRM_Core_BAO_RecurringEntity::getPositionAndCount($row['activity_id'], 'civicrm_activity'); $row['repeat'] = ''; if ($repeat) { $row['repeat'] = ts('Repeating (%1 of %2)', array(1 => $repeat[0], 2 => $repeat[1])); } $rows[] = $row; } return $rows; }
/** * Do the set default related to location type id, * primary location, default country */ public function blockSetDefaults(&$defaults) { $locationTypeKeys = array_filter(array_keys(CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id')), 'is_int'); sort($locationTypeKeys); // get the default location type $locationType = CRM_Core_BAO_LocationType::getDefault(); // unset primary location type $primaryLocationTypeIdKey = CRM_Utils_Array::key($locationType->id, $locationTypeKeys); unset($locationTypeKeys[$primaryLocationTypeIdKey]); // reset the array sequence $locationTypeKeys = array_values($locationTypeKeys); // get default phone and im provider id. $defPhoneTypeId = key(CRM_Core_OptionGroup::values('phone_type', FALSE, FALSE, FALSE, ' AND is_default = 1')); $defIMProviderId = key(CRM_Core_OptionGroup::values('instant_messenger_service', FALSE, FALSE, FALSE, ' AND is_default = 1')); $defWebsiteTypeId = key(CRM_Core_OptionGroup::values('website_type', FALSE, FALSE, FALSE, ' AND is_default = 1')); $allBlocks = $this->_blocks; if (array_key_exists('Address', $this->_editOptions)) { $allBlocks['Address'] = $this->_editOptions['Address']; } $config = CRM_Core_Config::singleton(); foreach ($allBlocks as $blockName => $label) { $name = strtolower($blockName); $hasPrimary = $updateMode = FALSE; // user is in update mode. if (array_key_exists($name, $defaults) && !CRM_Utils_System::isNull($defaults[$name])) { $updateMode = TRUE; } for ($instance = 1; $instance <= $this->get($blockName . '_Block_Count'); $instance++) { // make we require one primary block, CRM-5505 if ($updateMode) { if (!$hasPrimary) { $hasPrimary = CRM_Utils_Array::value('is_primary', CRM_Utils_Array::value($instance, $defaults[$name])); } continue; } //set location to primary for first one. if ($instance == 1) { $hasPrimary = TRUE; $defaults[$name][$instance]['is_primary'] = TRUE; $defaults[$name][$instance]['location_type_id'] = $locationType->id; } else { $locTypeId = isset($locationTypeKeys[$instance - 1]) ? $locationTypeKeys[$instance - 1] : $locationType->id; $defaults[$name][$instance]['location_type_id'] = $locTypeId; } //set default country if ($name == 'address' && $config->defaultContactCountry) { $defaults[$name][$instance]['country_id'] = $config->defaultContactCountry; } //set default state/province if ($name == 'address' && $config->defaultContactStateProvince) { $defaults[$name][$instance]['state_province_id'] = $config->defaultContactStateProvince; } //set default phone type. if ($name == 'phone' && $defPhoneTypeId) { $defaults[$name][$instance]['phone_type_id'] = $defPhoneTypeId; } //set default website type. if ($name == 'website' && $defWebsiteTypeId) { $defaults[$name][$instance]['website_type_id'] = $defWebsiteTypeId; } //set default im provider. if ($name == 'im' && $defIMProviderId) { $defaults[$name][$instance]['provider_id'] = $defIMProviderId; } } if (!$hasPrimary) { $defaults[$name][1]['is_primary'] = TRUE; } } }
/** * Build the form object. * * * @param CRM_Core_Form $form * * @return void */ public static function buildQuickForm(&$form) { $toArray = array(); $providers = CRM_SMS_BAO_Provider::getProviders(NULL, NULL, TRUE, 'is_default desc'); $providerSelect = array(); foreach ($providers as $provider) { $providerSelect[$provider['id']] = $provider['title']; } $suppressedSms = 0; //here we are getting logged in user id as array but we need target contact id. CRM-5988 $cid = $form->get('cid'); if ($cid) { $form->_contactIds = array($cid); } $to = $form->add('text', 'to', ts('To'), array('class' => 'huge'), TRUE); $form->add('text', 'activity_subject', ts('Name The SMS'), array('class' => 'huge'), TRUE); $toSetDefault = TRUE; if (property_exists($form, '_context') && $form->_context == 'standalone') { $toSetDefault = FALSE; } // when form is submitted recompute contactIds $allToSMS = array(); if ($to->getValue()) { $allToPhone = explode(',', $to->getValue()); $form->_contactIds = array(); foreach ($allToPhone as $value) { list($contactId, $phone) = explode('::', $value); if ($contactId) { $form->_contactIds[] = $contactId; $form->_toContactPhone[] = $phone; } } $toSetDefault = TRUE; } //get the group of contacts as per selected by user in case of Find Activities if (!empty($form->_activityHolderIds)) { $extendTargetContacts = 0; $invalidActivity = 0; $validActivities = 0; foreach ($form->_activityHolderIds as $key => $id) { //valid activity check if (CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity', $id, 'subject', 'id') != self::RECIEVED_SMS_ACTIVITY_SUBJECT) { $invalidActivity++; continue; } $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name'); $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts); //target contacts limit check $ids = array_keys(CRM_Activity_BAO_ActivityContact::getNames($id, $targetID)); if (count($ids) > 1) { $extendTargetContacts++; continue; } $validActivities++; $form->_contactIds = empty($form->_contactIds) ? $ids : array_unique(array_merge($form->_contactIds, $ids)); } if (!$validActivities) { $errorMess = ""; if ($extendTargetContacts) { $errorMess = ts('One selected activity consists of more than one target contact.', array('count' => $extendTargetContacts, 'plural' => '%count selected activities consist of more than one target contact.')); } if ($invalidActivity) { $errorMess = $errorMess ? ' ' : ''; $errorMess .= ts('The selected activity is invalid.', array('count' => $invalidActivity, 'plural' => '%count selected activities are invalid.')); } CRM_Core_Error::statusBounce(ts("%1: SMS Reply will not be sent.", array(1 => $errorMess))); } } if (is_array($form->_contactIds) && !empty($form->_contactIds) && $toSetDefault) { $returnProperties = array('sort_name' => 1, 'phone' => 1, 'do_not_sms' => 1, 'is_deceased' => 1, 'display_name' => 1); list($form->_contactDetails) = CRM_Utils_Token::getTokenDetails($form->_contactIds, $returnProperties, FALSE, FALSE); // make a copy of all contact details $form->_allContactDetails = $form->_contactDetails; foreach ($form->_contactIds as $key => $contactId) { $value = $form->_contactDetails[$contactId]; //to check if the phone type is "Mobile" $phoneTypes = CRM_Core_OptionGroup::values('phone_type', TRUE, FALSE, FALSE, NULL, 'name'); if (CRM_Utils_System::getClassName($form) == 'CRM_Activity_Form_Task_SMS') { //to check for "if the contact id belongs to a specified activity type" $actDetails = CRM_Activity_BAO_Activity::getContactActivity($contactId); if (self::RECIEVED_SMS_ACTIVITY_SUBJECT != CRM_Utils_Array::retrieveValueRecursive($actDetails, 'subject')) { $suppressedSms++; unset($form->_contactDetails[$contactId]); continue; } } if (isset($value['phone_type_id']) && $value['phone_type_id'] != CRM_Utils_Array::value('Mobile', $phoneTypes) || $value['do_not_sms'] || empty($value['phone']) || !empty($value['is_deceased'])) { //if phone is not primary check if non-primary phone is "Mobile" if (!empty($value['phone']) && $value['phone_type_id'] != CRM_Utils_Array::value('Mobile', $phoneTypes) && empty($value['is_deceased'])) { $filter = array('do_not_sms' => 0); $contactPhones = CRM_Core_BAO_Phone::allPhones($contactId, FALSE, 'Mobile', $filter); if (count($contactPhones) > 0) { $mobilePhone = CRM_Utils_Array::retrieveValueRecursive($contactPhones, 'phone'); $form->_contactDetails[$contactId]['phone_id'] = CRM_Utils_Array::retrieveValueRecursive($contactPhones, 'id'); $form->_contactDetails[$contactId]['phone'] = $mobilePhone; $form->_contactDetails[$contactId]['phone_type_id'] = CRM_Utils_Array::value('Mobile', $phoneTypes); } else { $suppressedSms++; unset($form->_contactDetails[$contactId]); continue; } } else { $suppressedSms++; unset($form->_contactDetails[$contactId]); continue; } } if (isset($mobilePhone)) { $phone = $mobilePhone; } elseif (empty($form->_toContactPhone)) { $phone = $value['phone']; } else { $phone = CRM_Utils_Array::value($key, $form->_toContactPhone); } if ($phone) { $toArray[] = array('text' => '"' . $value['sort_name'] . '" (' . $phone . ')', 'id' => "{$contactId}::{$phone}"); } } if (empty($toArray)) { CRM_Core_Error::statusBounce(ts('Selected contact(s) do not have a valid Phone, or communication preferences specify DO NOT SMS, or they are deceased')); } } //activity related variables if (isset($invalidActivity)) { $form->assign('invalidActivity', $invalidActivity); } if (isset($extendTargetContacts)) { $form->assign('extendTargetContacts', $extendTargetContacts); } $form->assign('toContact', json_encode($toArray)); $form->assign('suppressedSms', $suppressedSms); $form->assign('totalSelectedContacts', count($form->_contactIds)); $form->add('select', 'sms_provider_id', ts('From'), $providerSelect, TRUE); CRM_Mailing_BAO_Mailing::commonCompose($form); if ($form->_single) { // also fix the user context stack if ($form->_context) { $url = CRM_Utils_System::url('civicrm/dashboard', 'reset=1'); } else { $url = CRM_Utils_System::url('civicrm/contact/view', "&show=1&action=browse&cid={$form->_contactIds[0]}&selectedChild=activity"); } $session = CRM_Core_Session::singleton(); $session->replaceUserContext($url); $form->addDefaultButtons(ts('Send SMS'), 'upload', 'cancel'); } else { $form->addDefaultButtons(ts('Send SMS'), 'upload'); } $form->addFormRule(array('CRM_Contact_Form_Task_SMSCommon', 'formRule'), $form); }
/** * Global validation rules for the form. * * @param array $values * Posted values of the form. * * @return array * list of errors to be posted back to the form */ public static function formRule($values) { $errors = array(); if (!empty($values['is_discount'])) { $occurDiscount = array_count_values($values['discount_name']); $countemptyrows = 0; $countemptyvalue = 0; for ($i = 1; $i <= self::NUM_DISCOUNT; $i++) { $start_date = $end_date = NULL; if (!empty($values['discount_name'][$i])) { if (!empty($values['discount_start_date'][$i])) { $start_date = $values['discount_start_date'][$i] ? CRM_Utils_Date::processDate($values['discount_start_date'][$i]) : 0; } if (!empty($values['discount_end_date'][$i])) { $end_date = $values['discount_end_date'][$i] ? CRM_Utils_Date::processDate($values['discount_end_date'][$i]) : 0; } if ($start_date && $end_date && strcmp($end_date, $start_date) < 0) { $errors["discount_end_date[{$i}]"] = ts('The discount end date cannot be prior to the start date.'); } if (!$start_date && !$end_date) { $errors["discount_start_date[{$i}]"] = $errors["discount_end_date[{$i}]"] = ts('Please specify either start date or end date.'); } if ($i > 1) { $end_date_1 = $values['discount_end_date'][$i - 1] ? CRM_Utils_Date::processDate($values['discount_end_date'][$i - 1]) : 0; if ($start_date && $end_date_1 && strcmp($end_date_1, $start_date) >= 0) { $errors["discount_start_date[{$i}]"] = ts('Select non-overlapping discount start date.'); } elseif (!$start_date && !$end_date_1) { $j = $i - 1; $errors["discount_start_date[{$i}]"] = $errors["discount_end_date[{$j}]"] = ts('Select either of the dates.'); } } foreach ($occurDiscount as $key => $value) { if ($value > 1 && $key != '') { if ($key == $values['discount_name'][$i]) { $errors['discount_name[' . $i . ']'] = ts('%1 is already used for Discount Name.', array(1 => $key)); } } } //validation for discount labels and values for ($index = self::NUM_OPTION; $index > 0; $index--) { $label = TRUE; if (empty($values['discounted_label'][$index]) && !empty($values['discounted_value'][$index][$i])) { $label = FALSE; if (!$label) { $errors["discounted_label[{$index}]"] = ts('Label cannot be empty.'); } } if (!empty($values['discounted_label'][$index])) { $duplicateIndex = CRM_Utils_Array::key($values['discounted_label'][$index], $values['discounted_label']); if (!($duplicateIndex === FALSE) && !($duplicateIndex == $index)) { $errors["discounted_label[{$index}]"] = ts('Duplicate label value'); } } if (empty($values['discounted_label'][$index]) && empty($values['discounted_value'][$index][$i])) { $countemptyrows++; } if (empty($values['discounted_value'][$index][$i])) { $countemptyvalue++; } } if (!empty($values['_qf_Fee_next']) && ($countemptyrows == 11 || $countemptyvalue == 11)) { $errors["discounted_label[1]"] = $errors["discounted_value[1][{$i}]"] = ts('At least one fee should be entered for your Discount Set. If you do not see the table to enter discount fees, click the "Add Discount Set to Fee Table" button.'); } } } } if ($values['is_monetary']) { //check if financial type is selected if (!$values['financial_type_id']) { $errors['financial_type_id'] = ts("Please select financial type."); } //check for the event fee label (mandatory) if (!$values['fee_label']) { $errors['fee_label'] = ts('Please enter the fee label for the paid event.'); } if (empty($values['price_set_id'])) { //check fee label and amount $check = 0; $optionKeys = array(); foreach ($values['label'] as $key => $val) { if (trim($val) && trim($values['value'][$key])) { $optionKeys[$key] = $key; $check++; } } $default = CRM_Utils_Array::value('default', $values); if ($default && !in_array($default, $optionKeys)) { $errors['default'] = ts('Please select an appropriate option as default.'); } if (!$check) { if (!$values['label'][1]) { $errors['label[1]'] = ts('Please enter a label for at least one fee level.'); } if (!$values['value'][1]) { $errors['value[1]'] = ts('Please enter an amount for at least one fee level.'); } } } if (isset($values['is_pay_later'])) { if (empty($values['pay_later_text'])) { $errors['pay_later_text'] = ts('Please enter the Pay Later prompt to be displayed on the Registration form.'); } if (empty($values['pay_later_receipt'])) { $errors['pay_later_receipt'] = ts('Please enter the Pay Later instructions to be displayed to your users.'); } } } return empty($errors) ? TRUE : $errors; }
/** * Process the view. * * * @return void */ public function preProcess() { $contactID = CRM_Utils_Request::retrieve('cid', 'Integer', $this, TRUE); $activityID = CRM_Utils_Request::retrieve('aid', 'Integer', $this, TRUE); $revs = CRM_Utils_Request::retrieve('revs', 'Boolean', CRM_Core_DAO::$_nullObject); $caseID = CRM_Utils_Request::retrieve('caseID', 'Boolean', CRM_Core_DAO::$_nullObject); $activitySubject = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity', $activityID, 'subject'); //check for required permissions, CRM-6264 if ($activityID && !CRM_Activity_BAO_Activity::checkPermission($activityID, CRM_Core_Action::VIEW)) { CRM_Core_Error::fatal(ts('You do not have permission to access this page.')); } $this->assign('contactID', $contactID); $this->assign('caseID', $caseID); // CRM-9145 $this->assign('activityID', $activityID); $xmlProcessor = new CRM_Case_XMLProcessor_Report(); $report = $xmlProcessor->getActivityInfo($contactID, $activityID, TRUE); $attachmentUrl = CRM_Core_BAO_File::attachmentInfo('civicrm_activity', $activityID); if ($attachmentUrl) { $report['fields'][] = array('label' => 'Attachment(s)', 'value' => $attachmentUrl, 'type' => 'Link'); } $tags = CRM_Core_BAO_EntityTag::getTag($activityID, 'civicrm_activity'); if (!empty($tags)) { $allTag = CRM_Core_PseudoConstant::get('CRM_Core_DAO_EntityTag', 'tag_id', array('onlyActive' => FALSE)); foreach ($tags as $tid) { $tags[$tid] = $allTag[$tid]; } $report['fields'][] = array('label' => 'Tags', 'value' => implode('<br />', $tags), 'type' => 'String'); } $this->assign('report', $report); $latestRevisionID = CRM_Activity_BAO_Activity::getLatestActivityId($activityID); $viewPriorActivities = array(); $priorActivities = CRM_Activity_BAO_Activity::getPriorAcitivities($activityID); foreach ($priorActivities as $activityId => $activityValues) { if (CRM_Case_BAO_Case::checkPermission($activityId, 'view', NULL, $contactID)) { $viewPriorActivities[$activityId] = $activityValues; } } if ($revs) { CRM_Utils_System::setTitle(ts('Activity Revision History')); $this->assign('revs', $revs); $this->assign('result', $viewPriorActivities); $this->assign('subject', $activitySubject); $this->assign('latestRevisionID', $latestRevisionID); } else { if (count($viewPriorActivities) > 1) { $this->assign('activityID', $activityID); } if ($latestRevisionID != $activityID) { $this->assign('latestRevisionID', $latestRevisionID); } } $parentID = CRM_Activity_BAO_Activity::getParentActivity($activityID); if ($parentID) { $this->assign('parentID', $parentID); } //viewing activity should get diplayed in recent list.CRM-4670 $activityTypeID = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity', $activityID, 'activity_type_id'); $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name'); $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts); $activityTargetContacts = CRM_Activity_BAO_ActivityContact::retrieveContactIdsByActivityId($activityID, $targetID); if (!empty($activityTargetContacts)) { $recentContactId = $activityTargetContacts[0]; } else { $recentContactId = $contactID; } if (!isset($caseID)) { $caseID = CRM_Core_DAO::getFieldValue('CRM_Case_DAO_CaseActivity', $activityID, 'case_id', 'activity_id'); } $url = CRM_Utils_System::url('civicrm/case/activity/view', "reset=1&aid={$activityID}&cid={$recentContactId}&caseID={$caseID}&context=home"); $recentContactDisplay = CRM_Contact_BAO_Contact::displayName($recentContactId); // add the recently created Activity $activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, TRUE); $title = ""; if (isset($activitySubject)) { $title = $activitySubject . ' - '; } $title = $title . $recentContactDisplay . ' (' . $activityTypes[$activityTypeID] . ')'; $recentOther = array(); if (CRM_Case_BAO_Case::checkPermission($activityID, 'edit')) { $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/case/activity', "reset=1&action=update&id={$activityID}&cid={$recentContactId}&caseid={$caseID}&context=home"); } if (CRM_Case_BAO_Case::checkPermission($activityID, 'delete')) { $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/case/activity', "reset=1&action=delete&id={$activityID}&cid={$recentContactId}&caseid={$caseID}&context=home"); } CRM_Utils_Recent::add($title, $url, $activityID, 'Activity', $recentContactId, $recentContactDisplay, $recentOther); }
/** * Return PCP Block info for dashboard. * * @param int $contactId * * @return array * array of Pcp if found */ public static function getPcpDashboardInfo($contactId) { $links = self::pcpLinks(); $query = "\nSELECT * FROM civicrm_pcp pcp\nWHERE pcp.is_active = 1\n AND pcp.contact_id = %1\nORDER BY page_type, page_id"; $params = array(1 => array($contactId, 'Integer')); $pcpInfoDao = CRM_Core_DAO::executeQuery($query, $params); $pcpInfo = array(); $hide = $mask = array_sum(array_keys($links['all'])); $contactPCPPages = array(); $event = CRM_Event_PseudoConstant::event(NULL, FALSE, "( is_template IS NULL OR is_template != 1 )"); $contribute = CRM_Contribute_PseudoConstant::contributionPage(); $pcpStatus = CRM_Contribute_PseudoConstant::pcpStatus(); $approved = CRM_Utils_Array::key('Approved', $pcpStatus); while ($pcpInfoDao->fetch()) { $mask = $hide; if ($links) { $replace = array('pcpId' => $pcpInfoDao->id, 'pcpBlock' => $pcpInfoDao->pcp_block_id, 'pageComponent' => $pcpInfoDao->page_type); } $pcpLink = $links['all']; $class = ''; if ($pcpInfoDao->status_id != $approved || $pcpInfoDao->is_active != 1) { $class = 'disabled'; if (!$pcpInfoDao->tellfriend) { $mask -= CRM_Core_Action::DETACH; } } if ($pcpInfoDao->is_active == 1) { $mask -= CRM_Core_Action::ENABLE; } else { $mask -= CRM_Core_Action::DISABLE; } $action = CRM_Core_Action::formLink($pcpLink, $mask, $replace, ts('more'), FALSE, 'pcp.dashboard.active', 'PCP', $pcpInfoDao->id); $component = $pcpInfoDao->page_type; $pageTitle = CRM_Utils_Array::value($pcpInfoDao->page_id, ${$component}); $pcpInfo[] = array('pageTitle' => $pageTitle, 'pcpId' => $pcpInfoDao->id, 'pcpTitle' => $pcpInfoDao->title, 'pcpStatus' => $pcpStatus[$pcpInfoDao->status_id], 'action' => $action, 'class' => $class); $contactPCPPages[$pcpInfoDao->page_type][] = $pcpInfoDao->page_id; } $excludePageClause = $clause = NULL; if (!empty($contactPCPPages)) { foreach ($contactPCPPages as $component => $entityIds) { $excludePageClause[] = "\n( target_entity_type = '{$component}'\nAND target_entity_id NOT IN ( " . implode(',', $entityIds) . ") )"; } $clause = ' AND ' . implode(' OR ', $excludePageClause); } $query = "\nSELECT *\nFROM civicrm_pcp_block block\nLEFT JOIN civicrm_pcp pcp ON pcp.pcp_block_id = block.id\nWHERE block.is_active = 1\n{$clause}\nGROUP BY block.id\nORDER BY target_entity_type, target_entity_id\n"; $pcpBlockDao = CRM_Core_DAO::executeQuery($query); $pcpBlock = array(); $mask = 0; while ($pcpBlockDao->fetch()) { if ($links) { $replace = array('pageId' => $pcpBlockDao->target_entity_id, 'pageComponent' => $pcpBlockDao->target_entity_type); } $pcpLink = $links['add']; $action = CRM_Core_Action::formLink($pcpLink, $mask, $replace, ts('more'), FALSE, 'pcp.dashboard.other', "{$pcpBlockDao->target_entity_type}_PCP", $pcpBlockDao->target_entity_id); $component = $pcpBlockDao->target_entity_type; if ($pageTitle = CRM_Utils_Array::value($pcpBlockDao->target_entity_id, ${$component})) { $pcpBlock[] = array('pageId' => $pcpBlockDao->target_entity_id, 'pageTitle' => $pageTitle, 'action' => $action); } } return array($pcpBlock, $pcpInfo); }
/** * Validate contact permission for * given operation on activity record. * * @param int $activityId activity record id. * @param string $operation user operation. * @param int $actTypeId activity type id. * @param int $contactId contact id/if not pass consider logged in * @param boolean $checkComponent do we need to check component enabled. * * @return boolean $allow true/false * @static */ static function checkPermission($activityId, $operation, $actTypeId = NULL, $contactId = NULL, $checkComponent = TRUE) { $allow = FALSE; if (!$actTypeId && $activityId) { $actTypeId = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity', $activityId, 'activity_type_id'); } if (!$activityId || !$operation || !$actTypeId) { return $allow; } //do check for civicase component enabled. if ($checkComponent) { static $componentEnabled; if (!isset($componentEnabled)) { $config = CRM_Core_Config::singleton(); $componentEnabled = FALSE; if (in_array('CiviCase', $config->enableComponents)) { $componentEnabled = TRUE; } } if (!$componentEnabled) { return $allow; } } //do check for cases. $caseActOperations = array('File On Case', 'Link Cases', 'Move To Case', 'Copy To Case'); if (in_array($operation, $caseActOperations)) { static $unclosedCases; if (!is_array($unclosedCases)) { $unclosedCases = self::getUnclosedCases(); } if ($operation == 'File On Case') { $allow = empty($unclosedCases) ? FALSE : TRUE; } else { $allow = count($unclosedCases) > 1 ? TRUE : FALSE; } } $actionOperations = array('view', 'edit', 'delete'); if (in_array($operation, $actionOperations)) { //do cache when user has non/supper permission. static $allowOperations; if (!is_array($allowOperations) || !array_key_exists($operation, $allowOperations)) { if (!$contactId) { $session = CRM_Core_Session::singleton(); $contactId = $session->get('userID'); } //check for permissions. $permissions = array('view' => array('access my cases and activities', 'access all cases and activities'), 'edit' => array('access my cases and activities', 'access all cases and activities'), 'delete' => array('delete activities')); //check for core permission. $hasPermissions = array(); $checkPermissions = CRM_Utils_Array::value($operation, $permissions); if (is_array($checkPermissions)) { foreach ($checkPermissions as $per) { if (CRM_Core_Permission::check($per)) { $hasPermissions[$operation][] = $per; } } } //has permissions. if (!empty($hasPermissions)) { //need to check activity object specific. if (in_array($operation, array('view', 'edit'))) { //do we have supper permission. if (in_array('access all cases and activities', $hasPermissions[$operation])) { $allowOperations[$operation] = $allow = TRUE; } else { //user has only access to my cases and activity. //here object specific permmions come in picture. //edit - contact must be source or assignee //view - contact must be source/assignee/target $isTarget = $isAssignee = $isSource = FALSE; $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name'); $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts); $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts); $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts); $target = new CRM_Activity_DAO_ActivityContact(); $target->record_type_id = $targetID; $target->activity_id = $activityId; $target->contact_id = $contactId; if ($target->find(TRUE)) { $isTarget = TRUE; } $assignee = new CRM_Activity_DAO_ActivityContact(); $assignee->activity_id = $activityId; $assignee->record_type_id = $assigneeID; $assignee->contact_id = $contactId; if ($assignee->find(TRUE)) { $isAssignee = TRUE; } $source = new CRM_Activity_DAO_ActivityContact(); $source->activity_id = $activityId; $source->record_type_id = $sourceID; $source->contact_id = $contactId; if ($source->find(TRUE)) { $isSource = TRUE; } if ($operation == 'edit') { if ($isAssignee || $isSource) { $allow = TRUE; } } if ($operation == 'view') { if ($isTarget || $isAssignee || $isSource) { $allow = TRUE; } } } } elseif (is_array($hasPermissions[$operation])) { $allowOperations[$operation] = $allow = TRUE; } } else { //contact do not have permission. $allowOperations[$operation] = FALSE; } } else { //use cache. //here contact might have supper/non permission. $allow = $allowOperations[$operation]; } } //do further only when operation is granted. if ($allow) { $activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, TRUE, FALSE, 'name'); //get the activity type name. $actTypeName = CRM_Utils_Array::value($actTypeId, $activityTypes); //do not allow multiple copy / edit action. $singletonNames = array('Open Case', 'Reassigned Case', 'Merge Case', 'Link Cases', 'Assign Case Role', 'Email', 'Inbound Email'); //do not allow to delete these activities, CRM-4543 $doNotDeleteNames = array('Open Case', 'Change Case Type', 'Change Case Status', 'Change Case Start Date'); //allow edit operation. $allowEditNames = array('Open Case'); // do not allow File on Case $doNotFileNames = array('Open Case', 'Change Case Type', 'Change Case Status', 'Change Case Start Date', 'Reassigned Case', 'Merge Case', 'Link Cases', 'Assign Case Role'); if (in_array($actTypeName, $singletonNames)) { $allow = FALSE; if ($operation == 'File On Case') { $allow = in_array($actTypeName, $doNotFileNames) ? FALSE : TRUE; } if (in_array($operation, $actionOperations)) { $allow = TRUE; if ($operation == 'edit') { $allow = in_array($actTypeName, $allowEditNames) ? TRUE : FALSE; } elseif ($operation == 'delete') { $allow = in_array($actTypeName, $doNotDeleteNames) ? FALSE : TRUE; } } } if ($allow && $operation == 'delete' && in_array($actTypeName, $doNotDeleteNames)) { $allow = FALSE; } if ($allow && $operation == 'File On Case' && in_array($actTypeName, $doNotFileNames)) { $allow = FALSE; } //check settings file for masking actions //on the basis the activity types //hide Edit link if activity type is NOT editable //(special case activities).CRM-5871 if ($allow && in_array($operation, $actionOperations)) { static $actionFilter = array(); if (!array_key_exists($operation, $actionFilter)) { $xmlProcessor = new CRM_Case_XMLProcessor_Process(); $actionFilter[$operation] = $xmlProcessor->get('Settings', 'ActivityTypes', FALSE, $operation); } if (array_key_exists($operation, $actionFilter[$operation]) && in_array($actTypeId, $actionFilter[$operation][$operation])) { $allow = FALSE; } } } return $allow; }
/** * returns all the rows in the given offset and rowCount * * @param enum $action the action being performed * @param int $offset the row number to start from * @param int $rowCount the number of rows to return * @param string $sort the sql string that describes the sort order * @param enum $output what should the result set include (web/email/csv) * * @return int the total number of rows for this action */ function &getRows($action, $offset, $rowCount, $sort, $output = NULL) { $config = CRM_Core_Config::singleton(); if (($output == CRM_Core_Selector_Controller::EXPORT || $output == CRM_Core_Selector_Controller::SCREEN) && $this->_formValues['radio_ts'] == 'ts_sel') { $includeContactIds = TRUE; } else { $includeContactIds = FALSE; } // note the formvalues were given by CRM_Contact_Form_Search to us // and contain the search criteria (parameters) // note that the default action is basic if ($rowCount) { $cacheKey = $this->buildPrevNextCache($sort); $result = $this->_query->getCachedContacts($cacheKey, $offset, $rowCount, $includeContactIds); } else { $result = $this->_query->searchQuery($offset, $rowCount, $sort, FALSE, $includeContactIds); } // process the result of the query $rows = array(); $permissions = array(CRM_Core_Permission::getPermission()); if (CRM_Core_Permission::check('delete contacts')) { $permissions[] = CRM_Core_Permission::DELETE; } $mask = CRM_Core_Action::mask($permissions); // mask value to hide map link if there are not lat/long $mapMask = $mask & 4095; if ($this->_searchContext == 'smog') { $gc = CRM_Core_SelectValues::groupContactStatus(); } if ($this->_ufGroupID) { $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id'); $names = array(); static $skipFields = array('group', 'tag'); foreach ($this->_fields as $key => $field) { if (!empty($field['in_selector']) && !in_array($key, $skipFields)) { if (strpos($key, '-') !== FALSE) { list($fieldName, $id, $type) = CRM_Utils_System::explode('-', $key, 3); if ($id == 'Primary') { $locationTypeName = 1; } else { $locationTypeName = CRM_Utils_Array::value($id, $locationTypes); if (!$locationTypeName) { continue; } } $locationTypeName = str_replace(' ', '_', $locationTypeName); if (in_array($fieldName, array('phone', 'im', 'email'))) { if ($type) { $names[] = "{$locationTypeName}-{$fieldName}-{$type}"; } else { $names[] = "{$locationTypeName}-{$fieldName}"; } } else { $names[] = "{$locationTypeName}-{$fieldName}"; } } else { $names[] = $field['name']; } } } $names[] = "status"; } elseif (!empty($this->_returnProperties)) { $names = self::makeProperties($this->_returnProperties); } else { $names = self::$_properties; } $multipleSelectFields = array('preferred_communication_method' => 1); $links = self::links($this->_context, $this->_contextMenu, $this->_key); //check explicitly added contact to a Smart Group. $groupID = CRM_Utils_Array::key('1', $this->_formValues['group']); $pseudoconstants = array(); // for CRM-3157 purposes if (in_array('world_region', $names)) { $pseudoconstants['world_region'] = array('dbName' => 'world_region_id', 'values' => CRM_Core_PseudoConstant::worldRegion()); } $seenIDs = array(); while ($result->fetch()) { $row = array(); $this->_query->convertToPseudoNames($result); // the columns we are interested in foreach ($names as $property) { if ($property == 'status') { continue; } if ($cfID = CRM_Core_BAO_CustomField::getKeyID($property)) { $row[$property] = CRM_Core_BAO_CustomField::getDisplayValue($result->{$property}, $cfID, $this->_options, $result->contact_id); } elseif ($multipleSelectFields && array_key_exists($property, $multipleSelectFields)) { $key = $property; $paramsNew = array($key => $result->{$property}); $name = array($key => array('newName' => $key, 'groupName' => $key)); CRM_Core_OptionGroup::lookupValues($paramsNew, $name, FALSE); $row[$key] = $paramsNew[$key]; } elseif (strpos($property, '-im')) { $row[$property] = $result->{$property}; if (!empty($result->{$property})) { $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id'); $providerId = $property . "-provider_id"; $providerName = $imProviders[$result->{$providerId}]; $row[$property] = $result->{$property} . " ({$providerName})"; } } elseif (in_array($property, array('addressee', 'email_greeting', 'postal_greeting'))) { $greeting = $property . '_display'; $row[$property] = $result->{$greeting}; } elseif (isset($pseudoconstants[$property])) { $row[$property] = CRM_Utils_Array::value($result->{$pseudoconstants[$property]['dbName']}, $pseudoconstants[$property]['values']); } elseif (strpos($property, '-url') !== FALSE) { $websiteUrl = ''; $websiteKey = 'website-1'; $propertyArray = explode('-', $property); $websiteFld = $websiteKey . '-' . array_pop($propertyArray); if (!empty($result->{$websiteFld})) { $websiteTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Website', 'website_type_id'); $websiteType = $websiteTypes[$result->{"{$websiteKey}-website_type_id"}]; $websiteValue = $result->{$websiteFld}; $websiteUrl = "<a href=\"{$websiteValue}\">{$websiteValue} ({$websiteType})</a>"; } $row[$property] = $websiteUrl; } else { $row[$property] = isset($result->{$property}) ? $result->{$property} : NULL; } } if (!empty($result->postal_code_suffix)) { $row['postal_code'] .= "-" . $result->postal_code_suffix; } if ($output != CRM_Core_Selector_Controller::EXPORT && $this->_searchContext == 'smog') { if (empty($result->status) && $groupID) { $contactID = $result->contact_id; if ($contactID) { $gcParams = array('contact_id' => $contactID, 'group_id' => $groupID); $gcDefaults = array(); CRM_Core_DAO::commonRetrieve('CRM_Contact_DAO_GroupContact', $gcParams, $gcDefaults); if (empty($gcDefaults)) { $row['status'] = ts('Smart'); } else { $row['status'] = $gc[$gcDefaults['status']]; } } else { $row['status'] = NULL; } } else { $row['status'] = $gc[$result->status]; } } if ($output != CRM_Core_Selector_Controller::EXPORT) { $row['checkbox'] = CRM_Core_Form::CB_PREFIX . $result->contact_id; if (!empty($this->_formValues['deleted_contacts']) && CRM_Core_Permission::check('access deleted contacts')) { $links = array(array('name' => ts('View'), 'url' => 'civicrm/contact/view', 'qs' => 'reset=1&cid=%%id%%', 'class' => 'no-popup', 'title' => ts('View Contact Details')), array('name' => ts('Restore'), 'url' => 'civicrm/contact/view/delete', 'qs' => 'reset=1&cid=%%id%%&restore=1', 'title' => ts('Restore Contact'))); if (CRM_Core_Permission::check('delete contacts')) { $links[] = array('name' => ts('Delete Permanently'), 'url' => 'civicrm/contact/view/delete', 'qs' => 'reset=1&cid=%%id%%&skip_undelete=1', 'title' => ts('Permanently Delete Contact')); } $row['action'] = CRM_Core_Action::formLink($links, NULL, array('id' => $result->contact_id), ts('more'), FALSE, 'contact.selector.row', 'Contact', $result->contact_id); } elseif (is_numeric(CRM_Utils_Array::value('geo_code_1', $row)) || $config->mapGeoCoding && !empty($row['city']) && CRM_Utils_Array::value('state_province', $row)) { $row['action'] = CRM_Core_Action::formLink($links, $mask, array('id' => $result->contact_id), ts('more'), FALSE, 'contact.selector.row', 'Contact', $result->contact_id); } else { $row['action'] = CRM_Core_Action::formLink($links, $mapMask, array('id' => $result->contact_id), ts('more'), FALSE, 'contact.selector.row', 'Contact', $result->contact_id); } // allow components to add more actions CRM_Core_Component::searchAction($row, $result->contact_id); $row['contact_type'] = CRM_Contact_BAO_Contact_Utils::getImage($result->contact_sub_type ? $result->contact_sub_type : $result->contact_type, FALSE, $result->contact_id); $row['contact_type_orig'] = $result->contact_sub_type ? $result->contact_sub_type : $result->contact_type; $row['contact_sub_type'] = $result->contact_sub_type ? CRM_Contact_BAO_ContactType::contactTypePairs(FALSE, $result->contact_sub_type, ', ') : $result->contact_sub_type; $row['contact_id'] = $result->contact_id; $row['sort_name'] = $result->sort_name; if (array_key_exists('id', $row)) { $row['id'] = $result->contact_id; } } // Dedupe contacts if (in_array($row['contact_id'], $seenIDs) === FALSE) { $seenIDs[] = $row['contact_id']; $rows[] = $row; } } return $rows; }
/** * Merge household record into the individual record * if exists * * @param string $exportTempTable * Temporary temp table that stores the records. * @param array $headerRows * Array of headers for the export file. * @param array $sqlColumns * Array of names of the table columns of the temp table. * @param string $prefix * Name of the relationship type that is prefixed to the table columns. */ public static function mergeSameHousehold($exportTempTable, &$headerRows, &$sqlColumns, $prefix) { $prefixColumn = $prefix . '_'; $allKeys = array_keys($sqlColumns); $replaced = array(); $headerRows = array_values($headerRows); // name map of the non standard fields in header rows & sql columns $mappingFields = array('civicrm_primary_id' => 'id', 'contact_source' => 'source', 'current_employer_id' => 'employer_id', 'contact_is_deleted' => 'is_deleted', 'name' => 'address_name', 'provider_id' => 'im_service_provider', 'phone_type_id' => 'phone_type'); //figure out which columns are to be replaced by which ones foreach ($sqlColumns as $columnNames => $dontCare) { if ($rep = CRM_Utils_Array::value($columnNames, $mappingFields)) { $replaced[$columnNames] = CRM_Utils_String::munge($prefixColumn . $rep, '_', 64); } else { $householdColName = CRM_Utils_String::munge($prefixColumn . $columnNames, '_', 64); if (!empty($sqlColumns[$householdColName])) { $replaced[$columnNames] = $householdColName; } } } $query = "UPDATE {$exportTempTable} SET "; $clause = array(); foreach ($replaced as $from => $to) { $clause[] = "{$from} = {$to} "; unset($sqlColumns[$to]); if ($key = CRM_Utils_Array::key($to, $allKeys)) { unset($headerRows[$key]); } } $query .= implode(",\n", $clause); $query .= " WHERE {$replaced['civicrm_primary_id']} != ''"; CRM_Core_DAO::executeQuery($query); //drop the table columns that store redundant household info $dropQuery = "ALTER TABLE {$exportTempTable} "; foreach ($replaced as $householdColumns) { $dropClause[] = " DROP {$householdColumns} "; } $dropQuery .= implode(",\n", $dropClause); CRM_Core_DAO::executeQuery($dropQuery); // also drop the temp table if exists $sql = "DROP TABLE IF EXISTS {$exportTempTable}_temp"; CRM_Core_DAO::executeQuery($sql); // clean up duplicate records $query = "\nCREATE TABLE {$exportTempTable}_temp SELECT *\nFROM {$exportTempTable}\nGROUP BY civicrm_primary_id "; CRM_Core_DAO::executeQuery($query); $query = "DROP TABLE {$exportTempTable}"; CRM_Core_DAO::executeQuery($query); $query = "ALTER TABLE {$exportTempTable}_temp RENAME TO {$exportTempTable}"; CRM_Core_DAO::executeQuery($query); }
/** * @todo document me - I seem a bit out of date.... */ public static function _getActTypes() { $activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, FALSE, FALSE, 'name'); self::$_renewalActType = CRM_Utils_Array::key('Membership Renewal', $activityTypes); self::$_signupActType = CRM_Utils_Array::key('Membership Signup', $activityTypes); }
function from() { //define table name $randomNum = md5(uniqid()); $this->_tableName = "civicrm_temp_custom_{$randomNum}"; //grab the contacts added in the date range first $sql = "CREATE TEMPORARY TABLE dates_{$this->_tableName} ( id int primary key, date_added date ) ENGINE=HEAP"; if ($this->_debug > 0) { print "-- Date range query: <pre>"; print "{$sql};"; print "</pre>"; } CRM_Core_DAO::executeQuery($sql); $startDate = CRM_Utils_Date::mysqlToIso(CRM_Utils_Date::processDate($this->_formValues['start_date'])); $endDateFix = NULL; if (!empty($this->_formValues['end_date'])) { $endDate = CRM_Utils_Date::mysqlToIso(CRM_Utils_Date::processDate($this->_formValues['end_date'])); # tack 11:59pm on to make search inclusive of the end date $endDateFix = "AND date_added <= '" . substr($endDate, 0, 10) . " 23:59:00'"; } $dateRange = "INSERT INTO dates_{$this->_tableName} ( id, date_added )\n SELECT\n civicrm_contact.id,\n min(civicrm_log.modified_date) AS date_added\n FROM\n civicrm_contact LEFT JOIN civicrm_log\n ON (civicrm_contact.id = civicrm_log.entity_id AND\n civicrm_log.entity_table = 'civicrm_contact')\n GROUP BY\n civicrm_contact.id\n HAVING\n date_added >= '{$startDate}' \n {$endDateFix}"; if ($this->_debug > 0) { print "-- Date range query: <pre>"; print "{$dateRange};"; print "</pre>"; } CRM_Core_DAO::executeQuery($dateRange, CRM_Core_DAO::$_nullArray); // Only include groups in the search query of one or more Include OR Exclude groups has been selected. // CRM-6356 if ($this->_groups) { //block for Group search $smartGroup = array(); require_once 'CRM/Contact/DAO/Group.php'; $group = new CRM_Contact_DAO_Group(); $group->is_active = 1; $group->find(); while ($group->fetch()) { $allGroups[] = $group->id; if ($group->saved_search_id) { $smartGroup[$group->saved_search_id] = $group->id; } } $includedGroups = implode(',', $allGroups); if (!empty($this->_includeGroups)) { $iGroups = implode(',', $this->_includeGroups); } else { //if no group selected search for all groups $iGroups = $includedGroups; } if (is_array($this->_excludeGroups)) { $xGroups = implode(',', $this->_excludeGroups); } else { $xGroups = 0; } $sql = "DROP TEMPORARY TABLE IF EXISTS Xg_{$this->_tableName}"; CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray); $sql = "CREATE TEMPORARY TABLE Xg_{$this->_tableName} ( contact_id int primary key) ENGINE=HEAP"; CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray); //used only when exclude group is selected if ($xGroups != 0) { $excludeGroup = "INSERT INTO Xg_{$this->_tableName} ( contact_id )\n SELECT DISTINCT civicrm_group_contact.contact_id\n FROM civicrm_group_contact, dates_{$this->_tableName} AS d\n WHERE \n d.id = civicrm_group_contact.contact_id AND \n civicrm_group_contact.status = 'Added' AND\n civicrm_group_contact.group_id IN( {$xGroups})"; CRM_Core_DAO::executeQuery($excludeGroup, CRM_Core_DAO::$_nullArray); //search for smart group contacts foreach ($this->_excludeGroups as $keys => $values) { if (in_array($values, $smartGroup)) { $ssId = CRM_Utils_Array::key($values, $smartGroup); $smartSql = CRM_Contact_BAO_SavedSearch::contactIDsSQL($ssId); $smartSql = $smartSql . " AND contact_a.id NOT IN ( \n SELECT contact_id FROM civicrm_group_contact \n WHERE civicrm_group_contact.group_id = {$values} AND civicrm_group_contact.status = 'Removed')"; $smartGroupQuery = " INSERT IGNORE INTO Xg_{$this->_tableName}(contact_id) {$smartSql}"; CRM_Core_DAO::executeQuery($smartGroupQuery, CRM_Core_DAO::$_nullArray); } } } $sql = "DROP TEMPORARY TABLE IF EXISTS Ig_{$this->_tableName}"; CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray); $sql = "CREATE TEMPORARY TABLE Ig_{$this->_tableName}\n ( id int PRIMARY KEY AUTO_INCREMENT,\n contact_id int,\n group_names varchar(64)) ENGINE=HEAP"; if ($this->_debug > 0) { print "-- Include groups query: <pre>"; print "{$sql};"; print "</pre>"; } CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray); $includeGroup = "INSERT INTO Ig_{$this->_tableName} (contact_id, group_names)\n SELECT d.id as contact_id, civicrm_group.name as group_name\n FROM dates_{$this->_tableName} AS d\n INNER JOIN civicrm_group_contact\n ON civicrm_group_contact.contact_id = d.id\n LEFT JOIN civicrm_group\n ON civicrm_group_contact.group_id = civicrm_group.id"; //used only when exclude group is selected if ($xGroups != 0) { $includeGroup .= " LEFT JOIN Xg_{$this->_tableName}\n ON d.id = Xg_{$this->_tableName}.contact_id"; } $includeGroup .= " WHERE \n civicrm_group_contact.status = 'Added' AND\n civicrm_group_contact.group_id IN({$iGroups})"; //used only when exclude group is selected if ($xGroups != 0) { $includeGroup .= " AND Xg_{$this->_tableName}.contact_id IS null"; } if ($this->_debug > 0) { print "-- Include groups query: <pre>"; print "{$includeGroup};"; print "</pre>"; } CRM_Core_DAO::executeQuery($includeGroup, CRM_Core_DAO::$_nullArray); //search for smart group contacts foreach ($this->_includeGroups as $keys => $values) { if (in_array($values, $smartGroup)) { $ssId = CRM_Utils_Array::key($values, $smartGroup); $smartSql = CRM_Contact_BAO_SavedSearch::contactIDsSQL($ssId); $smartSql .= " AND contact_a.id IN (\n SELECT id AS contact_id\n FROM dates_{$this->_tableName} )"; $smartSql .= " AND contact_a.id NOT IN ( \n SELECT contact_id FROM civicrm_group_contact\n WHERE civicrm_group_contact.group_id = {$values} AND civicrm_group_contact.status = 'Removed')"; //used only when exclude group is selected if ($xGroups != 0) { $smartSql .= " AND contact_a.id NOT IN (SELECT contact_id FROM Xg_{$this->_tableName})"; } $smartGroupQuery = " INSERT IGNORE INTO\n Ig_{$this->_tableName}(contact_id) \n {$smartSql}"; CRM_Core_DAO::executeQuery($smartGroupQuery, CRM_Core_DAO::$_nullArray); if ($this->_debug > 0) { print "-- Smart group query: <pre>"; print "{$smartGroupQuery};"; print "</pre>"; } $insertGroupNameQuery = "UPDATE IGNORE Ig_{$this->_tableName}\n SET group_names = (SELECT title FROM civicrm_group\n WHERE civicrm_group.id = {$values})\n WHERE Ig_{$this->_tableName}.contact_id IS NOT NULL \n AND Ig_{$this->_tableName}.group_names IS NULL"; CRM_Core_DAO::executeQuery($insertGroupNameQuery, CRM_Core_DAO::$_nullArray); if ($this->_debug > 0) { print "-- Smart group query: <pre>"; print "{$insertGroupNameQuery};"; print "</pre>"; } } } } // end if( $this->_groups ) condition $from = "FROM civicrm_contact contact_a"; /* We need to join to this again to get the date_added value */ $from .= " INNER JOIN dates_{$this->_tableName} d ON (contact_a.id = d.id)"; // Only include groups in the search query of one or more Include OR Exclude groups has been selected. // CRM-6356 if ($this->_groups) { $from .= " INNER JOIN Ig_{$this->_tableName} temptable1 ON (contact_a.id = temptable1.contact_id)"; } //this makes smart groups using this search compatible w/ CiviMail $from .= " LEFT JOIN civicrm_email ON (contact_a.id = civicrm_email.contact_id)"; return $from; }
/** * @param array $batchIds * @param $status */ public static function closeReOpen($batchIds = array(), $status) { $batchStatus = CRM_Core_PseudoConstant::get('CRM_Batch_DAO_Batch', 'status_id'); $params['status_id'] = CRM_Utils_Array::key($status, $batchStatus); $session = CRM_Core_Session::singleton(); $params['modified_date'] = date('YmdHis'); $params['modified_id'] = $session->get('userID'); foreach ($batchIds as $key => $value) { $params['id'] = $ids['batchID'] = $value; self::create($params, $ids); } $url = CRM_Utils_System::url('civicrm/financial/financialbatches', "reset=1&batchStatus={$params['status_id']}"); CRM_Utils_System::redirect($url); }
/** * Set default values for the form. * * @param CRM_Core_Form $form * @param array $defaults */ public static function setDefaultValues(&$form, &$defaults) { if (!empty($defaults['preferred_language'])) { $languages = CRM_Contact_BAO_Contact::buildOptions('preferred_language'); $defaults['preferred_language'] = CRM_Utils_Array::key($defaults['preferred_language'], $languages); } // CRM-7119: set preferred_language to default if unset if (empty($defaults['preferred_language'])) { $config = CRM_Core_Config::singleton(); $defaults['preferred_language'] = $config->lcMessages; } if (empty($defaults['communication_style_id'])) { $defaults['communication_style_id'] = array_pop(CRM_Core_OptionGroup::values('communication_style', TRUE, NULL, NULL, 'AND is_default = 1')); } // CRM-17778 -- set preferred_mail_format to default if unset if (empty($defaults['preferred_mail_format'])) { $defaults['preferred_mail_format'] = 'Both'; } else { $defaults['preferred_mail_format'] = array_search($defaults['preferred_mail_format'], CRM_Core_SelectValues::pmf()); } //set default from greeting types CRM-4575, CRM-9739 if ($form->_action & CRM_Core_Action::ADD) { foreach (CRM_Contact_BAO_Contact::$_greetingTypes as $greeting) { if (empty($defaults[$greeting . '_id'])) { if ($defaultGreetingTypeId = CRM_Contact_BAO_Contact_Utils::defaultGreeting($form->_contactType, $greeting)) { $defaults[$greeting . '_id'] = $defaultGreetingTypeId; } } } } else { foreach (CRM_Contact_BAO_Contact::$_greetingTypes as $greeting) { $name = "{$greeting}_display"; $form->assign($name, CRM_Utils_Array::value($name, $defaults)); } } }