/** * Cleans field def default values before returning them as a member of the * metadata response payload * * Bug 56505 * Cleans default value of fields to strip out metacharacters used by the app. * Used initially for cleaning default multienum values. * * @param array $fielddefs * @return array */ public function normalizeFieldDefs(array $defs) { $this->getSugarFieldHandler(); foreach ($defs['fields'] as $name => $def) { if (isset($def['type'])) { $type = !empty($def['custom_type']) ? $def['custom_type'] : $def['type']; $field = $this->sfh->getSugarField($type); $defs['fields'][$name] = $field->getNormalizedDefs($def, $defs); } } return $defs['fields']; }
/** * @dataProvider _providerEmailTemplateFormat */ public function testEmailTemplateFormat($unformattedValue, $expectedValue) { require_once 'include/SugarFields/SugarFieldHandler.php'; $sfr = SugarFieldHandler::getSugarField('encrypt'); $formattedValue = $sfr->getEmailTemplateValue($unformattedValue, array(), array('notify_user' => $GLOBALS['current_user'])); $this->assertEquals($expectedValue, $formattedValue); }
private function process_reports() { require_once 'include/SugarFields/SugarFieldHandler.php'; $sfh = new SugarFieldHandler(); $sf = $sfh->getSugarField('Teamset', true); $teams = $sf->getTeamsFromRequest($this->name); $full_form_values = array(); if (!empty($teams)) { if (isset($_REQUEST["primary_{$this->name}_collection"])) { $this->ss->assign('hasPrimaryTeam', true); $primary = $_REQUEST["primary_{$this->name}_collection"]; $key = "id_{$this->name}_collection_{$primary}"; //Get the $_REQUEST index key $primary = $_REQUEST[$key]; $primaryTeam = array('id' => $primary, 'name' => $teams[$primary]); $full_form_values['primary'] = $primaryTeam; unset($teams[$primary]); //Unset the primary team } else { //Here we technically don't have a primary team chosen, but we need to allocate //a primary team to display as the first team in the widget foreach ($teams as $team_id => $team_name) { $full_form_values['primary'] = array('id' => $team_id, 'name' => $team_name); $this->showPrimaryChecked = false; unset($teams[$team_id]); break; } } foreach ($teams as $team_id => $team_name) { $full_form_values['secondaries'][] = array('id' => $team_id, 'name' => $team_name); } $this->bean->{$this->value_name} = array_merge($this->bean->{$this->value_name}, $full_form_values); } }
/** * Checks the SugarField defintion for an available santization method. * * @param $value string * @param $vardef array * @param $focus object bean of the module we're importing into * @return string sanitized and validated value on success, bool false on failure */ public function __call($name, $params) { static $sfh; if (!isset($sfh)) { require_once 'include/SugarFields/SugarFieldHandler.php'; $sfh = new SugarFieldHandler(); } $value = $params[0]; $vardef = $params[1]; if (isset($params[2])) { $focus = $params[2]; } else { $focus = null; } if ($name == 'relate' && !empty($params[3])) { $this->addRelatedBean = true; } else { $this->addRelatedBean = false; } $field = $sfh->getSugarField(ucfirst($name)); if ($field instanceof SugarFieldBase) { $value = $field->importSanitize($value, $vardef, $focus, $this); } return $value; }
/** * Gets a file and returns an HTTP response with the contents of the request file for download * * @param SugarBean $bean The SugarBean to get the file for * @param string $field The field name to get the file for * @param boolean $forceDownload force to download the file if true. */ public function getFile(SugarBean $bean, $field, $forceDownload = false) { if ($this->validateBeanAndField($bean, $field, 'file') || $this->validateBeanAndField($bean, $field, 'image')) { $def = $bean->field_defs[$field]; if ($def['type'] == 'image') { $info = $this->getImageInfo($bean, $field); } elseif ($def['type'] == 'file') { $info = $this->getFileInfo($bean, $field); require_once 'include/SugarFields/SugarFieldHandler.php'; $sfh = new SugarFieldHandler(); /* @var $sf SugarFieldFile */ $sf = $sfh->getSugarField($def['type']); //If the requested file is not a supported image type, we should force a download. if (!$forceDownload && !in_array($info['content-type'], $sf::$imageFileMimeTypes)) { $forceDownload = true; } } if ($info) { $this->outputFile($forceDownload, $info); } else { // @TODO Localize this exception message throw new Exception('File information could not be retrieved for this record'); } } }
function smarty_function_sugarvar_teamset($params, &$smarty) { require_once 'include/SugarFields/SugarFieldHandler.php'; $sfh = new SugarFieldHandler(); $sugarField = $sfh->getSugarField('Teamset'); return $sugarField->render($params, $smarty); }
function populateFromPost($prefix, &$focus, $skipRetrieve = false) { global $current_user; if (!empty($_REQUEST[$prefix . 'record']) && !$skipRetrieve) { $focus->retrieve($_REQUEST[$prefix . 'record']); } if (!empty($_POST['assigned_user_id']) && $focus->assigned_user_id != $_POST['assigned_user_id'] && $_POST['assigned_user_id'] != $current_user->id) { $GLOBALS['check_notify'] = true; } require_once 'include/SugarFields/SugarFieldHandler.php'; $sfh = new SugarFieldHandler(); foreach ($focus->field_defs as $field => $def) { $type = !empty($def['custom_type']) ? $def['custom_type'] : $def['type']; $sf = $sfh->getSugarField(ucfirst($type), true); if ($sf != null) { $sf->save($focus, $_POST, $field, $def); } if (isset($_POST[$prefix . $field])) { if (is_array($_POST[$prefix . $field]) && !empty($focus->field_defs[$field]['isMultiSelect'])) { if (empty($_POST[$prefix . $field][0])) { unset($_POST[$prefix . $field][0]); } if (!empty($_POST[$prefix . $field][0])) { $_POST[$prefix . $field] = implode('^,^', $_POST[$prefix . $field]); } else { continue; } } $focus->{$field} = $_POST[$prefix . $field]; /* * overrides the passed value for booleans. * this will be fully deprecated when the change to binary booleans is complete. */ if (isset($focus->field_defs[$prefix . $field]) && $focus->field_defs[$prefix . $field]['type'] == 'bool' && isset($focus->field_defs[$prefix . $field]['options'])) { $opts = explode("|", $focus->field_defs[$prefix . $field]['options']); $bool = $_POST[$prefix . $field]; if (is_int($bool) || ($bool === "0" || $bool === "1" || $bool === "2")) { // 1=on, 2=off $selection = $_POST[$prefix . $field] == "0" ? 1 : 0; } elseif (is_bool($_POST[$prefix . $field])) { // true=on, false=off $selection = $_POST[$prefix . $field] ? 0 : 1; } $focus->{$field} = $opts[$selection]; } } else { if (!empty($focus->field_defs[$field]['isMultiSelect']) && !isset($_POST[$prefix . $field]) && isset($_POST[$prefix . $field . '_multiselect'])) { $focus->{$field} = ''; } } } foreach ($focus->additional_column_fields as $field) { if (isset($_POST[$prefix . $field])) { $value = $_POST[$prefix . $field]; $focus->{$field} = $value; } } return $focus; }
/** * @dataProvider _providerEmailTemplateFormat */ public function testEmailTemplateFormat($unformattedValue, $expectedValue, $dateFormat, $timeFormat) { $GLOBALS['sugar_config']['default_date_format'] = $dateFormat; $GLOBALS['sugar_config']['default_time_format'] = $timeFormat; $this->user->setPreference('datef', $dateFormat); $this->user->setPreference('timef', $timeFormat); require_once 'include/SugarFields/SugarFieldHandler.php'; $sfr = SugarFieldHandler::getSugarField('datetimecombo'); $formattedValue = $sfr->getEmailTemplateValue($unformattedValue, array(), array('notify_user' => $this->user)); $this->assertEquals($expectedValue, $formattedValue); }
/** * @ticket 36744 */ public function testFormatEnumField() { $langpack = new SugarTestLangPackCreator(); $langpack->setAppListString('case_priority_dom', array('P1' => 'High', 'P2' => 'Medium', 'P3' => 'Low')); $langpack->save(); $GLOBALS['app_list_strings'] = return_app_list_strings_language($GLOBALS['current_language']); $fieldDef = array('name' => 'priority', 'vname' => 'LBL_PRIORITY', 'type' => 'enum', 'options' => 'case_priority_dom', 'len' => 25, 'audited' => true, 'comment' => 'The priority of the case'); $field_value = "P2"; require_once 'include/SugarFields/SugarFieldHandler.php'; $sfr = SugarFieldHandler::getSugarField('enum'); $this->assertEquals(trim($sfr->formatField($field_value, $fieldDef)), 'Medium'); }
public function setUp() { $enumField = SugarFieldHandler::getSugarField('enum'); $parentFieldArray = array('ACCEPT_STATUS_NAME' => 'Accepted'); $vardef = array('name' => 'accept_status_name', 'type' => 'enum', 'source' => 'non-db', 'vname' => 'LBL_LIST_ACCEPT_STATUS', 'options' => 'dom_meeting_accept_status', 'massupdate' => false, 'studio' => array('listview' => false, 'searchview' => false)); $displayParams = array('vname' => 'LBL_LIST_ACCEPT_STATUS', 'width' => '11%', 'sortable' => false, 'linked_field' => 'users', 'linked_field_set' => 'users', 'name' => 'accept_status_name', 'module' => 'Users'); $col = 1; $this->_listViewSmartyOutput1 = trim($enumField->getListViewSmarty($parentFieldArray, $vardef, $displayParams, $col)); $vardef['name'] = 'just_another_name'; $parentFieldArray['JUST_ANOTHER_NAME'] = 'None'; $this->_listViewSmartyOutput2 = trim($enumField->getListViewSmarty($parentFieldArray, $vardef, $displayParams, $col)); }
/** * Override of parent apiSave to force the custom save to be run from API * @param SugarBean $bean * @param array $params * @param string $field * @param array $properties */ public function apiSave(SugarBean $bean, array $params, $field, $properties) { // Mapped fields needs to have something to map from. if (empty($properties['mapFunction']) || empty($properties['parentField'])) { return; } // First make sure the parent field exists on this bean if (isset($bean->field_defs[$properties['parentField']])) { require_once 'include/SugarFields/SugarFieldHandler.php'; $sfh = new SugarFieldHandler(); $sf = $sfh->getSugarField($bean->field_defs[$properties['parentField']]['type']); if (method_exists($sf, $properties['mapFunction'])) { $bean->{$field} = $sf->{$properties['mapFunction']}($bean->{$properties['parentField']}); } } }
/** * Method that returns a JSON representation of the bean. * @return string */ public function toJson() { $this->retrieve(); $sfh = new SugarFieldHandler(); $data = array(); require_once 'include/api/RestService.php'; $service = new RestService(); foreach ($this->field_defs as $fieldName => $properties) { $type = !empty($properties['custom_type']) ? $properties['custom_type'] : $properties['type']; $field = $sfh->getSugarField($type); if ($field != null && isset($this->{$fieldName})) { $field->apiFormatField($data, $this, array(), $fieldName, $properties, array(), $service); } } return json_encode($data); }
/** * Save the Individual Worksheet * * @return ForecastWorksheet * @throws SugarApiException */ public function save() { require_once 'include/SugarFields/SugarFieldHandler.php'; /* @var $seed ForecastWorksheet */ $seed = BeanFactory::getBean("ForecastWorksheets"); $seed->loadFromRow($this->args); $sfh = new SugarFieldHandler(); foreach ($seed->field_defs as $properties) { $fieldName = $properties['name']; if (!isset($this->args[$fieldName])) { continue; } if (!$seed->ACLFieldAccess($fieldName, 'save')) { // No write access to this field, but they tried to edit it global $app_strings; throw new SugarApiException(string_format($app_strings['SUGAR_API_EXCEPTION_NOT_AUTHORIZED'], array($fieldName, $this->args['module']))); } $type = !empty($properties['custom_type']) ? $properties['custom_type'] : $properties['type']; $field = $sfh->getSugarField($type); if (!is_null($field)) { $field->save($seed, $this->args, $fieldName, $properties); } } // Check if this is the first commit, then save has_commits true to the config table $admin = BeanFactory::getBean('Administration'); $settings = $admin->getConfigForModule('Forecasts'); if (!isset($settings['has_commits']) || !$settings['has_commits']) { $admin->saveSetting('Forecasts', 'has_commits', true, 'base'); MetaDataManager::refreshModulesCache(array('Forecasts')); } $seed->setWorksheetArgs($this->args); // we need to set the parent_type and parent_id so it finds it when we try and retrieve the old records $seed->parent_type = $this->getArg('parent_type'); $seed->parent_id = $this->getArg('parent_id'); $seed->saveWorksheet(); // we have the id, just retrieve the record again $seed = BeanFactory::getBean("ForecastWorksheets", $this->getArg('record')); return $seed; }
/** * */ function process_page() { global $theme; global $focus; global $mod_strings; global $app_strings; global $app_list_strings; global $currentModule; global $odd_bg; global $even_bg; global $audit; global $current_language; $audit_list = Audit::get_audit_list(); $xtpl = new XTemplate('modules/Audit/Popup_picker.html'); $xtpl->assign('MOD', $mod_strings); $xtpl->assign('APP', $app_strings); insert_popup_header($theme); //output header echo "<table width='100%' cellpadding='0' cellspacing='0'><tr><td>"; $mod_strings = return_module_language($current_language, $focus->module_dir); $printImageURL = SugarThemeRegistry::current()->getImageURL('print.gif'); $titleExtra = <<<EOHTML <a href="javascript:void window.open('index.php?{$GLOBALS['request_string']}','printwin','menubar=1,status=0,resizable=1,scrollbars=1,toolbar=0,location=1')" class='utilsLink'> <!--not_in_theme!--><img src="{$printImageURL}" alt="{$GLOBALS['app_strings']['LNK_PRINT']}"></a> <a href="javascript:void window.open('index.php?{$GLOBALS['request_string']}','printwin','menubar=1,status=0,resizable=1,scrollbars=1,toolbar=0,location=1')" class='utilsLink'> {$GLOBALS['app_strings']['LNK_PRINT']} </a> EOHTML; $params = array(); $params[] = translate('LBL_MODULE_NAME', $focus->module_dir); $params[] = $focus->get_summary_text(); $params[] = translate('LBL_CHANGE_LOG', 'Audit'); echo str_replace('</div>', "<span class='utils'>{$titleExtra}</span></div>", getClassicModuleTitle($focus->module_dir, $params, false)); $oddRow = true; $audited_fields = $focus->getAuditEnabledFieldDefinitions(); asort($audited_fields); $fields = ''; $field_count = count($audited_fields); $start_tag = "<table><tr><td >"; $end_tag = "</td></tr></table>"; if ($field_count > 0) { $index = 0; foreach ($audited_fields as $key => $value) { $index++; $vname = ''; if (isset($value['vname'])) { $vname = $value['vname']; } else { if (isset($value['label'])) { $vname = $value['label']; } } $fields .= str_replace(':', '', translate($vname, $focus->module_dir)); if ($index < $field_count) { $fields .= ", "; } } echo $start_tag . translate('LBL_AUDITED_FIELDS', 'Audit') . $fields . $end_tag; } else { echo $start_tag . translate('LBL_AUDITED_FIELDS', 'Audit') . $end_tag; } foreach ($audit_list as $audit) { if (empty($audit['before_value_string']) && empty($audit['after_value_string'])) { $before_value = $audit['before_value_text']; $after_value = $audit['after_value_text']; } else { $before_value = $audit['before_value_string']; $after_value = $audit['after_value_string']; } // Let's run the audit data through the sugar field system if (isset($audit['data_type'])) { require_once 'include/SugarFields/SugarFieldHandler.php'; $vardef = array('name' => 'audit_field', 'type' => $audit['data_type']); $field = SugarFieldHandler::getSugarField($audit['data_type']); $before_value = $field->getChangeLogSmarty(array($vardef['name'] => $before_value), $vardef, array(), $vardef['name']); $after_value = $field->getChangeLogSmarty(array($vardef['name'] => $after_value), $vardef, array(), $vardef['name']); } $activity_fields = array('ID' => $audit['id'], 'NAME' => $audit['field_name'], 'BEFORE_VALUE' => $before_value, 'AFTER_VALUE' => $after_value, 'CREATED_BY' => $audit['created_by'], 'DATE_CREATED' => $audit['date_created']); $xtpl->assign("ACTIVITY", $activity_fields); if ($oddRow) { //todo move to themes $xtpl->assign("ROW_COLOR", 'oddListRow'); $xtpl->assign("BG_COLOR", $odd_bg); } else { //todo move to themes $xtpl->assign("ROW_COLOR", 'evenListRow'); $xtpl->assign("BG_COLOR", $even_bg); } $oddRow = !$oddRow; $xtpl->parse("audit.row"); // Put the rows in. } //end foreach $xtpl->parse("audit"); $xtpl->out("audit"); insert_popup_footer(); }
public function setUp() { $this->intField = SugarFieldHandler::getSugarField('int'); }
/** * Return list of fields from view def field set and populate $displayParams with display parameters * of link and collection fields * * @param array $fieldSet The field set * @param array $fieldDefs Bean field definitions * @param array $displayParams Associative array of field names and their display params * @return array * * @access protected Should be used only by SugarFieldBase and subclasses */ public function getFieldNames(array $fieldSet, array $fieldDefs, &$displayParams) { $fields = array(); foreach ($fieldSet as $field) { if (is_string($field)) { // direct field name $field = array('name' => $field); } if (is_array($field)) { $type = 'base'; if (isset($field['name'])) { $fields[] = $field['name']; if (isset($fieldDefs[$field['name']]['type'])) { $type = $fieldDefs[$field['name']]['type']; } } $sf = SugarFieldHandler::getSugarField($type); $sf->processLayoutField($this, $field, $fieldDefs, $fields, $displayParams); } } return $fields; }
/** * get_teams_hidden_inputs * This is a helper function to construct a String of the hidden input parameters representing the * teams that were sent to the form base code * * @param $module String value of module * @return String HTML format of teams sent to the form base code */ function get_teams_hidden_inputs($module = '') { $_REQUEST = array_merge($_REQUEST, $_POST); if (!empty($module)) { foreach ($_REQUEST as $name => $value) { if (preg_match("/^{$module}(.*?team_name.*?\$)/", $name, $matches)) { $_REQUEST[$matches[1]] = $value; } } } require_once 'include/SugarFields/SugarFieldHandler.php'; $sfh = new SugarFieldHandler(); $sf = $sfh->getSugarField('Teamset', true); $teams = $sf->getTeamsFromRequest('team_name'); $input = ''; if (!empty($teams)) { $count = 0; foreach ($teams as $id => $name) { $input .= "<input type='hidden' name='id_team_name_collection_{$count}' value='" . urlencode($id) . "'>\n"; $input .= "<input type='hidden' name='team_name_collection_{$count}' value='" . urlencode($name) . "'>\n"; $count++; } if (isset($_REQUEST['primary_team_name_collection'])) { $input .= "<input type='hidden' name='primary_team_name_collection' value='" . $_REQUEST['primary_team_name_collection'] . "'>\n"; } } return $input; }
/** * @return void * @param unknown $data * @param unknown $xTemplateSection * @param unknown $html_varName * @desc INTERNAL FUNCTION handles the rows */ function process_dynamic_listview_rows($data, $parent_data, $xtemplateSection, $html_varName, $subpanel_def) { global $odd_bg; global $even_bg; global $hilite_bg; global $click_bg; $this->xTemplate->assign("BG_HILITE", $hilite_bg); $this->xTemplate->assign('CHECKALL', "<img src='" . SugarThemeRegistry::current()->getImageURL('blank.gif') . "' width=\"1\" height=\"1\" alt=\"\" />"); //$this->xTemplate->assign("BG_CLICK", $click_bg); $oddRow = true; $count = 0; reset($data); //GETTING OFFSET $offset = $this->getOffset($html_varName); //$totaltime = 0; $processed_ids = array(); $fill_additional_fields = array(); //Either retrieve the is_fill_in_additional_fields property from the lone //subpanel or visit each subpanel's subpanels to retreive the is_fill_in_addition_fields //property $subpanel_list = array(); if ($subpanel_def->isCollection()) { $subpanel_list = $subpanel_def->sub_subpanels; } else { $subpanel_list[] = $subpanel_def; } foreach ($subpanel_list as $this_subpanel) { if ($this_subpanel->is_fill_in_additional_fields()) { $fill_additional_fields[] = $this_subpanel->bean_name; $fill_additional_fields[$this_subpanel->bean_name] = true; } } if (empty($data)) { $this->xTemplate->assign("ROW_COLOR", 'oddListRow'); $thepanel = $subpanel_def; if ($subpanel_def->isCollection()) { $thepanel = $subpanel_def->get_header_panel_def(); } $this->xTemplate->assign("COL_COUNT", count($thepanel->get_list_fields())); $this->xTemplate->parse($xtemplateSection . ".nodata"); } while (list($aVal, $aItem) = each($data)) { $aItem->check_date_relationships_load(); // TODO: expensive and needs to be removed and done better elsewhere if (!empty($fill_additional_fields[$aItem->object_name]) || $aItem->object_name == 'Case' && !empty($fill_additional_fields['aCase'])) { $aItem->fill_in_additional_list_fields(); //$aItem->fill_in_additional_detail_fields(); } //rrs bug: 25343 $aItem->call_custom_logic("process_record"); if (isset($parent_data[$aItem->id])) { $aItem->parent_name = $parent_data[$aItem->id]['parent_name']; if (!empty($parent_data[$aItem->id]['parent_name_owner'])) { $aItem->parent_name_owner = $parent_data[$aItem->id]['parent_name_owner']; $aItem->parent_name_mod = $parent_data[$aItem->id]['parent_name_mod']; } } $fields = $aItem->get_list_view_data(); if (isset($processed_ids[$aItem->id])) { continue; } else { $processed_ids[$aItem->id] = 1; } //ADD OFFSET TO ARRAY $fields['OFFSET'] = $offset + $count + 1; if ($this->shouldProcess) { if ($aItem->ACLAccess('EditView')) { $this->xTemplate->assign('PREROW', "<input type='checkbox' class='checkbox' name='mass[]' value='" . $fields['ID'] . "' />"); } else { $this->xTemplate->assign('PREROW', ''); } if ($aItem->ACLAccess('DetailView')) { $this->xTemplate->assign('TAG_NAME', 'a'); } else { $this->xTemplate->assign('TAG_NAME', 'span'); } $this->xTemplate->assign('CHECKALL', "<input type='checkbox' class='checkbox' name='massall' id='massall' value='' onclick='sListView.check_all(document.MassUpdate, \"mass[]\", this.checked);' />"); } if ($oddRow) { $ROW_COLOR = 'oddListRow'; $BG_COLOR = $odd_bg; } else { $ROW_COLOR = 'evenListRow'; $BG_COLOR = $even_bg; } $oddRow = !$oddRow; $this->xTemplate->assign("ROW_COLOR", $ROW_COLOR); $this->xTemplate->assign("BG_COLOR", $BG_COLOR); $layout_manager = $this->getLayoutManager(); $layout_manager->setAttribute('context', 'List'); $layout_manager->setAttribute('image_path', $this->local_image_path); $layout_manager->setAttribute('module_name', $subpanel_def->_instance_properties['module']); if (!empty($this->child_focus)) { $layout_manager->setAttribute('related_module_name', $this->child_focus->module_dir); } //AG$subpanel_data = $this->list_field_defs; //$bla = array_pop($subpanel_data); //select which sub-panel to display here, the decision will be made based on the type of //the sub-panel and panel in the bean being processed. if ($subpanel_def->isCollection()) { $thepanel = $subpanel_def->sub_subpanels[$aItem->panel_name]; } else { $thepanel = $subpanel_def; } //get data source name $linked_field = $thepanel->get_data_source_name(); $linked_field_set = $thepanel->get_data_source_name(true); foreach ($thepanel->get_list_fields() as $field_name => $list_field) { //add linked field attribute to the array. $list_field['linked_field'] = $linked_field; $list_field['linked_field_set'] = $linked_field_set; $usage = empty($list_field['usage']) ? '' : $list_field['usage']; if ($usage != 'query_only') { $list_field['name'] = $field_name; $module_field = $field_name . '_mod'; $owner_field = $field_name . '_owner'; if (!empty($aItem->{$module_field})) { $list_field['owner_id'] = $aItem->{$owner_field}; $list_field['owner_module'] = $aItem->{$module_field}; } else { $list_field['owner_id'] = false; $list_field['owner_module'] = false; } if (isset($list_field['alias'])) { $list_field['name'] = $list_field['alias']; } else { $list_field['name'] = $field_name; } $list_field['fields'] = $fields; $list_field['module'] = $aItem->module_dir; $list_field['start_link_wrapper'] = $this->start_link_wrapper; $list_field['end_link_wrapper'] = $this->end_link_wrapper; $list_field['subpanel_id'] = $this->subpanel_id; $list_field['DetailView'] = $aItem->ACLAccess('DetailView'); $list_field['ListView'] = $aItem->ACLAccess('ListView'); $list_field['EditView'] = $aItem->ACLAccess('EditView'); $list_field['Delete'] = $aItem->ACLAccess('Delete'); if (isset($aItem->field_defs[strtolower($list_field['name'])])) { require_once 'include/SugarFields/SugarFieldHandler.php'; // We need to see if a sugar field exists for this field type first, // if it doesn't, toss it at the old sugarWidgets. This is for // backwards compatibilty and will be removed in a future release $vardef = $aItem->field_defs[strtolower($list_field['name'])]; if (isset($vardef['type'])) { $fieldType = isset($vardef['custom_type']) ? $vardef['custom_type'] : $vardef['type']; $tmpField = SugarFieldHandler::getSugarField($fieldType, true); } else { $tmpField = NULL; } if ($tmpField != NULL) { $widget_contents = SugarFieldHandler::displaySmarty($list_field['fields'], $vardef, 'ListView', $list_field); } else { // No SugarField for this particular type // Use the old, icky, SugarWidget for now $widget_contents = $layout_manager->widgetDisplay($list_field); } if (isset($list_field['widget_class']) && $list_field['widget_class'] == 'SubPanelDetailViewLink') { // We need to call into the old SugarWidgets for the time being, so it can generate a proper link with all the various corner-cases handled // So we'll populate the field data with the pre-rendered display for the field $list_field['fields'][$field_name] = $widget_contents; if ('full_name' == $field_name) { //bug #32465 $list_field['fields'][strtoupper($field_name)] = $widget_contents; } $widget_contents = $layout_manager->widgetDisplay($list_field); } else { if (isset($list_field['widget_class']) && $list_field['widget_class'] == 'SubPanelEmailLink') { $widget_contents = $layout_manager->widgetDisplay($list_field); } } } else { // This handles the edit and remove buttons $widget_contents = $layout_manager->widgetDisplay($list_field); } static $count; if (!isset($count)) { $count = 0; } else { $count++; } $this->xTemplate->assign('CELL_COUNT', $count); if (empty($widget_contents)) { $widget_contents = ' '; } $this->xTemplate->assign('CELL', $widget_contents); $this->xTemplate->parse($xtemplateSection . ".row.cell"); } } $aItem->setupCustomFields($aItem->module_dir); $aItem->custom_fields->populateAllXTPL($this->xTemplate, 'detail', $html_varName, $fields); $count++; $this->xTemplate->parse($xtemplateSection . ".row"); } $this->xTemplate->parse($xtemplateSection); }
/** * getExportContentsFromResult * * This is a function to handle the processing of generating the export contents. * * @param Mixed $focus SugarBean instance we are retrieving export results for * @param Mixed $result database result resource from the export SQL * @param bool $members used to indicate whether or not to apply filtering for header rows; false by default * @param array $remove_from_members Array of header columns to filter out; empty by default * @param bool $populate boolean used to indicate whether or not to populate with test data; false by default * @return string */ function getExportContentFromResult($focus, $result, $members = false, $remove_from_members = array(), $populate = false) { global $current_user, $locale, $app_strings; $sampleRecordNum = 5; $delimiter = getDelimiter(); $timedate = TimeDate::getInstance(); $db = DBManagerFactory::getInstance(); $fields_array = $db->getFieldsArray($result, true); // check if ID field is contained in query result $is_id_exported = in_array('id', $fields_array); //set up the order on the header row $fields_array = get_field_order_mapping($focus->module_dir, $fields_array, true, $focus->fields_to_exclude); //set up labels to be used for the header row $field_labels = array(); foreach ($fields_array as $key => $dbname) { //Remove fields that are only used for logic if ($members && in_array($dbname, $remove_from_members)) { continue; } //default to the db name of label does not exist $field_labels[$key] = translateForExport($dbname, $focus); } $user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : ''; if ($locale->getExportCharset() == 'UTF-8' && !preg_match('/macintosh|mac os x|mac_powerpc/i', $user_agent)) { //Bug 55520 - add BOM to the exporting CSV so any symbols are displayed correctly in Excel $BOM = ""; $content = $BOM; } else { $content = ''; } $pre_id = ''; // Setup the "header" row with proper delimiters $content .= "\"" . implode("\"" . getDelimiter() . "\"", array_values($field_labels)) . "\"\r\n"; if ($populate) { //this is a sample request with no data, so create fake datarows $content .= returnFakeDataRow($focus, $fields_array, $sampleRecordNum); } else { $records = array(); //process retrieved record $isAdminUser = is_admin($current_user); while ($val = $db->fetchByAssoc($result, false)) { //order the values in the record array $val = get_field_order_mapping($focus->module_dir, $val); $new_arr = array(); if (!$isAdminUser) { $focus->id = !empty($val['id']) ? $val['id'] : ''; $focus->assigned_user_id = !empty($val['assigned_user_id']) ? $val['assigned_user_id'] : ''; $focus->created_by = !empty($val['created_by']) ? $val['created_by'] : ''; $focus->ACLFilterFieldList($val, array(), array("blank_value" => true)); } if ($members) { if ($is_id_exported && $pre_id == $val['id']) { continue; } if (isset($val['ea_deleted']) && isset($val['primary_email_address']) && ($val['ea_deleted'] == 1 || $val['ear_deleted'] == 1)) { $val['primary_email_address'] = ''; } unset($val['ea_deleted']); unset($val['ear_deleted']); unset($val['primary_address']); } $pre_id = $is_id_exported ? $val['id'] : ''; require_once 'include/SugarFields/SugarFieldHandler.php'; //replace user_name with full name if use_real_name preference setting is enabled //and this is a user name field $useRealNames = $current_user->getPreference('use_real_names'); foreach ($val as $key => $value) { //if key is not part of field map, then continue if (!isset($fields_array[$key])) { continue; } //getting content values depending on their types $fieldNameMapKey = $fields_array[$key]; if (isset($focus->field_name_map[$fieldNameMapKey]) && $focus->field_name_map[$fieldNameMapKey]['type']) { $sfh = SugarFieldHandler::getSugarField($focus->field_name_map[$fieldNameMapKey]['type']); $value = $sfh->exportSanitize($value, $focus->field_defs[$key], $focus, $val); } if (isset($focus->field_name_map[$fields_array[$key]]['custom_type']) && $focus->field_name_map[$fields_array[$key]]['custom_type'] == 'teamset') { require_once 'modules/Teams/TeamSetManager.php'; $value = TeamSetManager::getCommaDelimitedTeams($val['team_set_id'], !empty($val['team_id']) ? $val['team_id'] : ''); } if ($useRealNames) { $value = formatRealNameField($focus, $fields_array, $key, $value); } // Keep as $key => $value for post-processing $new_arr[$key] = str_replace('"', '""', $value); } //foreach // Use Bean ID as key for records if it exists if ($is_id_exported) { $records[$pre_id] = $new_arr; } else { $records[] = $new_arr; } } // Check if we're going to export non-primary emails if ($is_id_exported && $focus->hasEmails()) { // Add header column $field_labels['email_addresses_non_primary'] = translateForExport('email_addresses_non_primary', $focus); // $records keys are bean ids $keys = array_keys($records); $email_data = getNonPrimaryEmailsData($focus, $keys); foreach (array_keys($records) as $bean_id) { $records[$bean_id]['email_addresses_non_primary'] = isset($email_data[$bean_id]) ? $email_data[$bean_id] : ''; } } // Write the export data foreach ($records as $record) { $line = implode("\"" . $delimiter . "\"", $record); $line = "\"" . $line; $line .= "\"\r\n"; $content .= $line; } } return $content; }
/** * Gets an array of beans from a SugarQuery * * @param SugarQuery $query - Query object with everything but the from() section filled in * @param array $fields - (Optional) A list of fields to populate in the beans * @param array $options - (Optional) Optional parameters for the function: * returnRawRows - Returns raw rows in the _row key, indexed by bean id * beanList - An array of beans to merge the results into * skipSecondaryQuery - Don't perform the secondary queries * @return array SugarBean - An array of SugarBeans populated with the requested fields */ function fetchFromQuery(SugarQuery $query, array $fields = array(), array $options = array()) { $queryFields = array(); $secondaryFields = array(); $beans = array(); $sfh = new SugarFieldHandler(); if (empty($fields)) { $fields = array_keys($this->field_defs); } foreach ($fields as $field) { if (!isset($this->field_defs[$field]) || !isset($this->field_defs[$field]['type'])) { // Not a valid field, remove it from the list continue; } $def = $this->field_defs[$field]; if ($def['type'] == 'link') { continue; } if (isset($def['link_type']) && $def['link_type'] == 'relationship_info') { // These fields are only here for backwards compatibility continue; } if (isset($def['link']) && $def['link'] != true && !isset($this->field_defs[$def['link']])) { $GLOBALS['log']->error("Invalid link detected: {$field} is looking for {$def['link']}"); continue; } if (!isset($options['skipSecondaryQuery']) || $options['skipSecondaryQuery'] == false) { $type = !empty($def['custom_type']) ? $def['custom_type'] : $this->db->getFieldType($def); $sugarField = $sfh->getSugarField($type); if ($sugarField->fieldNeedsSecondaryQuery($field, $this)) { $secondaryFields[$field] = $sugarField; continue; } } if (isset($def['source']) && $def['source'] == 'non-db' && (empty($def['rname']) || empty($def['link']))) { // Non-db that isn't a relate field. continue; } $queryFields[$field] = $field; // Disable distinct on text type fields, since Oracle doesn't // allow distinct selects on CLOB types $fieldType = $this->db->getFieldType($def); $isTextType = $fieldType ? $this->db->isTextType($fieldType) : false; if ($isTextType) { $query->distinct(false); } } foreach ($this->field_defs as $field => $fieldDef) { if (isset($fieldDef['mandatory_fetch']) && $fieldDef['mandatory_fetch'] == true) { $queryFields[$field] = $field; } } $queryFields['id'] = 'id'; if (isset($this->field_defs['assigned_user_id'])) { $queryFields['assigned_user_id'] = 'assigned_user_id'; } $query->select($queryFields); $this->call_custom_logic('before_fetch_query', array('query' => $query, 'fields' => $fields)); $rows = $query->execute(); $rawRows = array(); foreach ($rows as $row) { if (isset($options['beanList'][$row['id']])) { $bean = $options['beanList'][$row['id']]; } else { $bean = $this->getCleanCopy(); } //true parameter below tells populate to perform conversions on row data $bean->fetched_row = $bean->populateFromRow($row, true); $bean->call_custom_logic("process_record"); $beans[$bean->id] = $bean; $rawRows[$bean->id] = $row; } if (!isset($options['skipSecondaryQuery']) || $options['skipSecondaryQuery'] == false) { foreach ($secondaryFields as $fieldName => $sugarField) { $sugarField->runSecondaryQuery($fieldName, $this, $beans); } } $this->call_custom_logic('after_fetch_query', array('beans' => $beans, 'fields' => $fields, 'rows' => $rawRows)); if (!empty($options['compensateDistinct'])) { $beans['_distinctCompensation'] = $this->computeDistinctCompensation($rows, $beans); } if (!empty($options['returnRawRows'])) { $beans['_rows'] = $rawRows; } return $beans; }
/** * Perform the Exact type query * * @param array $layout_def * @return string the subquery to be run */ function queryFilterexact(&$layout_def) { require_once 'include/SugarFields/SugarFieldHandler.php'; $sfh = new SugarFieldHandler(); $sf = $sfh->getSugarField('teamset'); $teams = array(); if (!empty($layout_def['input_name0'])) { foreach ($layout_def['input_name0'] as $team) { $teams[$team] = $team; } } $searchParams = $sf->getTeamSetIdSearchField('team_set_id', 'exact', $teams); $query = string_format($searchParams['subquery'], array($searchParams['value'])); return $this->_get_column_select($layout_def) . "= ({$query}) " . $this->queryPrimaryTeam($layout_def) . "\n"; }
/** * Populate the searchFields from an array * * @param array $array array to search through * @param string $switchVar variable to use in switch statement * @param bool $addAllBeanFields true to process at all bean fields */ function populateFromArray(&$array, $switchVar = null, $addAllBeanFields = true) { if ((!empty($array['searchFormTab']) || !empty($switchVar)) && !empty($this->searchFields)) { $arrayKeys = array_keys($array); $searchFieldsKeys = array_keys($this->searchFields); if (empty($switchVar)) { $switchVar = $array['searchFormTab']; } //name of the search tab $SearchName = str_replace('_search', '', $switchVar); if ($switchVar == 'saved_views') { foreach ($this->searchFields as $name => $params) { foreach ($this->tabs as $tabName) { if (!empty($array[$name . '_' . $tabName['name']])) { $this->searchFields[$name]['value'] = $array[$name . '_' . $tabName['name']]; if (empty($this->fieldDefs[$name . '_' . $tabName['name']]['value'])) { $this->fieldDefs[$name . '_' . $tabName['name']]['value'] = $array[$name . '_' . $tabName['name']]; } } } } if ($addAllBeanFields) { foreach ($this->seed->field_name_map as $key => $params) { if (!in_array($key, $searchFieldsKeys)) { foreach ($this->tabs->name as $tabName) { if (in_array($key . '_' . $tabName['name'], $arrayKeys)) { $this->searchFields[$key] = array('query_type' => 'default', 'value' => $array[$key . '_' . $tabName['name']]); } } } } } } else { $fromMergeRecords = isset($array['merge_module']); foreach ($this->searchFields as $name => $params) { $long_name = $name . '_' . $SearchName; /*nsingh 21648: Add additional check for bool values=0. empty() considers 0 to be empty Only repopulates if value is 0 or 1:( */ if (isset($array[$long_name]) && !$this->isEmptyDropdownField($long_name, $array[$long_name]) && ($array[$long_name] !== '' || isset($this->fieldDefs[$long_name]['type']) && $this->fieldDefs[$long_name]['type'] == 'bool' && ($array[$long_name] == '0' || $array[$long_name] == '1'))) { $this->searchFields[$name]['value'] = $array[$long_name]; if (empty($this->fieldDefs[$long_name]['value'])) { $this->fieldDefs[$long_name]['value'] = $array[$long_name]; } } else { if (!empty($array[$name]) && !$fromMergeRecords && !$this->isEmptyDropdownField($name, $array[$name])) { //basic $this->searchFields[$name]['value'] = $array[$name]; if (empty($this->fieldDefs[$long_name]['value'])) { $this->fieldDefs[$long_name]['value'] = $array[$name]; } } } if (!empty($params['enable_range_search']) && isset($this->searchFields[$name]['value'])) { if (preg_match('/^range_(.*?)$/', $long_name, $match) && isset($array[$match[1] . '_range_choice'])) { $this->searchFields[$name]['operator'] = $array[$match[1] . '_range_choice']; } } if (!empty($params['is_date_field']) && isset($this->searchFields[$name]['value'])) { global $timedate; // FG - bug 45287 - to db conversion is ok, but don't adjust timezone (not now), otherwise you'll jump to the day before (if at GMT-xx) $date_value = $timedate->to_db_date($this->searchFields[$name]['value'], false); $this->searchFields[$name]['value'] = $date_value == '' ? $this->searchFields[$name]['value'] : $date_value; } } if ((empty($array['massupdate']) || $array['massupdate'] == 'false') && $addAllBeanFields) { foreach ($this->seed->field_name_map as $key => $params) { if ($key != 'assigned_user_name' && $key != 'modified_by_name') { $long_name = $key . '_' . $SearchName; if (in_array($key . '_' . $SearchName, $arrayKeys) && !in_array($key, $searchFieldsKeys) && !$this->isEmptyDropdownField($long_name, $array[$long_name])) { $this->searchFields[$key] = array('query_type' => 'default', 'value' => $array[$long_name]); if (!empty($params['type']) && $params['type'] == 'parent' && !empty($params['type_name']) && !empty($this->searchFields[$key]['value'])) { require_once 'include/SugarFields/SugarFieldHandler.php'; $sfh = new SugarFieldHandler(); $sf = $sfh->getSugarField('Parent'); $this->searchFields[$params['type_name']] = array('query_type' => 'default', 'value' => $sf->getSearchInput($params['type_name'], $array)); } if (empty($this->fieldDefs[$long_name]['value'])) { $this->fieldDefs[$long_name]['value'] = $array[$long_name]; } } } } } } } if (is_array($this->searchFields)) { foreach ($this->searchFields as $fieldName => $field) { if (!empty($field['value']) && is_string($field['value'])) { $this->searchFields[$fieldName]['value'] = trim($field['value']); } } } }
/** * Moves temporary files associated with the bean from the temporary folder * to the upload folder. * * @param array $args The request arguments. * @param SugarBean $bean The bean associated with the file. * @throws SugarApiExceptionInvalidParameter If the file mime types differ * from $imageFileMimeTypes. */ protected function moveTemporaryFiles($args, SugarBean $bean) { require_once 'include/upload_file.php'; require_once 'include/SugarFields/SugarFieldHandler.php'; $fileFields = $bean->getFieldDefinitions('type', array('file', 'image')); $sfh = new SugarFieldHandler(); // FIXME This path should be changed with BR-1955. $basepath = UploadStream::path('upload://tmp/'); $configDir = SugarConfig::getInstance()->get('upload_dir', 'upload'); foreach ($fileFields as $fieldName => $def) { if (empty($args[$fieldName . '_guid'])) { continue; } $this->verifyFieldAccess($bean, $fieldName); $filepath = $basepath . $args[$fieldName . '_guid']; if (!is_file($filepath)) { continue; } if ($def['type'] === 'image') { $filename = $args[$fieldName . '_guid']; $bean->{$fieldName} = $filename; } else { // FIXME Image verification and mime type updating // should not be duplicated from SugarFieldFile. // SC-3338 is tracking this. require_once 'include/utils/file_utils.php'; $filename = $bean->id; $mimeType = get_file_mime_type($filepath, 'application/octet-stream'); $sf = $sfh->getSugarField($def['type']); $extension = pathinfo($fieldName, PATHINFO_EXTENSION); if (in_array($mimeType, $sf::$imageFileMimeTypes) && !verify_image_file($filepath)) { throw new SugarApiExceptionInvalidParameter(string_format($GLOBALS['app_strings']['LBL_UPLOAD_IMAGE_FILE_NOT_SUPPORTED'], array($extension))); } $bean->file_mime_type = $mimeType; $bean->file_ext = $extension; } $destination = rtrim($configDir, '/\\') . '/' . $filename; // FIXME BR-1956 will address having multiple files // associated with a record. rename($filepath, $destination); } }
/** * @return void * @param unknown $data * @param unknown $xTemplateSection * @param unknown $html_varName * @desc INTERNAL FUNCTION handles the rows */ function process_dynamic_listview_rows($data, $parent_data, $xtemplateSection, $html_varName, $subpanel_def) { global $subpanel_item_count; global $odd_bg; global $even_bg; global $hilite_bg; global $click_bg; $this->xTemplate->assign("BG_HILITE", $hilite_bg); $this->xTemplate->assign('CHECKALL', SugarThemeRegistry::current()->getImage('blank', '', 1, 1, ".gif", '')); //$this->xTemplate->assign("BG_CLICK", $click_bg); $subpanel_item_count = 0; $oddRow = true; $count = 0; reset($data); //GETTING OFFSET $offset = $this->getOffset($html_varName); //$totaltime = 0; $processed_ids = array(); $fill_additional_fields = array(); //Either retrieve the is_fill_in_additional_fields property from the lone //subpanel or visit each subpanel's subpanels to retrieve the is_fill_in_addition_fields //property $subpanel_list = array(); if ($subpanel_def->isCollection()) { $subpanel_list = $subpanel_def->sub_subpanels; } else { $subpanel_list[] = $subpanel_def; } foreach ($subpanel_list as $this_subpanel) { if ($this_subpanel->is_fill_in_additional_fields()) { $fill_additional_fields[] = $this_subpanel->bean_name; $fill_additional_fields[$this_subpanel->bean_name] = true; } } if (empty($data)) { $this->xTemplate->assign("ROW_COLOR", 'oddListRow'); $thepanel = $subpanel_def; if ($subpanel_def->isCollection()) { $thepanel = $subpanel_def->get_header_panel_def(); } $this->xTemplate->assign("COL_COUNT", count($thepanel->get_list_fields())); $this->xTemplate->parse($xtemplateSection . ".nodata"); } while (list($aVal, $aItem) = each($data)) { $subpanel_item_count++; $aItem->check_date_relationships_load(); // TODO: expensive and needs to be removed and done better elsewhere if (!empty($fill_additional_fields[$aItem->object_name]) || $aItem->object_name == 'Case' && !empty($fill_additional_fields['aCase'])) { $aItem->fill_in_additional_list_fields(); //$aItem->fill_in_additional_detail_fields(); } //rrs bug: 25343 $aItem->call_custom_logic("process_record"); if (isset($parent_data[$aItem->id])) { $aItem->parent_name = $parent_data[$aItem->id]['parent_name']; if (!empty($parent_data[$aItem->id]['parent_name_owner'])) { $aItem->parent_name_owner = $parent_data[$aItem->id]['parent_name_owner']; $aItem->parent_name_mod = $parent_data[$aItem->id]['parent_name_mod']; } } $fields = $aItem->get_list_view_data(); if (isset($processed_ids[$aItem->id])) { continue; } else { $processed_ids[$aItem->id] = 1; } //ADD OFFSET TO ARRAY $fields['OFFSET'] = $offset + $count + 1; if ($this->shouldProcess) { if ($aItem->ACLAccess('EditView')) { $this->xTemplate->assign('PREROW', "<input type='checkbox' class='checkbox' name='mass[]' value='" . $fields['ID'] . "' />"); } else { $this->xTemplate->assign('PREROW', ''); } if ($aItem->ACLAccess('DetailView')) { $this->xTemplate->assign('TAG_NAME', 'a'); } else { $this->xTemplate->assign('TAG_NAME', 'span'); } $this->xTemplate->assign('CHECKALL', "<input type='checkbox' title='" . $GLOBALS['app_strings']['LBL_SELECT_ALL_TITLE'] . "' class='checkbox' name='massall' id='massall' value='' onclick='sListView.check_all(document.MassUpdate, \"mass[]\", this.checked);' />"); } if ($oddRow) { $ROW_COLOR = 'oddListRow'; $BG_COLOR = $odd_bg; } else { $ROW_COLOR = 'evenListRow'; $BG_COLOR = $even_bg; } $oddRow = !$oddRow; $button_contents = array(); $this->xTemplate->assign("ROW_COLOR", $ROW_COLOR); $this->xTemplate->assign("BG_COLOR", $BG_COLOR); $layout_manager = $this->getLayoutManager(); $layout_manager->setAttribute('context', 'List'); $layout_manager->setAttribute('image_path', $this->local_image_path); $layout_manager->setAttribute('module_name', $subpanel_def->_instance_properties['module']); if (!empty($this->child_focus)) { $layout_manager->setAttribute('related_module_name', $this->child_focus->module_dir); } //AG$subpanel_data = $this->list_field_defs; //$bla = array_pop($subpanel_data); //select which sub-panel to display here, the decision will be made based on the type of //the sub-panel and panel in the bean being processed. if ($subpanel_def->isCollection()) { $thepanel = $subpanel_def->sub_subpanels[$aItem->panel_name]; } else { $thepanel = $subpanel_def; } //get data source name $linked_field = $thepanel->get_data_source_name(); $linked_field_set = $thepanel->get_data_source_name(true); static $count; if (!isset($count)) { $count = 0; } $field_acl['DetailView'] = $aItem->ACLAccess('DetailView'); $field_acl['ListView'] = $aItem->ACLAccess('ListView'); $field_acl['EditView'] = $aItem->ACLAccess('EditView'); $field_acl['Delete'] = $aItem->ACLAccess('Delete'); foreach ($thepanel->get_list_fields() as $field_name => $list_field) { //add linked field attribute to the array. $list_field['linked_field'] = $linked_field; $list_field['linked_field_set'] = $linked_field_set; $usage = empty($list_field['usage']) ? '' : $list_field['usage']; if ($usage != 'query_only') { $list_field['name'] = $field_name; $module_field = $field_name . '_mod'; $owner_field = $field_name . '_owner'; if (!empty($aItem->{$module_field})) { $list_field['owner_id'] = $aItem->{$owner_field}; $list_field['owner_module'] = $aItem->{$module_field}; } else { $list_field['owner_id'] = false; $list_field['owner_module'] = false; } if (isset($list_field['alias'])) { $list_field['name'] = $list_field['alias']; } else { $list_field['name'] = $field_name; } $list_field['fields'] = $fields; $list_field['module'] = $aItem->module_dir; $list_field['start_link_wrapper'] = $this->start_link_wrapper; $list_field['end_link_wrapper'] = $this->end_link_wrapper; $list_field['subpanel_id'] = $this->subpanel_id; $list_field += $field_acl; if (isset($aItem->field_defs[strtolower($list_field['name'])])) { require_once 'include/SugarFields/SugarFieldHandler.php'; // We need to see if a sugar field exists for this field type first, // if it doesn't, toss it at the old sugarWidgets. This is for // backwards compatibility and will be removed in a future release $vardef = $aItem->field_defs[strtolower($list_field['name'])]; if (isset($vardef['type'])) { $fieldType = isset($vardef['custom_type']) ? $vardef['custom_type'] : $vardef['type']; $tmpField = SugarFieldHandler::getSugarField($fieldType, true); } else { $tmpField = NULL; } if ($tmpField != NULL) { $widget_contents = SugarFieldHandler::displaySmarty($list_field['fields'], $vardef, 'ListView', $list_field); } else { // No SugarField for this particular type // Use the old, icky, SugarWidget for now $widget_contents = $layout_manager->widgetDisplay($list_field); } if (isset($list_field['widget_class']) && $list_field['widget_class'] == 'SubPanelDetailViewLink') { // We need to call into the old SugarWidgets for the time being, so it can generate a proper link with all the various corner-cases handled // So we'll populate the field data with the pre-rendered display for the field $list_field['fields'][$field_name] = $widget_contents; if ('full_name' == $field_name) { //bug #32465 $list_field['fields'][strtoupper($field_name)] = $widget_contents; } //vardef source is non db, assign the field name to varname for processing of column. if (!empty($vardef['source']) && $vardef['source'] == 'non-db') { $list_field['varname'] = $field_name; } $widget_contents = $layout_manager->widgetDisplay($list_field); } else { if (isset($list_field['widget_class']) && $list_field['widget_class'] == 'SubPanelEmailLink') { $widget_contents = $layout_manager->widgetDisplay($list_field); } } $count++; $this->xTemplate->assign('CELL_COUNT', $count); $this->xTemplate->assign('CLASS', ""); if (empty($widget_contents)) { $widget_contents = ' '; } $this->xTemplate->assign('CELL', $widget_contents); $this->xTemplate->parse($xtemplateSection . ".row.cell"); } else { // This handles the edit and remove buttons and icon widget if (isset($list_field['widget_class']) && $list_field['widget_class'] == "SubPanelIcon") { $count++; $widget_contents = $layout_manager->widgetDisplay($list_field); $this->xTemplate->assign('CELL_COUNT', $count); $this->xTemplate->assign('CLASS', ""); if (empty($widget_contents)) { $widget_contents = ' '; } $this->xTemplate->assign('CELL', $widget_contents); $this->xTemplate->parse($xtemplateSection . ".row.cell"); } elseif (preg_match("/button/i", $list_field['name'])) { if ($layout_manager->widgetDisplay($list_field) != "") { $button_contents[] = $layout_manager->widgetDisplay($list_field); } } else { $count++; $this->xTemplate->assign('CLASS', ""); $widget_contents = $layout_manager->widgetDisplay($list_field); $this->xTemplate->assign('CELL_COUNT', $count); if (empty($widget_contents)) { $widget_contents = ' '; } $this->xTemplate->assign('CELL', $widget_contents); $this->xTemplate->parse($xtemplateSection . ".row.cell"); } } } } // Make sure we have at least one button before rendering a column for // the action buttons in a list view. Relevant bugs: #51647 and #51640. if (isset($button_contents[0])) { // this is for inline buttons on listviews // bug#51275: smarty widget to help provide the action menu functionality as it is currently sprinkled throughout the app with html require_once 'include/Smarty/plugins/function.sugar_action_menu.php'; $tempid = create_guid(); $button_contents[0] = "<div style='display: inline' id='{$tempid}'>" . $button_contents[0] . "</div>"; $action_button = smarty_function_sugar_action_menu(array('id' => $tempid, 'buttons' => $button_contents, 'class' => 'clickMenu subpanel records fancymenu button', 'flat' => false), $this->xTemplate); $this->xTemplate->assign('CLASS', "inlineButtons"); $this->xTemplate->assign('CELL_COUNT', ++$count); //Bug#51275 for beta3 pre_script is not required any more $this->xTemplate->assign('CELL', $action_button); $this->xTemplate->parse($xtemplateSection . ".row.cell"); } $aItem->setupCustomFields($aItem->module_dir); $aItem->custom_fields->populateAllXTPL($this->xTemplate, 'detail', $html_varName, $fields); $count++; $this->xTemplate->parse($xtemplateSection . ".row"); } $this->xTemplate->parse($xtemplateSection); }
/** * Do some processing before saving the bean to the database. */ public function pre_save() { if (!empty($_POST['assigned_user_id']) && $_POST['assigned_user_id'] != $this->bean->assigned_user_id && $_POST['assigned_user_id'] != $GLOBALS['current_user']->id && empty($GLOBALS['sugar_config']['exclude_notifications'][$this->bean->module_dir])) { $this->bean->notify_on_save = true; } $GLOBALS['log']->debug("SugarController:: performing pre_save."); require_once 'include/SugarFields/SugarFieldHandler.php'; $sfh = new SugarFieldHandler(); foreach ($this->bean->field_defs as $field => $properties) { $type = !empty($properties['custom_type']) ? $properties['custom_type'] : $properties['type']; $sf = $sfh->getSugarField(ucfirst($type), true); if (isset($_POST[$field])) { if (is_array($_POST[$field]) && !empty($properties['isMultiSelect'])) { if (empty($_POST[$field][0])) { unset($_POST[$field][0]); } $_POST[$field] = encodeMultienumValue($_POST[$field]); } $this->bean->{$field} = $_POST[$field]; } else { if (!empty($properties['isMultiSelect']) && !isset($_POST[$field]) && isset($_POST[$field . '_multiselect'])) { $this->bean->{$field} = ''; } } if ($sf != null) { $sf->save($this->bean, $_POST, $field, $properties); } } foreach ($this->bean->relationship_fields as $field => $link) { if (!empty($_POST[$field])) { $this->bean->{$field} = $_POST[$field]; } } if (!$this->bean->ACLAccess('save')) { ACLController::displayNoAccess(true); sugar_cleanup(true); } $this->bean->unformat_all_fields(); }
/** * Populating bean from $_POST * * @param string $prefix of name of fields * @param SugarBean $focus bean * @param bool $skipRetrieve do not retrieve data of bean * @param bool $checkACL do not update fields if they are forbidden for current user * @return SugarBean */ function populateFromPost($prefix, &$focus, $skipRetrieve = false, $checkACL = false) { global $current_user; if (!empty($_REQUEST[$prefix . 'record']) && !$skipRetrieve) { $focus->retrieve($_REQUEST[$prefix . 'record']); } if (!empty($_POST['assigned_user_id']) && $focus->assigned_user_id != $_POST['assigned_user_id'] && $_POST['assigned_user_id'] != $current_user->id) { $GLOBALS['check_notify'] = true; } require_once 'include/SugarFields/SugarFieldHandler.php'; $sfh = new SugarFieldHandler(); $isOwner = $focus->isOwner($current_user->id); $relatedFields = array(); foreach ($focus->field_defs as $field => $def) { if (empty($def['type']) || $def['type'] != 'relate') { continue; } if (empty($def['source']) || $def['source'] != 'non-db') { continue; } if (empty($def['id_name']) || $def['id_name'] == $field) { continue; } $relatedFields[$def['id_name']] = $field; } foreach ($focus->field_defs as $field => $def) { if ($field == 'id' && !empty($focus->id)) { // Don't try and overwrite the ID continue; } $type = !empty($def['custom_type']) ? $def['custom_type'] : $def['type']; $sf = $sfh->getSugarField($type); if ($sf != null) { $sf->save($focus, $_POST, $field, $def, $prefix); } else { $GLOBALS['log']->fatal("Field '{$field}' does not have a SugarField handler"); } /* if(isset($_POST[$prefix.$field])) { if(is_array($_POST[$prefix.$field]) && !empty($focus->field_defs[$field]['isMultiSelect'])) { if($_POST[$prefix.$field][0] === '' && !empty($_POST[$prefix.$field][1]) ) { unset($_POST[$prefix.$field][0]); } $_POST[$prefix.$field] = encodeMultienumValue($_POST[$prefix.$field]); } $focus->$field = $_POST[$prefix.$field]; /* * overrides the passed value for booleans. * this will be fully deprecated when the change to binary booleans is complete. / if(isset($focus->field_defs[$prefix.$field]) && $focus->field_defs[$prefix.$field]['type'] == 'bool' && isset($focus->field_defs[$prefix.$field]['options'])) { $opts = explode("|", $focus->field_defs[$prefix.$field]['options']); $bool = $_POST[$prefix.$field]; if(is_int($bool) || ($bool === "0" || $bool === "1" || $bool === "2")) { // 1=on, 2=off $selection = ($_POST[$prefix.$field] == "0") ? 1 : 0; } elseif(is_bool($_POST[$prefix.$field])) { // true=on, false=off $selection = ($_POST[$prefix.$field]) ? 0 : 1; } $focus->$field = $opts[$selection]; } } else if(!empty($focus->field_defs[$field]['isMultiSelect']) && !isset($_POST[$prefix.$field]) && isset($_POST[$prefix.$field . '_multiselect'])) { $focus->$field = ''; } */ } foreach ($focus->additional_column_fields as $field) { if (isset($_POST[$prefix . $field])) { $value = $_POST[$prefix . $field]; $focus->{$field} = $value; } } return $focus; }
function bpminbox_get_display_text($temp_module, $field, $field_value, $adv_type = null, $ext1 = null, $context = null) { global $app_list_strings, $current_user; if ($temp_module->field_defs[$field]['type'] == "relate") { //echo $field; //bug 23502, assigned user should be displayed as username here. But I don't know if created user, modified user or even other module should display names instead of ids. if ($temp_module->field_defs[$field]['name'] == 'assigned_user_id' && !empty($field_value) && !empty($context['for_action_display'])) { if ($adv_type != 'exist_user') { return bpminbox_get_username_by_id($field_value); } else { $target_type = "assigned_user_name"; } } else { if (!empty($temp_module->field_defs[$field]['dbType'])) { $target_type = $temp_module->field_defs[$field]['dbType']; } else { return $field_value; } } } elseif (!empty($temp_module->field_defs[$field]['calculated']) && !empty($context['for_action_display'])) { //Cannot set the value of calculated fields. return false; } else { $target_type = $temp_module->field_defs[$field]['type']; } //Land of the "one offs" //This is for meetings and calls, the reminder time if ($temp_module->field_defs[$field]['name'] == "reminder_time") { $target_type = "enum"; $temp_module->field_defs[$field]['options'] = "reminder_time_options"; } if ($target_type == "assigned_user_name") { if ($adv_type == null) { $user_array = get_user_array(true, "Active", $field_value, true); if (!isset($user_array[$field_value])) { return false; } return $user_array[$field_value]; } if ($adv_type == "exist_user") { if ($ext1 == "Manager") { return "Manager of the " . $app_list_strings['wflow_adv_user_type_dom'][$field_value]; } else { return $app_list_strings['wflow_adv_user_type_dom'][$field_value]; } } } if ($adv_type == "datetime") { if (empty($field_value)) { $field_value = 0; } return $app_list_strings['tselect_type_dom'][$field_value] . " from " . $app_list_strings['wflow_action_datetime_type_dom'][$ext1]; } if ($adv_type == "exist_team") { return $app_list_strings['wflow_adv_team_type_dom'][$field_value]; } if ($adv_type == "value_calc") { return "existing value" . $app_list_strings['query_calc_oper_dom'][$ext1] . " by " . $field_value; } if ($adv_type == "enum_step") { return $app_list_strings['wflow_adv_enum_type_dom'][$ext1] . " " . $field_value . " step(s)"; } if ($target_type === 'bool') { $field_value = (bool) $field_value; } require_once 'include/SugarFields/SugarFieldHandler.php'; $sugarField = SugarFieldHandler::getSugarField($target_type); //$GLOBALS['log']->debug("Field: $field is of type $target_type, before: $field_value"); $field_value = $sugarField->getEmailTemplateValue($field_value, $temp_module->field_defs[$field], $context); //$GLOBALS['log']->debug("after: $field_value"); return $field_value; }
/** * getValueFromRequest * This is a helper method to extract a value from the request * Array. We do some special processing for fields that start * with 'date_' by checking to see if they also include time * and meridiem values * * @param request The request Array * @param name The field name to extract value for * @return String value for given name */ function getValueFromRequest($request, $name) { //Special processing for date values (combine to one field) if (preg_match('/^date_(.*)$/s', $name, $matches)) { $d = $request[$name]; if (isset($request['time_' . $matches[1]])) { $d .= ' ' . $request['time_' . $matches[1]]; if (isset($request[$matches[1] . '_meridiem'])) { $d .= $request[$matches[1] . '_meridiem']; } } else { if (isset($request['time_hour_' . $matches[1]]) && isset($request['time_minute_' . $matches[1]])) { $d .= sprintf(' %s:%s', $request['time_hour_' . $matches[1]], $request['time_minute_' . $matches[1]]); } if (isset($request['meridiem'])) { $d .= $request['meridiem']; } } return $d; } if (empty($request[$name]) || !isset($this->fieldDefs[$name])) { return $request[$name]; } //if it's a bean field - unformat it require_once 'include/SugarFields/SugarFieldHandler.php'; $sfh = new SugarFieldHandler(); $type = !empty($this->fieldDefs[$name]['custom_type']) ? $this->fieldDefs[$name]['custom_type'] : $this->fieldDefs[$name]['type']; $sf = $sfh->getSugarField($type); return $sf ? $sf->unformatField($request[$name], $this->fieldDefs[$name]) : $request[$name]; }
} else { $newUser = false; } if (!$current_user->is_admin && !$GLOBALS['current_user']->isAdminForModule('Users')) { if ($current_user->id != $focus->id || !empty($_POST['is_admin']) || !empty($_POST['UserType']) && $_POST['UserType'] == 'Administrator') { $GLOBALS['log']->fatal("SECURITY:Non-Admin " . $current_user->id . " attempted to change settings for user:"******"Location: index.php?module=Users&action=Logout"); exit; } } // Populate the custom fields $sfh = new SugarFieldHandler(); foreach ($focus->field_defs as $fieldName => $field) { if (isset($field['source']) && $field['source'] == 'custom_fields') { $type = !empty($field['custom_type']) ? $field['custom_type'] : $field['type']; $sf = $sfh->getSugarField($type); if ($sf != null) { $sf->save($focus, $_POST, $fieldName, $field, ''); } else { $GLOBALS['log']->fatal("Field '{$fieldName}' does not have a SugarField handler"); } } } $portal = array("user_name", "last_name", "status", "portal_only"); $group = array("user_name", "last_name", "status", "is_group"); if (isset($_POST['portal_only']) && ($_POST['portal_only'] == '1' || $focus->portal_only)) { foreach ($portal as $field) { if (isset($_POST[$field])) { $value = $_POST[$field]; $focus->{$field} = $value; }
/** * generateSearchWhere * * This function serves as the central piece of SearchForm2.php * It is responsible for creating the WHERE clause for a given search operation * * @param bool $add_custom_fields boolean indicating whether or not custom fields should be added * @param string $module Module to search against * * @return string the SQL WHERE clause based on the arguments supplied in SearchForm2 instance */ public function generateSearchWhere($add_custom_fields = false, $module = '') { global $timedate; $db = $this->seed->db; $this->searchColumns = array(); $values = $this->searchFields; $where_clauses = array(); $like_char = '%'; $table_name = $this->seed->object_name; $this->seed->fill_in_additional_detail_fields(); //rrs check for team_id foreach ($this->searchFields as $field => $parms) { $GLOBALS['log']->debug('SearchForm2.generateSearchWhere, field: ' . $field); $GLOBALS['log']->debug('SearchForm2.generateSearchWhere, parms: ' . print_r($parms, TRUE)); $customField = false; // Jenny - Bug 7462: We need a type check here to avoid database errors // when searching for numeric fields. This is a temporary fix until we have // a generic search form validation mechanism. $type = !empty($this->seed->field_name_map[$field]['type']) ? $this->seed->field_name_map[$field]['type'] : ''; $GLOBALS['log']->debug('SearchForm2.generateSearchWhere, type: ' . $type); //If range search is enabled for the field, we first check if this is the starting range if (!empty($parms['enable_range_search']) && empty($type)) { if (preg_match('/^start_range_(.*?)$/', $field, $match)) { $real_field = $match[1]; $start_field = 'start_range_' . $real_field; $end_field = 'end_range_' . $real_field; if (isset($this->searchFields[$start_field]['value']) && isset($this->searchFields[$end_field]['value'])) { $this->searchFields[$real_field]['value'] = $this->searchFields[$start_field]['value'] . '<>' . $this->searchFields[$end_field]['value']; $this->searchFields[$real_field]['operator'] = 'between'; $parms['value'] = $this->searchFields[$real_field]['value']; $parms['operator'] = 'between'; $field_type = isset($this->seed->field_name_map[$real_field]['type']) ? $this->seed->field_name_map[$real_field]['type'] : ''; if ($field_type == 'datetimecombo' || $field_type == 'datetime') { $type = $field_type; } $field = $real_field; unset($this->searchFields[$end_field]['value']); } else { //if both start and end ranges have not been defined, skip this filter. continue; } } else { if (preg_match('/^range_(.*?)$/', $field, $match) && isset($this->searchFields[$field]['value'])) { $real_field = $match[1]; //Special case for datetime and datetimecombo fields. By setting the type here we allow an actual between search if (in_array($parms['operator'], array('=', 'between', "not_equal", 'less_than', 'greater_than', 'less_than_equals', 'greater_than_equals'))) { $field_type = isset($this->seed->field_name_map[$real_field]['type']) ? $this->seed->field_name_map[$real_field]['type'] : ''; if (strtolower($field_type) == 'readonly' && isset($this->seed->field_name_map[$real_field]['dbType'])) { $field_type = $this->seed->field_name_map[$real_field]['dbType']; } if ($field_type == 'datetimecombo' || $field_type == 'datetime' || $field_type == 'int') { $type = $field_type; } } $this->searchFields[$real_field]['value'] = $this->searchFields[$field]['value']; $this->searchFields[$real_field]['operator'] = $this->searchFields[$field]['operator']; $params['value'] = $this->searchFields[$field]['value']; $params['operator'] = $this->searchFields[$field]['operator']; unset($this->searchFields[$field]['value']); $field = $real_field; } else { //Skip this range search field, it is the end field THIS IS NEEDED or the end range date will break the query continue; } } } //Test to mark whether or not the field is a custom field if (!empty($this->seed->field_name_map[$field]['source']) && ($this->seed->field_name_map[$field]['source'] == 'custom_fields' || $this->seed->field_name_map[$field]['source'] == 'non-db' && (!empty($this->seed->field_name_map[$field]['custom_module']) || isset($this->seed->field_name_map[$field]['ext2'])))) { $customField = true; } if ($type == 'int' && isset($parms['value']) && !empty($parms['value'])) { require_once 'include/SugarFields/SugarFieldHandler.php'; $intField = SugarFieldHandler::getSugarField('int'); $newVal = $intField->getSearchWhereValue($parms['value']); $parms['value'] = $newVal; } elseif ($type == 'html' && $customField) { continue; } if (isset($parms['value']) && $parms['value'] != "") { $operator = $db->isNumericType($type) ? '=' : 'like'; if (!empty($parms['operator'])) { $operator = strtolower($parms['operator']); } if (is_array($parms['value'])) { $field_value = ''; // always construct the where clause for multiselects using the 'like' form to handle combinations of multiple $vals and multiple $parms if (!empty($this->seed->field_name_map[$field]['isMultiSelect']) && $this->seed->field_name_map[$field]['isMultiSelect']) { // construct the query for multenums // use the 'like' query as both custom and OOB multienums are implemented with types that cannot be used with an 'in' $operator = 'custom_enum'; $table_name = $this->seed->table_name; if ($customField) { $table_name .= "_cstm"; } $db_field = $table_name . "." . $field; foreach ($parms['value'] as $val) { if ($val != ' ' and $val != '') { $qVal = $db->quote($val); if (!empty($field_value)) { $field_value .= ' or '; } $field_value .= "{$db_field} like '%^{$qVal}^%'"; } else { $field_value .= '(' . $db_field . ' IS NULL or ' . $db_field . "='^^' or " . $db_field . "='')"; } } } else { $operator = $operator != 'subquery' ? 'in' : $operator; $GLOBALS['log']->debug('SearchForm2.generateSearchWhere, value_count: ' . count($parms['value'])); $GLOBALS['log']->debug('SearchForm2.generateSearchWhere, value-0: ' . $parms['value'][0]); if (count($parms['value']) == 1 && empty($parms['value'][0])) { continue; } foreach ($parms['value'] as $val) { if ($val != ' ' and $val != '') { if (!empty($field_value)) { $field_value .= ','; } $field_value .= $db->quoteType($type, $val); } else { if ($operator == 'in') { $operator = 'isnull'; } } } } } else { $field_value = $parms['value']; } //set db_fields array. if (!isset($parms['db_field'])) { $parms['db_field'] = array($field); } //This if-else block handles the shortcut checkbox selections for "My Items" and "Closed Only" if (!empty($parms['my_items'])) { if ($parms['value'] == false) { continue; } else { //my items is checked. global $current_user; $field_value = $db->quote($current_user->id); $operator = '='; } } else { if (!empty($parms['closed_values']) && is_array($parms['closed_values'])) { if ($parms['value'] == false) { continue; } else { $field_value = ''; foreach ($parms['closed_values'] as $closed_value) { $field_value .= "," . $db->quoted($closed_value); } $field_value = substr($field_value, 1); } } } $where = ''; $itr = 0; if ($field_value != '' || $operator == 'isnull') { $this->searchColumns[strtoupper($field)] = $field; foreach ($parms['db_field'] as $db_field) { if (strstr($db_field, '.') === false) { //Try to get the table for relate fields from link defs if ($type == 'relate' && !empty($this->seed->field_name_map[$field]['link']) && !empty($this->seed->field_name_map[$field]['rname'])) { $link = $this->seed->field_name_map[$field]['link']; $relname = $link['relationship']; if ($this->seed->load_relationship($link)) { //Martin fix #27494 $db_field = $this->seed->field_name_map[$field]['name']; } else { //Best Guess for table name $db_field = strtolower($link['module']) . '.' . $db_field; } } else { if ($type == 'parent') { if (!empty($this->searchFields['parent_type'])) { $parentType = $this->searchFields['parent_type']; $rel_module = $parentType['value']; global $beanFiles, $beanList; if (!empty($beanFiles[$beanList[$rel_module]])) { require_once $beanFiles[$beanList[$rel_module]]; $rel_seed = new $beanList[$rel_module](); $db_field = 'parent_' . $rel_module . '_' . $rel_seed->table_name . '.name'; } } } else { if ($type == 'relate' && $customField && !empty($this->seed->field_name_map[$field]['module'])) { $db_field = !empty($this->seed->field_name_map[$field]['name']) ? $this->seed->field_name_map[$field]['name'] : 'name'; } else { if (!$customField) { if (!empty($this->seed->field_name_map[$field]['db_concat_fields'])) { $db_field = $db->concat($this->seed->table_name, $this->seed->field_name_map[$db_field]['db_concat_fields']); } else { $db_field = $this->seed->table_name . "." . $db_field; } } else { if (!empty($this->seed->field_name_map[$field]['db_concat_fields'])) { $db_field = $db->concat($this->seed->table_name . "_cstm.", $this->seed->field_name_map[$db_field]['db_concat_fields']); } else { $db_field = $this->seed->table_name . "_cstm." . $db_field; } } } } } } if ($type == 'date') { // The regular expression check is to circumvent special case YYYY-MM $operator = '='; if (preg_match('/^\\d{4}.\\d{1,2}$/', $field_value) != 0) { // preg_match returns number of matches $db_field = $this->seed->db->convert($db_field, "date_format", array("%Y-%m")); } else { $field_value = $timedate->to_db_date($field_value, false); $db_field = $this->seed->db->convert($db_field, "date_format", array("%Y-%m-%d")); } } if ($type == 'datetime' || $type == 'datetimecombo') { try { if ($operator == '=' || $operator == 'between') { // FG - bug45287 - If User asked for a range, takes edges from it. $placeholderPos = strpos($field_value, "<>"); if ($placeholderPos !== FALSE && $placeholderPos > 0) { $datesLimit = explode("<>", $field_value); $dateStart = $timedate->getDayStartEndGMT($datesLimit[0]); $dateEnd = $timedate->getDayStartEndGMT($datesLimit[1]); $dates = $dateStart; $dates['end'] = $dateEnd['end']; $dates['enddate'] = $dateEnd['enddate']; $dates['endtime'] = $dateEnd['endtime']; } else { $dates = $timedate->getDayStartEndGMT($field_value); } // FG - bug45287 - Note "start" and "end" are the correct interval at GMT timezone $field_value = array($dates["start"], $dates["end"]); $operator = 'between'; } else { if ($operator == 'not_equal') { $dates = $timedate->getDayStartEndGMT($field_value); $field_value = array($dates["start"], $dates["end"]); $operator = 'date_not_equal'; } else { if ($operator == 'greater_than') { $dates = $timedate->getDayStartEndGMT($field_value); $field_value = $dates["end"]; } else { if ($operator == 'less_than') { $dates = $timedate->getDayStartEndGMT($field_value); $field_value = $dates["start"]; } else { if ($operator == 'greater_than_equals') { $dates = $timedate->getDayStartEndGMT($field_value); $field_value = $dates["start"]; } else { if ($operator == 'less_than_equals') { $dates = $timedate->getDayStartEndGMT($field_value); $field_value = $dates["end"]; } } } } } } } catch (Exception $timeException) { //In the event that a date value is given that cannot be correctly processed by getDayStartEndGMT method, //just skip searching on this field and continue. This may occur if user switches locale date formats //in another browser screen, but re-runs a search with the previous format on another screen $GLOBALS['log']->error($timeException->getMessage()); continue; } } if ($type == 'decimal' || $type == 'float' || $type == 'currency' || !empty($parms['enable_range_search']) && empty($parms['is_date_field'])) { require_once 'modules/Currencies/Currency.php'; //we need to handle formatting either a single value or 2 values in case the 'between' search option is set //start by splitting the string if the between operator exists $fieldARR = explode('<>', $field_value); //set the first pass through boolean $values = array(); foreach ($fieldARR as $fv) { //reset the field value, it will be rebuild in the foreach loop below $tmpfield_value = unformat_number($fv); if ($type == 'currency' && stripos($field, '_usdollar') !== FALSE) { // It's a US Dollar field, we need to do some conversions from the user's local currency $currency_id = $GLOBALS['current_user']->getPreference('currency'); if (empty($currency_id)) { $currency_id = -99; } if ($currency_id != -99) { $currency = new Currency(); $currency->retrieve($currency_id); $tmpfield_value = $currency->convertToDollar($tmpfield_value); } } $values[] = $tmpfield_value; } $field_value = join('<>', $values); if (!empty($parms['enable_range_search']) && $parms['operator'] == '=' && $type != 'int') { // Databases can't really search for floating point numbers, because they can't be accurately described in binary, // So we have to fuzz out the math a little bit $field_value = array($field_value - 0.01, $field_value + 0.01); $operator = 'between'; } } if ($db->supports("case_sensitive") && isset($parms['query_type']) && $parms['query_type'] == 'case_insensitive') { $db_field = 'upper(' . $db_field . ")"; $field_value = strtoupper($field_value); } $itr++; if (!empty($where)) { $where .= " OR "; } //Here we make a last attempt to determine the field type if possible if (empty($type) && isset($parms['db_field']) && isset($parms['db_field'][0]) && isset($this->seed->field_defs[$parms['db_field'][0]]['type'])) { $type = $this->seed->field_defs[$parms['db_field'][0]]['type']; } switch (strtolower($operator)) { case 'subquery': $in = 'IN'; if (isset($parms['subquery_in_clause'])) { if (!is_array($parms['subquery_in_clause'])) { $in = $parms['subquery_in_clause']; } elseif (isset($parms['subquery_in_clause'][$field_value])) { $in = $parms['subquery_in_clause'][$field_value]; } } $sq = $parms['subquery']; if (is_array($sq)) { $and_or = ' AND '; if (isset($sq['OR'])) { $and_or = ' OR '; } $first = true; foreach ($sq as $q) { if (empty($q) || strlen($q) < 2) { continue; } if (!$first) { $where .= $and_or; } $where .= " {$db_field} {$in} ({$q} " . $this->seed->db->quoted($field_value . '%') . ") "; $first = false; } } elseif (!empty($parms['query_type']) && $parms['query_type'] == 'format') { $stringFormatParams = array(0 => $field_value, 1 => $GLOBALS['current_user']->id); $where .= "{$db_field} {$in} (" . string_format($parms['subquery'], $stringFormatParams) . ")"; } else { //Bug#37087: Re-write our sub-query to it is executed first and contents stored in a derived table to avoid mysql executing the query //outside in. Additional details: http://bugs.mysql.com/bug.php?id=9021 $selectCol = ' * '; //use the select column in the subquery if it exists if (!empty($parms['subquery'])) { $selectCol = $this->getSelectCol($parms['subquery']); } $where .= "{$db_field} {$in} (select {$selectCol} from ({$parms['subquery']} " . $this->seed->db->quoted($field_value . '%') . ") {$field}_derived)"; } break; case 'like': if ($type == 'bool' && $field_value == 0) { // Bug 43452 - FG - Added parenthesis surrounding the OR (without them the WHERE clause would be broken) $where .= "( " . $db_field . " = '0' OR " . $db_field . " IS NULL )"; } else { // check to see if this is coming from unified search or not $UnifiedSearch = !empty($parms['force_unifiedsearch']); if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'UnifiedSearch') { $UnifiedSearch = true; } // If it is a unified search and if the search contains more then 1 word (contains space) // and if it's the last element from db_field (so we do the concat only once, not for every db_field element) // we concat the db_field array() (both original, and in reverse order) and search for the whole string in it if ($UnifiedSearch && strpos($field_value, ' ') !== false && strpos($db_field, $parms['db_field'][count($parms['db_field']) - 1]) !== false) { // Get the table name used for concat $concat_table = explode('.', $db_field); $concat_table = $concat_table[0]; // Get the fields for concatenating $concat_fields = $parms['db_field']; // If db_fields (e.g. contacts.first_name) contain table name, need to remove it for ($i = 0; $i < count($concat_fields); $i++) { if (strpos($concat_fields[$i], $concat_table) !== false) { $concat_fields[$i] = substr($concat_fields[$i], strlen($concat_table) + 1); } } // Concat the fields and search for the value $where .= $this->seed->db->concat($concat_table, $concat_fields) . " LIKE " . $this->seed->db->quoted($field_value . $like_char); $where .= ' OR ' . $this->seed->db->concat($concat_table, array_reverse($concat_fields)) . " LIKE " . $this->seed->db->quoted($field_value . $like_char); } else { //Check if this is a first_name, last_name search if (isset($this->seed->field_name_map) && isset($this->seed->field_name_map[$db_field])) { $vardefEntry = $this->seed->field_name_map[$db_field]; if (!empty($vardefEntry['db_concat_fields']) && in_array('first_name', $vardefEntry['db_concat_fields']) && in_array('last_name', $vardefEntry['db_concat_fields'])) { if (!empty($GLOBALS['app_list_strings']['salutation_dom']) && is_array($GLOBALS['app_list_strings']['salutation_dom'])) { foreach ($GLOBALS['app_list_strings']['salutation_dom'] as $salutation) { if (!empty($salutation) && strpos($field_value, $salutation) === 0) { $field_value = trim(substr($field_value, strlen($salutation))); break; } } } } } //field is not last name or this is not from global unified search, so do normal where clause $where .= $db_field . " like " . $this->seed->db->quoted(sql_like_string($field_value, $like_char)); } } break; case 'not in': $where .= $db_field . ' not in (' . $field_value . ')'; break; case 'in': $where .= $db_field . ' in (' . $field_value . ')'; break; case '=': if ($type == 'bool' && $field_value == 0) { $where .= "({$db_field} = 0 OR {$db_field} IS NULL)"; } else { $where .= $db_field . " = " . $db->quoteType($type, $field_value); } break; // tyoung bug 15971 - need to add these special cases into the $where query // tyoung bug 15971 - need to add these special cases into the $where query case 'custom_enum': $where .= $field_value; break; case 'between': if (!is_array($field_value)) { $field_value = explode('<>', $field_value); } $field_value[0] = $db->quoteType($type, $field_value[0]); $field_value[1] = $db->quoteType($type, $field_value[1]); $where .= "({$db_field} >= {$field_value[0]} AND {$db_field} <= {$field_value[1]})"; break; case 'date_not_equal': if (!is_array($field_value)) { $field_value = explode('<>', $field_value); } $field_value[0] = $db->quoteType($type, $field_value[0]); $field_value[1] = $db->quoteType($type, $field_value[1]); $where .= "({$db_field} IS NULL OR {$db_field} < {$field_value[0]} OR {$db_field} > {$field_value[1]})"; break; case 'innerjoin': $this->seed->listview_inner_join[] = $parms['innerjoin'] . " '" . $parms['value'] . "%')"; break; case 'not_equal': $field_value = $db->quoteType($type, $field_value); $where .= "({$db_field} IS NULL OR {$db_field} != {$field_value})"; break; case 'greater_than': $field_value = $db->quoteType($type, $field_value); $where .= "{$db_field} > {$field_value}"; break; case 'greater_than_equals': $field_value = $db->quoteType($type, $field_value); $where .= "{$db_field} >= {$field_value}"; break; case 'less_than': $field_value = $db->quoteType($type, $field_value); $where .= "{$db_field} < {$field_value}"; break; case 'less_than_equals': $field_value = $db->quoteType($type, $field_value); $where .= "{$db_field} <= {$field_value}"; break; case 'next_7_days': case 'last_7_days': case 'last_month': case 'this_month': case 'next_month': case 'last_30_days': case 'next_30_days': case 'this_year': case 'last_year': case 'next_year': if (!empty($field) && !empty($this->seed->field_name_map[$field]['type'])) { $where .= $this->parseDateExpression(strtolower($operator), $db_field, $this->seed->field_name_map[$field]['type']); } else { $where .= $this->parseDateExpression(strtolower($operator), $db_field); } break; case 'isnull': $where .= "({$db_field} IS NULL OR {$db_field} = '')"; if ($field_value != '') { $where .= ' OR ' . $db_field . " in (" . $field_value . ')'; } break; } } } if (!empty($where)) { if ($itr > 1) { array_push($where_clauses, '( ' . $where . ' )'); } else { array_push($where_clauses, $where); } } } } $GLOBALS['log']->debug('SearchForm2.generateSearchWhere, where_clauses: ' . print_r($where_clauses, TRUE)); return $where_clauses; }