/** * @return array */ public function checkOptionGroupValues() { $messages = array(); $problemValues = array(); $optionGroups = civicrm_api3('OptionGroup', 'get', array('sequential' => 1, 'data_type' => array('IS NOT NULL' => 1), 'options' => array('limit' => 0))); if ($optionGroups['count'] > 0) { foreach ($optionGroups['values'] as $optionGroup) { $values = CRM_Core_BAO_OptionValue::getOptionValuesArray($optionGroup['id']); if (count($values) > 0) { foreach ($values as $value) { $validate = CRM_Utils_Type::validate($value['value'], $optionGroup['data_type'], FALSE); if (!$validate) { $problemValues[] = array('group_name' => $optionGroup['title'], 'value_name' => $value['label']); } } } } } if (!empty($problemValues)) { $strings = ''; foreach ($problemValues as $problemValue) { $strings .= ts('<tr><td> "%1" </td><td> "%2" </td></tr>', array(1 => $problemValue['group_name'], 2 => $problemValue['value_name'])); } $messages[] = new CRM_Utils_Check_Message(__FUNCTION__, ts('The Following Option Values contain value fields that do not match the Data Type of the Option Group</p> <p><table><tbody><th>Option Group</th><th>Option Value</th></tbody><tbody>') . $strings . ts('</tbody></table></p>'), ts('Option Values with problematic Values'), \Psr\Log\LogLevel::NOTICE, 'fa-server'); } return $messages; }
/** * 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}")); }
/** * @param string $name of variable to return * @param string $type data type * - String * - Integer * @param string $location - deprecated * @param boolean $abort abort if empty * @return Ambigous <mixed, NULL, value, unknown, array, number> */ function retrieve($name, $type, $abort = TRUE) { $value = CRM_Utils_Type::validate(CRM_Utils_Array::value($name, $this->_inputParameters), $type, FALSE); if ($abort && $value === NULL) { throw new CRM_Core_Exception("Could not find an entry for {$name}"); } return $value; }
/** * @param string $name * @param $type * @param bool $abort * * @return mixed */ public function retrieve($name, $type, $abort = TRUE) { static $store = NULL; $value = CRM_Utils_Type::validate(CRM_Utils_Array::value($name, $this->_inputParameters), $type, FALSE); if ($abort && $value === NULL) { CRM_Core_Error::debug_log_message("Could not find an entry for {$name}"); echo "Failure: Missing Parameter<p>" . CRM_Utils_Type::escape($name, 'String'); exit; } return $value; }
public static function getCaseActivity() { // Should those params be passed through the validateParams method? $caseID = CRM_Utils_Type::validate($_GET['caseID'], 'Integer'); $contactID = CRM_Utils_Type::validate($_GET['cid'], 'Integer'); $userID = CRM_Utils_Type::validate($_GET['userID'], 'Integer'); $context = CRM_Utils_Type::validate(CRM_Utils_Array::value('context', $_GET), 'String'); $optionalParameters = array('source_contact_id' => 'Integer', 'status_id' => 'Integer', 'activity_deleted' => 'Boolean', 'activity_type_id' => 'Integer', 'activity_date_low' => 'Date', 'activity_date_high' => 'Date'); $params = CRM_Core_Page_AJAX::defaultSortAndPagerParams(); $params += CRM_Core_Page_AJAX::validateParams(array(), $optionalParameters); // get the activities related to given case $activities = CRM_Case_BAO_Case::getCaseActivity($caseID, $params, $contactID, $context, $userID); CRM_Utils_JSON::output($activities); }
/** * Retrieve a value from the bag. * * @param string $key * @param string|null $type * @param mixed $default * @return mixed * @throws API_Exception */ public function get($key, $type = NULL, $default = NULL) { if (!array_key_exists($key, $this->data)) { return $default; } if (!$type) { return $this->data[$key]; } $r = CRM_Utils_Type::validate($this->data[$key], $type); if ($r !== NULL) { return $r; } else { throw new \API_Exception(ts("Could not find valid value for %1 (%2)", array(1 => $key, 2 => $type))); } }
static function retrieve($name, $type, $object, $abort = TRUE) { $value = CRM_Utils_Array::value($name, $object); if ($abort && $value === NULL) { CRM_Core_Error::debug_log_message("Could not find an entry for {$name}"); echo "Failure: Missing Parameter<p>"; exit; } if ($value) { if (!CRM_Utils_Type::validate($value, $type)) { CRM_Core_Error::debug_log_message("Could not find a valid entry for {$name}"); echo "Failure: Invalid Parameter<p>"; exit; } } return $value; }
/** * Retrieve a value from the request (GET/POST/REQUEST) * * @param string $name * Name of the variable to be retrieved. * @param string $type * Type of the variable (see CRM_Utils_Type for details). * @param object $store * Session scope where variable is stored. * @param bool $abort * TRUE, if the variable is required. * @param mixed $default * Default value of the variable if not present. * @param string $method * Where to look for the variable - 'GET', 'POST' or 'REQUEST'. * * @return mixed * The value of the variable */ public static function retrieve($name, $type, &$store = NULL, $abort = FALSE, $default = NULL, $method = 'REQUEST') { // hack to detect stuff not yet converted to new style if (!is_string($type)) { CRM_Core_Error::backtrace(); CRM_Core_Error::fatal(ts("Please convert retrieve call to use new function signature")); } $value = NULL; switch ($method) { case 'GET': $value = CRM_Utils_Array::value($name, $_GET); break; case 'POST': $value = CRM_Utils_Array::value($name, $_POST); break; default: $value = CRM_Utils_Array::value($name, $_REQUEST); break; } if (isset($value) && CRM_Utils_Type::validate($value, $type, $abort, $name) === NULL) { $value = NULL; } if (!isset($value) && $store) { $value = $store->get($name); } if (!isset($value) && $abort) { CRM_Core_Error::fatal(ts("Could not find valid value for %1", array(1 => $name))); } if (!isset($value) && $default) { $value = $default; } // minor hack for action if ($name == 'action' && is_string($value)) { $value = CRM_Core_Action::resolve($value); } if (isset($value) && $store) { $store->set($name, $value); } return $value; }
/** * Verify user has permission to access a case. * * @param int $caseId * @param bool $denyClosed * Set TRUE if one wants closed cases to be treated as inaccessible. * * @return bool */ public static function accessCase($caseId, $denyClosed = TRUE) { if (!$caseId || !self::enabled()) { return FALSE; } // This permission always has access if (CRM_Core_Permission::check('access all cases and activities')) { return TRUE; } // This permission is required at minimum if (!CRM_Core_Permission::check('access my cases and activities')) { return FALSE; } $session = CRM_Core_Session::singleton(); $userID = CRM_Utils_Type::validate($session->get('userID'), 'Positive'); $caseId = CRM_Utils_Type::validate($caseId, 'Positive'); $condition = " AND civicrm_case.is_deleted = 0 "; $condition .= " AND case_relationship.contact_id_b = {$userID} "; $condition .= " AND civicrm_case.id = {$caseId}"; if ($denyClosed) { $closedId = CRM_Core_OptionGroup::getValue('case_status', 'Closed', 'name'); $condition .= " AND civicrm_case.status_id != {$closedId}"; } // We don't actually care about activities in the case, but the underlying // query is verbose, and this allows us to share the basic query with // getCases(). $type=='any' means that activities will be left-joined. $query = self::getCaseActivityQuery('any', $userID, $condition); $queryParams = array(); $dao = CRM_Core_DAO::executeQuery($query, $queryParams); return (bool) $dao->fetch(); }
/** * The constructor takes an assoc array * key names of variable (which should be the same as the column name) * value: ascending or descending * * @param mixed $vars * Assoc array as described above. * @param string $defaultSortOrder * Order to sort. * * @return \CRM_Utils_Sort */ public function __construct(&$vars, $defaultSortOrder = NULL) { $this->_vars = array(); $this->_response = array(); foreach ($vars as $weight => $value) { $this->_vars[$weight] = array('name' => CRM_Utils_Type::validate($value['sort'], 'MysqlColumnName'), 'direction' => CRM_Utils_Array::value('direction', $value), 'title' => $value['name']); } $this->_currentSortID = 1; if (isset($this->_vars[$this->_currentSortID])) { $this->_currentSortDirection = $this->_vars[$this->_currentSortID]['direction']; } $this->_urlVar = self::SORT_ID; $this->_link = CRM_Utils_System::makeURL($this->_urlVar, TRUE); $this->initialize($defaultSortOrder); }
/** * Global form rule. * * @param array $fields * The input form values. * @param array $files * The uploaded files if any. * @param array $self * Current form object. * * @return array * array of errors / empty array. */ public static function formRule($fields, $files, $self) { $errors = array(); if ($self->_gName == 'case_status' && empty($fields['grouping'])) { $errors['grouping'] = ts('Status class is a required field'); } if (in_array($self->_gName, array('email_greeting', 'postal_greeting', 'addressee')) && empty($self->_defaultValues['is_reserved'])) { $label = $fields['label']; $condition = " AND v.label = '{$label}' "; $values = CRM_Core_OptionGroup::values($self->_gName, FALSE, FALSE, FALSE, $condition, 'filter'); $checkContactOptions = TRUE; if ($self->_id && $self->_defaultValues['contactOptions'] == $fields['contactOptions']) { $checkContactOptions = FALSE; } if ($checkContactOptions && in_array($fields['contactOptions'], $values)) { $errors['label'] = ts('This Label already exists in the database for the selected contact type.'); } } if ($self->_gName == 'from_email_address') { $formEmail = CRM_Utils_Mail::pluckEmailFromHeader($fields['label']); if (!CRM_Utils_Rule::email($formEmail)) { $errors['label'] = ts('Please enter a valid email address.'); } $formName = explode('"', $fields['label']); if (empty($formName[1]) || count($formName) != 3) { $errors['label'] = ts('Please follow the proper format for From Email Address'); } } $dataType = self::getOptionGroupDataType($self->_gName); if ($dataType && $self->_gName !== 'activity_type') { $validate = CRM_Utils_Type::validate($fields['value'], $dataType, FALSE); if (!$validate) { CRM_Core_Session::setStatus(ts('Data Type of the value field for this option value does not match ' . $dataType), ts('Value field Data Type mismatch')); } } return $errors; }
/** * Delete the tag. * * @param int $id * Tag id. * * @return bool */ public static function del($id) { // since this is a destructive operation, lets make sure // id is a positive number CRM_Utils_Type::validate($id, 'Positive'); // delete all crm_entity_tag records with the selected tag id $entityTag = new CRM_Core_DAO_EntityTag(); $entityTag->tag_id = $id; $entityTag->delete(); // delete from tag table $tag = new CRM_Core_DAO_Tag(); $tag->id = $id; CRM_Utils_Hook::pre('delete', 'Tag', $id, $tag); if ($tag->delete()) { CRM_Utils_Hook::post('delete', 'Tag', $id, $tag); return TRUE; } return FALSE; }
/** * set variables up before form is built * * @access public */ function preProcess() { // VOL-71: permissions check is moved from XML to preProcess function to support // permissions-challenged Joomla instances if (CRM_Core_Config::singleton()->userPermissionClass->isModulePermissionSupported() && !CRM_Volunteer_Permission::check('register to volunteer')) { CRM_Utils_System::permissionDenied(); } $validNeedIds = array(); $needs = CRM_Utils_Request::retrieve('needs', 'String', $this, TRUE); if (!is_array($needs)) { $needs = explode(',', $needs); } foreach ($needs as $need) { if (CRM_Utils_Type::validate($need, 'Positive', FALSE)) { $validNeedIds[] = $need; } } $api = civicrm_api3('VolunteerNeed', 'get', array('id' => array('IN' => $validNeedIds))); $this->_needs = $api['values']; foreach ($this->_needs as $need) { $this->_projects[$need['project_id']] = array(); } $this->fetchProjectDetails(); $this->setDestination(); $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE); // current mode $this->_mode = $this->_action == CRM_Core_Action::PREVIEW ? 'test' : 'live'; }
/** * @param string $name * Parameter name. * @param string $type * Parameter type. * @param bool $abort * Abort if not present. * @param null $default * Default value. * * @throws CRM_Core_Exception * @return mixed */ public function retrieve($name, $type, $abort = TRUE, $default = NULL) { $value = CRM_Utils_Type::validate(empty($this->_inputParameters[$name]) ? $default : $this->_inputParameters[$name], $type, FALSE); if ($abort && $value === NULL) { throw new CRM_Core_Exception("Could not find an entry for {$name}"); } return $value; }
/** * Helper function to call validate on arrays * * @see validate */ public static function validateAll($data, $type, $abort = TRUE) { foreach ($data as $key => $value) { $data[$key] = CRM_Utils_Type::validate($value, $type, $abort); } return $data; }
/** * @param int $need_id * @return int The number of assignments on the given need */ public static function getAssignmentCount($need_id) { CRM_Utils_Type::validate($need_id, 'Integer'); return civicrm_api3('VolunteerAssignment', 'getcount', array('volunteer_need_id' => $need_id)); }
/** * Wrapper method for retrieve * * @param mixed $id Int or int-like string representing project ID * @return CRM_Volunteer_BAO_Project */ static function retrieveByID($id) { $id = (int) CRM_Utils_Type::validate($id, 'Integer'); $projects = self::retrieve(array('id' => $id)); if (!array_key_exists($id, $projects)) { CRM_Core_Error::fatal("No project with ID {$id} exists."); } return $projects[$id]; }
/** * get the variable information from the request (GET/POST/SESSION * * @param $name name of the variable to be retrieved * @param $type type of the variable (see CRM_Utils_Type for details) * @param $store session scope where variable is stored * @param $abort is this variable required * @param $default default value of the variable if not present * @param $method where should we look for the variable * * @return string the value of the variable * @access public * @static * */ static function retrieve($name, $type, &$store, $abort = false, $default = null, $method = 'GET') { // hack to detect stuff not yet converted to new style if (!is_string($type)) { CRM_Core_Error::backtrace(); CRM_Core_Error::fatal("Please convert retrieve call to use new function signature"); } $value = null; switch ($method) { case 'GET': $value = CRM_Utils_Array::value($name, $_GET); break; case 'POST': $value = CRM_Utils_Array::value($name, $_POST); break; default: $value = CRM_Utils_Array::value($name, $_REQUEST); break; } require_once 'CRM/Utils/Type.php'; if (isset($value) && CRM_Utils_Type::validate($value, $type, $abort, $name) === null) { $value = null; } if (!isset($value) && $store) { $value = $store->get($name); } if (!isset($value) && $abort) { CRM_Core_Error::fatal("Could not find valid value for {$name}"); } if (!isset($value) && $default) { $value = $default; } // minor hack for action if ($name == 'action' && is_string($value)) { $value = CRM_Core_Action::resolve($value); } if (isset($value) && $store) { $store->set($name, $value); } return $value; }
static function composeQuery($query, &$params, $abort) { require_once 'CRM/Utils/Type.php'; $tr = array(); foreach ($params as $key => $item) { if (is_numeric($key)) { if (CRM_Utils_Type::validate($item[0], $item[1]) !== null) { $item[0] = self::escapeString($item[0]); if ($item[1] == 'String' || $item[1] == 'Memo' || $item[1] == 'Link') { if (isset($item[2]) && $item[2]) { $item[0] = "'%{$item[0]}%'"; } else { $item[0] = "'{$item[0]}'"; } } if (($item[1] == 'Date' || $item[1] == 'Timestamp') && strlen($item[0]) == 0) { $item[0] = 'null'; } $tr['%' . $key] = $item[0]; } else { if ($abort) { CRM_Core_Error::fatal("{$item[0]} is not of type {$item[1]}"); } } } } return strtr($query, $tr); }
/** * global validation rules for the form * * @param array $fields posted values of the form * * @return array list of errors to be posted back to the form * @static * @access public */ static function formRule(&$values) { //CRM_Core_Error::debug('s', $values); if (CRM_Utils_Array::value('addMore', $values) || CRM_Utils_Array::value('addBlock', $values)) { return true; } require_once 'CRM/Contact/BAO/Contact.php'; $fields = array(); $fields = CRM_Contact_BAO_Contact::exportableFields('All', false, true); require_once 'CRM/Core/Component.php'; $compomentFields =& CRM_Core_Component::getQueryFields(); $fields = array_merge($fields, $compomentFields); $fld = array(); $fld = CRM_Core_BAO_Mapping::formattedFields($values, true); require_once 'CRM/Utils/Type.php'; $errorMsg = array(); foreach ($fld as $k => $v) { if (!$v[1]) { $errorMsg["operator[{$v['3']}][{$v['4']}]"] = ts("Please enter the operator."); } else { if (in_array($v[1], array('IS NULL', 'IS NOT NULL')) && $v[2]) { $errorMsg["value[{$v['3']}][{$v['4']}]"] = ts('Please clear your value if you want to use %1 operator.', array(1 => $v[1])); } else { if ($v[0] == 'group' || $v[0] == 'tag') { $grpId = array_keys($v[2]); if (!key($v[2])) { $errorMsg["value[{$v['3']}][{$v['4']}]"] = ts("Please enter the value."); } if (count($grpId) > 1) { if ($v[1] != 'IN' && $v[1] != 'NOT IN') { $errorMsg["value[{$v['3']}][{$v['4']}]"] = ts("Please enter the valid value."); } foreach ($grpId as $val) { $error = CRM_Utils_Type::validate($val, 'Integer', false); if ($error != $val) { $errorMsg["value[{$v['3']}][{$v['4']}]"] = ts("Please enter valid value."); break; } } } else { $error = CRM_Utils_Type::validate($grpId[0], 'Integer', false); if ($error != $grpId[0]) { $errorMsg["value[{$v['3']}][{$v['4']}]"] = ts('Please enter valid %1 id.', array(1 => $v[0])); } } } else { if (substr($v[0], 0, 7) === 'do_not_' or substr($v[0], 0, 3) === 'is_') { if ($v[2]) { $v2 = array($v[2]); if (!isset($v[2])) { $errorMsg["value[{$v['3']}][{$v['4']}]"] = ts("Please enter the value."); } $error = CRM_Utils_Type::validate($v2[0], 'Integer', false); if ($error != $v2[0]) { $errorMsg["value[{$v['3']}][{$v['4']}]"] = ts("Please enter valid value."); } } else { $errorMsg["value[{$v['3']}][{$v['4']}]"] = ts("Please enter the value."); } } else { if ($v[0] === 'sort_name' || $v[0] === 'display_name') { $v2 = trim($v[2]); if (empty($v2)) { $errorMsg["value[{$v['3']}][{$v['4']}]"] = ts("Please enter the value."); } } else { if (substr($v[0], 0, 7) == 'custom_') { $type = $fields[$v[0]]['data_type']; // hack to handle custom data of type state and country if (in_array($type, array('Country', 'StateProvince'))) { $type = "Integer"; } } else { $fldName = $v[0]; // FIXME: no idea at this point what to do with this, // FIXME: but definitely needs fixing. if (substr($v[0], 0, 13) == 'contribution_') { $fldName = substr($v[0], 13); } $fldType = CRM_Utils_Array::value('type', $fields[$fldName]); $type = CRM_Utils_Type::typeToString($fldType); // Check Empty values for Integer Or Boolean Or Date type For operators other than IS NULL and IS NOT NULL. if (!in_array($v[1], array('IS NULL', 'IS NOT NULL'))) { if (($type == 'Int' || $type == 'Boolean') && !trim($v[2]) && $v[2] != '0') { $errorMsg["value[{$v['3']}][{$v['4']}]"] = ts("Please enter the value."); } else { if ($type == 'Date' && !trim($v[2])) { $errorMsg["value[{$v['3']}][{$v['4']}]"] = ts("Please enter the value."); } } } } if ($type && empty($errorMsg)) { // check for valid format while using IN Operator if ($v[1] == 'IN') { $inVal = trim($v[2]); //checking for format to avoid db errors if (!preg_match('/^[(]([A-Za-z0-9\'\\,]+)[)]$/', $inVal)) { $errorMsg["value[{$v['3']}][{$v['4']}]"] = ts("Please enter correct Data ( in valid format )."); } // Validate each value in parenthesis to avoid db errors if (empty($errorMsg)) { $parenValues = array(); $parenValues = explode(',', trim($inVal, "(..)")); foreach ($parenValues as $val) { if (!$val && $val != '0') { $errorMsg["value[{$v['3']}][{$v['4']}]"] = ts("Please enter the values correctly."); } if (empty($errorMsg)) { $error = CRM_Utils_Type::validate($val, $type, false); if ($error != $val) { $errorMsg["value[{$v['3']}][{$v['4']}]"] = ts("Please enter valid value."); } } } } } else { if (trim($v[2])) { //else check value for rest of the Operators $error = CRM_Utils_Type::validate($v[2], $type, false); if ($error != $v[2]) { $errorMsg["value[{$v['3']}][{$v['4']}]"] = ts("Please enter valid value."); } } } } } } } } } } if (!empty($errorMsg)) { return $errorMsg; } return true; }
/** * Gets all campaign related data and returns it as a std class. * * @param int $contributionPageID * @param string $widgetID * * @return stdClass */ public static function getContributionPageData($contributionPageID, $widgetID) { $config = CRM_Core_Config::singleton(); $data = array(); $data['currencySymbol'] = $config->defaultCurrencySymbol; if (empty($contributionPageID) || CRM_Utils_Type::validate($contributionPageID, 'Integer') == NULL) { $data['is_error'] = TRUE; CRM_Core_Error::debug_log_message("{$contributionPageID} is not set"); return $data; } $widget = new CRM_Contribute_DAO_Widget(); $widget->contribution_page_id = $contributionPageID; if (!$widget->find(TRUE)) { $data['is_error'] = TRUE; CRM_Core_Error::debug_log_message("{$contributionPageID} is not found"); return $data; } $data['is_error'] = FALSE; if (!$widget->is_active) { $data['is_active'] = FALSE; } $data['is_active'] = TRUE; $data['title'] = $widget->title; $data['logo'] = $widget->url_logo; $data['button_title'] = $widget->button_title; $data['about'] = $widget->about; $query = "\n SELECT count( id ) as count,\n sum( total_amount) as amount\n FROM civicrm_contribution\n WHERE is_test = 0\n AND contribution_status_id = 1\n AND contribution_page_id = %1"; $params = array(1 => array($contributionPageID, 'Integer')); $dao = CRM_Core_DAO::executeQuery($query, $params); if ($dao->fetch()) { $data['num_donors'] = (int) $dao->count; $data['money_raised'] = (int) $dao->amount; } else { $data['num_donors'] = $data['money_raised'] = $data->money_raised = 0; } $query = "\n SELECT goal_amount, start_date, end_date, is_active\n FROM civicrm_contribution_page\n WHERE id = %1"; $params = array(1 => array($contributionPageID, 'Integer')); $dao = CRM_Core_DAO::executeQuery($query, $params); $data['campaign_start'] = ''; $startDate = NULL; if ($dao->fetch()) { $data['money_target'] = (int) $dao->goal_amount; // conditions that needs to be handled // 1. Campaign is not active - no text // 2. Campaign start date greater than today - show start date // 3. Campaign end date is set and greater than today - show end date // 4. If no start and end date or no end date and start date greater than today, then it's ongoing if ($dao->is_active) { $data['campaign_start'] = ts('Campaign is ongoing'); // check for time being between start and end date $now = time(); if ($dao->start_date) { $startDate = CRM_Utils_Date::unixTime($dao->start_date); if ($startDate && $startDate >= $now) { $data['is_active'] = FALSE; $data['campaign_start'] = ts('Campaign starts on %1', array(1 => CRM_Utils_Date::customFormat($dao->start_date, $config->dateformatFull))); } } if ($dao->end_date) { $endDate = CRM_Utils_Date::unixTime($dao->end_date); if ($endDate && $endDate < $now) { $data['is_active'] = FALSE; $data['campaign_start'] = ts('Campaign ended on %1', array(1 => CRM_Utils_Date::customFormat($dao->end_date, $config->dateformatFull))); } elseif ($startDate >= $now) { $data['campaign_start'] = ts('Campaign starts on %1', array(1 => CRM_Utils_Date::customFormat($dao->start_date, $config->dateformatFull))); } else { $data['campaign_start'] = ts('Campaign ends on %1', array(1 => CRM_Utils_Date::customFormat($dao->end_date, $config->dateformatFull))); } } } else { $data['is_active'] = FALSE; } } else { $data['is_active'] = FALSE; } $data['money_raised_percentage'] = 0; if ($data['money_target'] > 0) { $percent = $data['money_raised'] / $data['money_target']; $data['money_raised_percentage'] = round($percent, 2) * 100 . "%"; $data['money_target_display'] = CRM_Utils_Money::format($data['money_target']); $data['money_raised'] = ts('Raised %1 of %2', array(1 => CRM_Utils_Money::format($data['money_raised']), 2 => $data['money_target_display'])); } else { $data['money_raised'] = ts('Raised %1', array(1 => CRM_Utils_Money::format($data['money_raised']))); } $data['money_low'] = 0; $data['num_donors'] = $data['num_donors'] . " " . ts('Donors'); $data['home_url'] = "<a href='{$config->userFrameworkBaseURL}' class='crm-home-url' style='color:" . $widget->color_homepage_link . "'>" . ts('Learn more.') . "</a>"; // if is_active is false, show this link and hide the contribute button $data['homepage_link'] = $widget->url_homepage; $data['colors'] = array(); $data['colors']["title"] = $widget->color_title; $data['colors']["button"] = $widget->color_button; $data['colors']["bar"] = $widget->color_bar; $data['colors']["main_text"] = $widget->color_main_text; $data['colors']["main"] = $widget->color_main; $data['colors']["main_bg"] = $widget->color_main_bg; $data['colors']["bg"] = $widget->color_bg; $data['colors']["about_link"] = $widget->color_about_link; return $data; }
/** * global validation rules for the form * * @param array $fields posted values of the form * * @return array list of errors to be posted back to the form * @static * @access public */ static function formRule($values, $files, $self) { if (CRM_Utils_Array::value('addMore', $values) || CRM_Utils_Array::value('addBlock', $values)) { return TRUE; } $fields = self::fields(); $fld = CRM_Core_BAO_Mapping::formattedFields($values, TRUE); $errorMsg = array(); foreach ($fld as $k => $v) { if (!$v[1]) { $errorMsg["operator[{$v['3']}][{$v['4']}]"] = ts("Please enter the operator."); } else { // CRM-10338 $v[2] = self::checkArrayKeyEmpty($v[2]); if (in_array($v[1], array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY')) && !empty($v[2])) { $errorMsg["value[{$v['3']}][{$v['4']}]"] = ts('Please clear your value if you want to use %1 operator.', array(1 => $v[1])); } elseif (($v[0] == 'group' || $v[0] == 'tag') && !empty($v[2])) { $grpId = array_keys($v[2]); if (!key($v[2])) { $errorMsg["value[{$v['3']}][{$v['4']}]"] = ts("Please enter a value."); } if (count($grpId) > 1) { if ($v[1] != 'IN' && $v[1] != 'NOT IN') { $errorMsg["value[{$v['3']}][{$v['4']}]"] = ts("Please enter a valid value."); } foreach ($grpId as $val) { $error = CRM_Utils_Type::validate($val, 'Integer', FALSE); if ($error != $val) { $errorMsg["value[{$v['3']}][{$v['4']}]"] = ts("Please enter valid value."); break; } } } else { $error = CRM_Utils_Type::validate($grpId[0], 'Integer', FALSE); if ($error != $grpId[0]) { $errorMsg["value[{$v['3']}][{$v['4']}]"] = ts('Please enter valid %1 id.', array(1 => $v[0])); } } } elseif (substr($v[0], 0, 7) === 'do_not_' or substr($v[0], 0, 3) === 'is_') { if (isset($v[2])) { $v2 = array($v[2]); if (!isset($v[2])) { $errorMsg["value[{$v['3']}][{$v['4']}]"] = ts("Please enter a value."); } $error = CRM_Utils_Type::validate($v2[0], 'Integer', FALSE); if ($error != $v2[0]) { $errorMsg["value[{$v['3']}][{$v['4']}]"] = ts("Please enter a valid value."); } } else { $errorMsg["value[{$v['3']}][{$v['4']}]"] = ts("Please enter a value."); } } else { if (substr($v[0], 0, 7) == 'custom_') { // Get rid of appended location type id list($fieldKey) = explode('-', $v[0]); $type = $fields[$fieldKey]['data_type']; // hack to handle custom data of type state and country if (in_array($type, array('Country', 'StateProvince'))) { $type = "Integer"; } } else { $fldName = $v[0]; // FIXME: no idea at this point what to do with this, // FIXME: but definitely needs fixing. if (substr($v[0], 0, 13) == 'contribution_') { $fldName = substr($v[0], 13); } $fldValue = CRM_Utils_Array::value($fldName, $fields); $fldType = CRM_Utils_Array::value('type', $fldValue); $type = CRM_Utils_Type::typeToString($fldType); // Check Empty values for Integer Or Boolean Or Date type For operators other than IS NULL and IS NOT NULL. if (!in_array($v[1], array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) { if (($type == 'Int' || $type == 'Boolean') && !trim($v[2]) && $v[2] != '0') { $errorMsg["value[{$v['3']}][{$v['4']}]"] = ts("Please enter a value."); } elseif ($type == 'Date' && !trim($v[2])) { $errorMsg["value[{$v['3']}][{$v['4']}]"] = ts("Please enter a value."); } } } if ($type && empty($errorMsg)) { // check for valid format while using IN Operator if ($v[1] == 'IN') { $inVal = trim($v[2]); //checking for format to avoid db errors if ($type == 'Int') { if (!preg_match('/^[(]([A-Za-z0-9\\,]+)[)]$/', $inVal)) { $errorMsg["value[{$v['3']}][{$v['4']}]"] = ts("Please enter correct Data (in valid format)."); } } else { if (!(substr($inVal, 0, 1) == '(' && substr($inVal, -1, 1) == ')') && !preg_match('/^[(]([A-Za-z0-9åäöÅÄÖüÜœŒæÆøØ\\,\\s]+)[)]$/', $inVal)) { $errorMsg["value[{$v['3']}][{$v['4']}]"] = ts("Please enter correct Data (in valid format)."); } } // Validate each value in parenthesis to avoid db errors if (empty($errorMsg)) { $parenValues = array(); $parenValues = explode(',', trim($inVal, "(..)")); foreach ($parenValues as $val) { $val = trim($val); if (!$val && $val != '0') { $errorMsg["value[{$v['3']}][{$v['4']}]"] = ts("Please enter the values correctly."); } if (empty($errorMsg)) { $error = CRM_Utils_Type::validate($val, $type, FALSE); if ($error != $val) { $errorMsg["value[{$v['3']}][{$v['4']}]"] = ts("Please enter a valid value."); } } } } } elseif (trim($v[2])) { //else check value for rest of the Operators $error = CRM_Utils_Type::validate($v[2], $type, FALSE); if ($error != $v[2]) { $errorMsg["value[{$v['3']}][{$v['4']}]"] = ts("Please enter a valid value."); } } } } } } if (!empty($errorMsg)) { $self->set('showSearchForm', TRUE); $self->assign('rows', NULL); return $errorMsg; } return TRUE; }
public static function validateParams($requiredParams = array(), $optionalParams = array()) { $params = array(); foreach ($requiredParams as $param => $type) { $params[$param] = CRM_Utils_Type::validate(CRM_Utils_Array::value($param, $_GET), $type); } foreach ($optionalParams as $param => $type) { if (CRM_Utils_Array::value($param, $_GET)) { $params[$param] = CRM_Utils_Type::validate(CRM_Utils_Array::value($param, $_GET), $type); } } return $params; }
/** * Create a new group. * * @param array $params * * @return CRM_Contact_BAO_Group|NULL * The new group BAO (if created) */ public static function create(&$params) { if (!empty($params['id'])) { CRM_Utils_Hook::pre('edit', 'Group', $params['id'], $params); } else { CRM_Utils_Hook::pre('create', 'Group', NULL, $params); } // form the name only if missing: CRM-627 $nameParam = CRM_Utils_Array::value('name', $params, NULL); if (!$nameParam && empty($params['id'])) { $params['name'] = CRM_Utils_String::titleToVar($params['title']); } // convert params if array type if (isset($params['group_type'])) { if (is_array($params['group_type'])) { $params['group_type'] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $params['group_type']) . CRM_Core_DAO::VALUE_SEPARATOR; } else { $params['group_type'] = CRM_Core_DAO::VALUE_SEPARATOR . $params['group_type'] . CRM_Core_DAO::VALUE_SEPARATOR; } } else { $params['group_type'] = NULL; } $session = CRM_Core_Session::singleton(); $cid = $session->get('userID'); // this action is add if ($cid && empty($params['id'])) { $params['created_id'] = $cid; } // this action is update if ($cid && !empty($params['id'])) { $params['modified_id'] = $cid; } // CRM-19068. // Validate parents parameter when creating group. if (!empty($params['parents'])) { $parents = is_array($params['parents']) ? array_keys($params['parents']) : (array) $params['parents']; foreach ($parents as $parent) { CRM_Utils_Type::validate($parent, 'Integer'); } } $group = new CRM_Contact_BAO_Group(); $group->copyValues($params); //@todo very hacky fix for the fact this function wants to receive 'parents' as an array further down but // needs it as a separated string for the DB. Preferred approaches are having the copyParams or save fn // use metadata to translate the array to the appropriate DB type or altering the param in the api layer, // or at least altering the param in same section as 'group_type' rather than repeating here. However, further down // we need the $params one to be in it's original form & we are not sure what test coverage we have on that if (isset($group->parents) && is_array($group->parents)) { $group->parents = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, array_keys($group->parents)) . CRM_Core_DAO::VALUE_SEPARATOR; } if (empty($params['id']) && !$nameParam) { $group->name .= "_tmp"; } $group->save(); if (!$group->id) { return NULL; } if (empty($params['id']) && !$nameParam) { $group->name = substr($group->name, 0, -4) . "_{$group->id}"; } $group->buildClause(); $group->save(); // add custom field values if (!empty($params['custom'])) { CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_group', $group->id); } // make the group, child of domain/site group by default. $domainGroupID = CRM_Core_BAO_Domain::getGroupId(); if (CRM_Utils_Array::value('no_parent', $params) !== 1) { if (empty($params['parents']) && $domainGroupID != $group->id && Civi::settings()->get('is_enabled') && !CRM_Contact_BAO_GroupNesting::hasParentGroups($group->id)) { // if no parent present and the group doesn't already have any parents, // make sure site group goes as parent $params['parents'] = array($domainGroupID => 1); } elseif (array_key_exists('parents', $params) && !is_array($params['parents'])) { $params['parents'] = array($params['parents'] => 1); } if (!empty($params['parents'])) { foreach ($params['parents'] as $parentId => $dnc) { if ($parentId && !CRM_Contact_BAO_GroupNesting::isParentChild($parentId, $group->id)) { CRM_Contact_BAO_GroupNesting::add($parentId, $group->id); } } } // this is always required, since we don't know when a // parent group is removed CRM_Contact_BAO_GroupNestingCache::update(); // update group contact cache for all parent groups $parentIds = CRM_Contact_BAO_GroupNesting::getParentGroupIds($group->id); foreach ($parentIds as $parentId) { CRM_Contact_BAO_GroupContactCache::add($parentId); } } if (!empty($params['organization_id'])) { $groupOrg = $params; $groupOrg['group_id'] = $group->id; CRM_Contact_BAO_GroupOrganization::add($groupOrg); } CRM_Utils_System::flushCache(); CRM_Contact_BAO_GroupContactCache::add($group->id); if (!empty($params['id'])) { CRM_Utils_Hook::post('edit', 'Group', $group->id, $group); } else { CRM_Utils_Hook::post('create', 'Group', $group->id, $group); } $recentOther = array(); if (CRM_Core_Permission::check('edit groups')) { $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/group', 'reset=1&action=update&id=' . $group->id); // currently same permission we are using for delete a group $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/group', 'reset=1&action=delete&id=' . $group->id); } // add the recently added group (unless hidden: CRM-6432) if (!$group->is_hidden) { CRM_Utils_Recent::add($group->title, CRM_Utils_System::url('civicrm/group/search', 'reset=1&force=1&context=smog&gid=' . $group->id), $group->id, 'Group', NULL, NULL, $recentOther); } return $group; }
/** * @param $query * @param array $params * @param bool $abort * * @return string * @throws Exception */ public static function composeQuery($query, &$params, $abort = TRUE) { $tr = array(); foreach ($params as $key => $item) { if (is_numeric($key)) { if (CRM_Utils_Type::validate($item[0], $item[1]) !== NULL) { $item[0] = self::escapeString($item[0]); if ($item[1] == 'String' || $item[1] == 'Memo' || $item[1] == 'Link') { // Support class constants stipulating wildcard characters and/or // non-quoting of strings. Also support legacy code which may be // passing in TRUE or 1 for $item[2], which used to indicate the // use of wildcard characters. if (!empty($item[2])) { if ($item[2] & CRM_Core_DAO::QUERY_FORMAT_WILDCARD || $item[2] === TRUE) { $item[0] = "'%{$item[0]}%'"; } elseif (!($item[2] & CRM_Core_DAO::QUERY_FORMAT_NO_QUOTES)) { $item[0] = "'{$item[0]}'"; } } else { $item[0] = "'{$item[0]}'"; } } if (($item[1] == 'Date' || $item[1] == 'Timestamp') && strlen($item[0]) == 0) { $item[0] = 'null'; } $tr['%' . $key] = $item[0]; } elseif ($abort) { CRM_Core_Error::fatal("{$item[0]} is not of type {$item[1]}"); } } } return strtr($query, $tr); }
/** * Gets all campaign related data and returns it as a std class. * * @param int $contributionPageID * @param string $widgetID * * @return object */ public function getContributionPageData($contributionPageID, $widgetID) { $config = CRM_Core_Config::singleton(); self::registerRequest($contributionPageID, $widgetID, __FUNCTION__); $data = new stdClass(); if (empty($contributionPageID) || CRM_Utils_Type::validate($contributionPageID, 'Integer') == NULL) { $data->is_error = TRUE; CRM_Core_Error::debug_log_message("{$contributionPageID} is not set"); return $data; } $widget = new CRM_Contribute_DAO_Widget(); $widget->contribution_page_id = $contributionPageID; if (!$widget->find(TRUE)) { $data->is_error = TRUE; CRM_Core_Error::debug_log_message("{$contributionPageID} is not found"); return $data; } $data->is_error = FALSE; if (!$widget->is_active) { $data->is_active = FALSE; } $data->is_active = TRUE; $data->title = $widget->title; $data->logo = $widget->url_logo; $data->button_title = $widget->button_title; $data->button_url = CRM_Utils_System::url('civicrm/contribute/transact', "reset=1&id={$contributionPageID}", TRUE, NULL, FALSE, TRUE); $data->about = $widget->about; $query = "\nSELECT count( id ) as count,\n sum( total_amount) as amount\nFROM civicrm_contribution\nWHERE is_test = 0\nAND contribution_status_id = 1\nAND contribution_page_id = %1"; $params = array(1 => array($contributionPageID, 'Integer')); $dao = CRM_Core_DAO::executeQuery($query, $params); if ($dao->fetch()) { $data->num_donors = $dao->count; $data->money_raised = $dao->amount; } else { $data->num_donors = $data->money_raised = 0; } $query = "\nSELECT goal_amount, start_date, end_date, is_active\nFROM civicrm_contribution_page\nWHERE id = %1"; $params = array(1 => array($contributionPageID, 'Integer')); $dao = CRM_Core_DAO::executeQuery($query, $params); if ($dao->fetch()) { $data->money_target = $dao->goal_amount; $data->campaign_start = CRM_Utils_Date::customFormat($dao->start_date, $config->dateformatFull); $data->campaign_end = CRM_Utils_Date::customFormat($dao->end_date, $config->dateformatFull); // check for time being between start and end date $now = time(); if ($dao->start_date) { $startDate = CRM_Utils_Date::unixTime($dao->start_date); if ($startDate && $startDate >= $now) { $data->is_active = FALSE; } } if ($dao->end_date) { $endDate = CRM_Utils_Date::unixTime($dao->end_date); if ($endDate && $endDate < $now) { $data->is_active = FALSE; } } } else { $data->is_active = FALSE; } // if is_active is false, show this link and hide the contribute button $data->homepage_link = $widget->url_homepage; // movie clip colors, must be in '0xRRGGBB' format $data->colors = array(); $hexPrefix = '0x'; $data->colors["title"] = str_replace('#', $hexPrefix, $widget->color_title); $data->colors["button"] = str_replace('#', $hexPrefix, $widget->color_button); $data->colors["bar"] = str_replace('#', $hexPrefix, $widget->color_bar); $data->colors["main_text"] = str_replace('#', $hexPrefix, $widget->color_main_text); $data->colors["main"] = str_replace('#', $hexPrefix, $widget->color_main); $data->colors["main_bg"] = str_replace('#', $hexPrefix, $widget->color_main_bg); $data->colors["bg"] = str_replace('#', $hexPrefix, $widget->color_bg); // these two have colors as normal hex format // because they're being used in a CSS object $data->colors["about_link"] = str_replace('#', $hexPrefix, $widget->color_about_link); $data->colors["homepage_link"] = str_replace('#', $hexPrefix, $widget->color_homepage_link); return $data; }
/** * @dataProvider validateDataProvider * @param $inputData * @param $inputType * @param $expectedResult */ public function testValidate($inputData, $inputType, $expectedResult) { $this->assertEquals($expectedResult, CRM_Utils_Type::validate($inputData, $inputType, FALSE)); }
/** * @param array $userSearchParams * Supported parameters: * - beneficiary: mixed - an int-like string, a comma-separated list * thereof, or an array representing one or more contact IDs * - project: int-like string representing project ID * - proximity: array - see CRM_Volunteer_BAO_Project::buildProximityWhere * - role_id: mixed - an int-like string, a comma-separated list thereof, or * an array representing one or more role IDs * - date_start: See setSearchDateParams() * - date_end: See setSearchDateParams() */ private function setSearchParams($userSearchParams) { $this->setSearchDateParams($userSearchParams); $projectId = CRM_Utils_Array::value('project', $userSearchParams); if (CRM_Utils_Type::validate($projectId, 'Positive', FALSE)) { $this->searchParams['project']['id'] = $projectId; } $proximity = CRM_Utils_Array::value('proximity', $userSearchParams); if (is_array($proximity)) { $this->searchParams['project']['proximity'] = $proximity; } $beneficiary = CRM_Utils_Array::value('beneficiary', $userSearchParams); if ($beneficiary) { if (!array_key_exists('project_contacts', $this->searchParams['project'])) { $this->searchParams['project']['project_contacts'] = array(); } $beneficiary = is_array($beneficiary) ? $beneficiary : explode(',', $beneficiary); $this->searchParams['project']['project_contacts']['volunteer_beneficiary'] = $beneficiary; } $role = CRM_Utils_Array::value('role_id', $userSearchParams); if ($role) { $this->searchParams['need']['role_id'] = is_array($role) ? $role : explode(',', $role); } }
/** * This function takes the profile data submitted by the user, loops * and delegates the data to processProfileData. * * @param array $data * The form data that was submitted * * @return array * An array of the contact IDs created by processing the list of contact IDs */ function processAdditionalVolunteers(array $data) { $cids = array(); $qty = CRM_Utils_Array::value('additionalVolunteerQuantity', $data, 0); $qty = CRM_Utils_Type::validate($qty, 'Integer', FALSE); if ($qty === NULL) { return $cids; } //Get the profile Fields $profileFields = array(); foreach ($this->getAdditionalVolunteerProfileIDs() as $profileID) { $profileFields += CRM_Core_BAO_UFGroup::getFields($profileID); } $index = 0; while ($index < $qty) { $profileData = CRM_Utils_Array::value('additionalVolunteers_' . $index, $data, array()); $cids[] = $this->processProfileData($profileData, $profileFields); $index++; } return $cids; }