public function formatForApi(SugarBean $bean, array $fieldList = array(), array $options = array()) { $db = DBManagerFactory::getInstance(); $query = "SELECT\n jt0.id assigned_user_id,\n jt0.user_name assigned_user_name,\n jt0.first_name assgn_fn,\n jt0.last_name assgn_ln,\n jt1.id kbdoc_approver_id,\n jt1.user_name kbdoc_approver_name,\n jt1.first_name appr_fn,\n jt1.last_name appr_ln,\n kvr.views_number views_number\n FROM\n kbdocuments LEFT JOIN kbdocuments_views_ratings kvr ON kbdocuments.id = kvr.kbdocument_id\n LEFT JOIN users jt0 ON jt0.id = kbdocuments.assigned_user_id AND jt0.deleted = 0\n LEFT JOIN users jt1 ON jt1.id = kbdocuments.kbdoc_approver_id AND jt1.deleted = 0\n WHERE\n kbdocuments.id = {$db->quoted($bean->id)}"; $res = $db->query($query); $addon = $db->fetchRow($res); if (in_array('views_number', $fieldList) && !empty($addon['views_number'])) { $bean->views_number = $addon['views_number']; } // bug 56834 - the api doesn't return kbdoc_approver_name $isKbApprover = in_array('kbdoc_approver_name', $fieldList); if ($isKbApprover && !empty($addon['kbdoc_approver_id'])) { $bean->kbdoc_approver_id = $addon['kbdoc_approver_id']; } //add kbdoc_approver_id if not in fieldList if ($isKbApprover && !in_array('kbdoc_approver_id', $fieldList)) { $fieldList[] = 'kbdoc_approver_id'; } $data = parent::formatForApi($bean, $fieldList, $options); // bug 56834 - manually fill kbdoc_approver_name if in fieldList if ((empty($fieldList) || $isKbApprover) && isset($data['kbdoc_approver_id'])) { $user = BeanFactory::getBean('Users'); $user->populateFromRow(array('id' => $addon['kbdoc_approver_id'], 'first_name' => $addon['appr_fn'], 'last_name' => $addon['appr_ln'])); $data['kbdoc_approver_name'] = Localization::getObject()->formatName($user); } if (in_array('assigned_user_name', $fieldList) && !empty($addon['assigned_user_id'])) { $user = BeanFactory::getBean('Users'); $user->populateFromRow(array('id' => $addon['assigned_user_id'], 'first_name' => $addon['assgn_fn'], 'last_name' => $addon['assgn_ln'])); $data['assigned_user_name'] = Localization::getObject()->formatName($user); } if (empty($fieldList) || in_array('attachment_list', $fieldList)) { $query = "SELECT rev.id rev_id, rev.filename filename, kbrev.id docrev_id FROM kbdocument_revisions kbrev LEFT JOIN document_revisions rev ON (kbrev.document_revision_id = rev.id) WHERE kbrev.kbdocument_id = '" . $bean->id . "' AND kbrev.deleted = 0 AND rev.deleted = 0 AND kbrev.kbcontent_id is NULL"; $ret = $db->query($query, true); $files = array(); while ($row = $db->fetchByAssoc($ret)) { $thisFile = array(); $thisFile['document_revision_id'] = $row['rev_id']; // add some extra meta so we can build the urls on the client $thisFile['id'] = $row['rev_id']; $thisFile['module'] = 'DocumentRevisions'; $thisFile['field_name'] = 'filename'; $thisFile['name'] = $row['filename']; $thisFile['kbdocument_revision_id'] = $row['docrev_id']; $thisFile['uri'] = $this->api->getResourceURI(array('DocumentRevisions', $row['rev_id'], 'file', 'filename')); $files[] = $thisFile; } $data['attachment_list'] = $files; } return $data; }
/** * Initialize Sugar environment */ protected function initSugar() { if ($this->sugar_initialized) { return; } // BR-385 - This fixes the issues around SugarThemeRegistry fatals. The cache needs rebuild on stage-post init of sugar if ($this->current_stage == 'post') { $this->cleanFileCache(); } if (!defined('sugarEntry')) { define('sugarEntry', true); } $this->log("Initializing SugarCRM environment"); global $beanFiles, $beanList, $objectList, $timedate, $moduleList, $modInvisList, $sugar_config, $locale, $sugar_version, $sugar_flavor, $sugar_build, $sugar_db_version, $sugar_timestamp, $db, $locale, $installing, $bwcModules, $app_list_strings, $modules_exempt_from_availability_check; $installing = true; include 'include/entryPoint.php'; $installing = false; $GLOBALS['current_language'] = $this->config['default_language']; if (empty($GLOBALS['current_language'])) { $GLOBALS['current_language'] = 'en_us'; } $GLOBALS['log'] = LoggerManager::getLogger('SugarCRM'); $this->db = $GLOBALS['db'] = DBManagerFactory::getInstance(); //Once we have a DB, we can do a full cache clear if ($this->current_stage == 'post') { $this->cleanCaches(); } SugarApplication::preLoadLanguages(); $timedate = TimeDate::getInstance(); if (empty($locale)) { if (method_exists('Localization', 'getObject')) { $locale = Localization::getObject(); } else { $locale = new Localization(); } } if (!isset($_SERVER['REQUEST_URI'])) { $_SERVER['REQUEST_URI'] = ''; } // Load user $GLOBALS['current_user'] = $this->getUser(); // Prepare DB if ($this->config['dbconfig']['db_type'] == 'mysql') { //Change the db wait_timeout for this session $now_timeout = $this->db->getOne("select @@wait_timeout"); $this->db->query("set wait_timeout=28800"); $now_timeout = $this->db->getOne("select @@wait_timeout"); $this->log("DB timeout set to {$now_timeout}"); } // stop trackers $trackerManager = TrackerManager::getInstance(true); $trackerManager->pause(); $trackerManager->unsetMonitors(); $this->sugar_initialized = true; $this->loadStrings(); $GLOBALS['app_list_strings'] = return_app_list_strings_language($GLOBALS['current_language']); $this->log("Done initializing SugarCRM environment"); }
public function expandField() { $this->checkCustomField(); if (isset($this->def['type']) && $this->def['type'] == 'function') { if (!empty($this->def['function_params'])) { foreach ($this->def['function_params'] as $param) { $this->addToSelect("{$this->table}.{$param}"); } } $this->markNonDb(); return; } if (empty($this->alias) && !empty($this->def['name'])) { $this->alias = $this->def['name']; } if (!empty($this->alias)) { $dbAlias = DBManagerFactory::getInstance()->getValidDBName($this->alias, false, 'alias'); if (strtolower($this->alias) != $dbAlias) { $this->original_alias = $this->alias; $this->alias = $dbAlias; } } if ($this->field == '*') { // remove * $this->moduleName = empty($this->moduleName) ? $this->query->getFromBean()->module_name : $this->moduleName; $bean = BeanFactory::getBean($this->moduleName); foreach ($bean->field_defs as $field => $def) { if (!isset($def['source']) || $def['source'] == 'db' || $def['source'] == 'custom_fields' && $def['type'] != 'relate') { $this->addToSelect("{$this->table}.{$field}"); } } $this->markNonDb(); return; } if ($this->def['type'] == 'fullname') { $nameFields = Localization::getObject()->getNameFormatFields($this->moduleName); foreach ($nameFields as $partOfName) { $alias = !empty($this->alias) ? "{$this->alias}__{$partOfName}" : "{$this->def['name']}__{$partOfName}"; $dbAlias = DBManagerFactory::getInstance()->getValidDBName($alias, false, 'alias'); if ($dbAlias != strtolower($alias)) { $this->addToSelect(array(array("{$this->table}.{$partOfName}", $dbAlias, $alias))); } else { $this->addToSelect(array(array("{$this->table}.{$partOfName}", $alias))); } } $this->markNonDb(); return; } if (!isset($this->def['source']) || $this->def['source'] == 'db') { return; } if (!empty($this->def['fields'])) { // this is a compound field foreach ($this->def['fields'] as $field) { $this->addToSelect("{$this->table}.{$field}"); } } if ($this->def['type'] == 'parent') { $this->query->hasParent($this->field); $this->addToSelect('parent_type'); $this->addToSelect('parent_id'); $this->markNonDb(); } if (isset($this->def['custom_type']) && $this->def['custom_type'] == 'teamset') { $this->addToSelect('team_set_id'); } // Exists only checks if (!empty($this->def['rname_exists'])) { $this->markNonDb(); $this->addToSelectRaw("case when {$this->jta}.{$this->def['rname']} IS NOT NULL then 1 else 0 end", $this->field); return; } if (!empty($this->def['rname']) && !empty($this->jta)) { $field = array("{$this->jta}.{$this->def['rname']}", $this->def['name']); $this->addToSelect(array($field)); $this->markNonDb(); } if (!empty($this->def['rname_link']) && !empty($this->jta)) { $this->field = $this->def['rname_link']; $this->alias = $this->def['name']; } if (!empty($this->def['source']) && $this->def['source'] == 'custom_fields') { $this->table = strstr($this->table, '_cstm') ? $this->table : $this->table . '_cstm'; } }
/** * get_user_array * * This is a helper function to return an Array of users depending on the parameters passed into the function. * This function uses the get_register_value function by default to use a caching layer where supported. * * @param bool $add_blank Boolean value to add a blank entry to the array results, true by default * @param string $status String value indicating the status to filter users by, "Active" by default * @param string $user_id String value to specify a particular user id value (searches the id column of users table), blank by default * @param bool $use_real_name Boolean value indicating whether or not results should include the full name or just user_name, false by default * @param String $user_name_filter String value indicating the user_name filter (searches the user_name column of users table) to optionally search with, blank by default * @param string $portal_filter String query filter for portal users (defaults to searching non-portal users), change to blank if you wish to search for all users including portal users * @param bool $from_cache Boolean value indicating whether or not to use the get_register_value function for caching, true by default * @return array Array of users matching the filter criteria that may be from cache (if similar search was previously run) */ function get_user_array($add_blank = true, $status = "Active", $user_id = '', $use_real_name = false, $user_name_filter = '', $portal_filter = ' AND portal_only=0 ', $from_cache = true) { global $locale, $current_user; if (empty($locale)) { $locale = Localization::getObject(); } $db = DBManagerFactory::getInstance(); // Pre-build query for use as cache key // Including deleted users for now. if (empty($status)) { $query = "SELECT id, first_name, last_name, user_name FROM users "; $where = "1=1" . $portal_filter; } else { $query = "SELECT id, first_name, last_name, user_name FROM users "; $where = "status='{$status}'" . $portal_filter; } $user = BeanFactory::getBean('Users'); $user->addVisibilityFrom($query); $query .= " WHERE {$where} "; $user->addVisibilityWhere($query); if (!empty($user_name_filter)) { $user_name_filter = $db->quote($user_name_filter); $query .= " AND user_name LIKE '{$user_name_filter}%' "; } if (!empty($user_id)) { $query .= " OR id='{$user_id}'"; } //get the user preference for name formatting, to be used in order by $order_by_string = ' user_name ASC '; if (!empty($current_user) && !empty($current_user->id)) { $formatString = $current_user->getPreference('default_locale_name_format'); //create the order by string based on position of first and last name in format string $firstNamePos = strpos($formatString, 'f'); $lastNamePos = strpos($formatString, 'l'); if ($firstNamePos !== false || $lastNamePos !== false) { //its possible for first name to be skipped, check for this if ($firstNamePos === false) { $order_by_string = 'last_name ASC'; } else { $order_by_string = $lastNamePos < $firstNamePos ? "last_name, first_name ASC" : "first_name, last_name ASC"; } } } $query = $query . ' ORDER BY ' . $order_by_string; if ($from_cache) { $key_name = $query . $status . $user_id . $use_real_name . $user_name_filter . $portal_filter; $key_name = md5($key_name); $user_array = get_register_value('user_array', $key_name); } if (empty($user_array)) { $temp_result = array(); $GLOBALS['log']->debug("get_user_array query: {$query}"); $result = $db->query($query, true, "Error filling in user array: "); // Get the id and the name. while ($row = $db->fetchByAssoc($result)) { if ($use_real_name == true || showFullName()) { if (isset($row['last_name'])) { // cn: we will ALWAYS have both first_name and last_name (empty value if blank in db) $temp_result[$row['id']] = $locale->formatName('Users', $row); } else { $temp_result[$row['id']] = $row['user_name']; } } else { $temp_result[$row['id']] = $row['user_name']; } } $user_array = $temp_result; if ($from_cache) { set_register_value('user_array', $key_name, $temp_result); } } if ($add_blank) { $user_array[''] = ''; } return $user_array; }
/** * Checks if a locale name format is part of the default list, if not adds it to the config * @param $name_format string a local name format string such as 's f l' * @return bool true on successful write to config file, false on failure; */ function upgradeLocaleNameFormat($name_format) { global $sugar_config, $sugar_version; $localization = Localization::getObject(); $localeConfigDefaults = $localization->getLocaleConfigDefaults(); $uw_strings = return_module_language($GLOBALS['current_language'], 'UpgradeWizard'); if (empty($sugar_config['name_formats'])) { $sugar_config['name_formats'] = $localeConfigDefaults['name_formats']; if (!rebuildConfigFile($sugar_config, $sugar_version)) { $errors[] = $uw_strings['ERR_UW_CONFIG_WRITE']; } } if (!in_array($name_format, $sugar_config['name_formats'])) { $new_config = sugarArrayMerge($sugar_config['name_formats'], array($name_format => $name_format)); $sugar_config['name_formats'] = $new_config; if (!rebuildConfigFile($sugar_config, $sugar_version)) { $errors[] = $uw_strings['ERR_UW_CONFIG_WRITE']; return false; } } return true; }
protected function importRow($row) { global $sugar_config, $mod_strings, $current_user; $focus = BeanFactory::getBean($this->bean->module_dir); $focus->unPopulateDefaultValues(); $focus->save_from_post = false; $focus->team_id = null; $this->ifs->createdBeans = array(); $this->importSource->resetRowErrorCounter(); $do_save = true; // set the currency for the row, if it has a currency_id in the row if ($this->currencyFieldPosition !== false && !empty($row[$this->currencyFieldPosition])) { $currency_id = $row[$this->currencyFieldPosition]; if (!isset($this->cachedCurrencySymbols[$currency_id])) { /** @var Currency $currency */ $currency = BeanFactory::getBean('Currencies', $currency_id); $this->cachedCurrencySymbols[$currency_id] = $currency->symbol; unset($currency); } $this->ifs->currency_symbol = $this->cachedCurrencySymbols[$currency_id]; $this->ifs->currency_id = $currency_id; } // Collect email addresses, and add them before save $emailAddresses = array('non-primary' => array()); $fields_order = $this->getImportColumnsOrder($focus->getFieldDefinitions()); foreach ($fields_order as $fieldNum) { // loop if this column isn't set if (!isset($this->importColumns[$fieldNum])) { continue; } // get this field's properties $field = $this->importColumns[$fieldNum]; $fieldDef = $focus->getFieldDefinition($field); $fieldTranslated = translate(isset($fieldDef['vname']) ? $fieldDef['vname'] : $fieldDef['name'], $focus->module_dir) . " (" . $fieldDef['name'] . ")"; $defaultRowValue = ''; // Bug 37241 - Don't re-import over a field we already set during the importing of another field if (!empty($focus->{$field})) { continue; } // translate strings global $locale; if (empty($locale)) { $locale = Localization::getObject(); } if (isset($row[$fieldNum])) { $rowValue = strip_tags(trim($row[$fieldNum])); } else { if (isset($this->sugarToExternalSourceFieldMap[$field]) && isset($row[$this->sugarToExternalSourceFieldMap[$field]])) { $rowValue = strip_tags(trim($row[$this->sugarToExternalSourceFieldMap[$field]])); } else { $rowValue = ''; } } // If there is an default value then use it instead if (!empty($_REQUEST[$field])) { $defaultRowValue = $this->populateDefaultMapValue($field, $_REQUEST[$field], $fieldDef); if (!empty($fieldDef['custom_type']) && $fieldDef['custom_type'] == 'teamset' && empty($rowValue)) { require_once 'include/SugarFields/Fields/Teamset/SugarFieldTeamset.php'; $sugar_field = new SugarFieldTeamset('Teamset'); $rowValue = implode(', ', $sugar_field->getTeamsFromRequest($field)); } if (empty($rowValue)) { $rowValue = $defaultRowValue; //reset the default value to empty $defaultRowValue = ''; } } // Bug 22705 - Don't update the First Name or Last Name value if Full Name is set if (in_array($field, array('first_name', 'last_name')) && !empty($focus->full_name)) { continue; } // loop if this value has not been set if (!isset($rowValue)) { continue; } // If the field is required and blank then error out if (array_key_exists($field, $focus->get_import_required_fields()) && empty($rowValue) && $rowValue != '0') { $this->importSource->writeError($mod_strings['LBL_REQUIRED_VALUE'], $fieldTranslated, 'NULL'); $do_save = false; } // Handle the special case 'Sync to Mail Client' if ($focus->object_name == "Contact" && $field == 'sync_contact') { /** * Bug #41194 : if true used as value of sync_contact - add curent user to list to sync */ if (true == $rowValue || 'true' == strtolower($rowValue)) { $focus->sync_contact = $focus->id; } elseif (false == $rowValue || 'false' == strtolower($rowValue)) { $focus->sync_contact = ''; } else { $bad_names = array(); $returnValue = $this->ifs->synctooutlook($rowValue, $fieldDef, $bad_names); // try the default value on fail if (!$returnValue && !empty($defaultRowValue)) { $returnValue = $this->ifs->synctooutlook($defaultRowValue, $fieldDef, $bad_names); } if (!$returnValue) { $this->importSource->writeError($mod_strings['LBL_ERROR_SYNC_USERS'], $fieldTranslated, $bad_names); $do_save = 0; } else { $focus->sync_contact = $returnValue; } } } // Handle email1 and email2 fields ( these don't have the type of email ) if ($field == 'email1' || $field == 'email2') { $returnValue = $this->ifs->email($rowValue, $fieldDef, $focus); // try the default value on fail if (!$returnValue && !empty($defaultRowValue)) { $returnValue = $this->ifs->email($defaultRowValue, $fieldDef); } if ($returnValue === FALSE) { $do_save = 0; $this->importSource->writeError($mod_strings['LBL_ERROR_INVALID_EMAIL'], $fieldTranslated, $rowValue); } else { $rowValue = $returnValue; $address = array('email_address' => $rowValue, 'primary_address' => $field == 'email1', 'invalid_email' => false, 'opt_out' => false); // check for current opt_out and invalid email settings for this email address // if we find any, set them now $emailres = $focus->db->query("SELECT opt_out, invalid_email FROM email_addresses WHERE email_address = '" . $focus->db->quote($rowValue) . "'"); if ($emailrow = $focus->db->fetchByAssoc($emailres)) { $address = array_merge($address, $emailrow); } if ($field === 'email1') { //flip the array so we can use it to get the key # $flippedVals = array_flip($this->importColumns); //if the opt out column is set, then attempt to retrieve the values if (isset($flippedVals['email_opt_out'])) { //if the string for this value has a length, then use it. if (isset($row[$flippedVals['email_opt_out']]) && strlen($row[$flippedVals['email_opt_out']]) > 0) { $address['opt_out'] = $row[$flippedVals['email_opt_out']]; } } //if the invalid email column is set, then attempt to retrieve the values if (isset($flippedVals['invalid_email'])) { //if the string for this value has a length, then use it. if (isset($row[$flippedVals['invalid_email']]) && strlen($row[$flippedVals['invalid_email']]) > 0) { $address['invalid_email'] = $row[$flippedVals['invalid_email']]; } } $emailAddresses['primary'] = $address; } else { $emailAddresses['non-primary'][] = $address; } } } if ($field == 'email_addresses_non_primary') { $nonPrimaryAddresses = $this->handleNonPrimaryEmails($rowValue, $defaultRowValue, $fieldTranslated); $emailAddresses['non-primary'] = array_merge($emailAddresses['non-primary'], $nonPrimaryAddresses); } // Handle splitting Full Name into First and Last Name parts if ($field == 'full_name' && !empty($rowValue)) { $this->ifs->fullname($rowValue, $fieldDef, $focus); } // to maintain 451 compatiblity if (!isset($fieldDef['module']) && $fieldDef['type'] == 'relate') { $fieldDef['module'] = ucfirst($fieldDef['table']); } if (isset($fieldDef['custom_type']) && !empty($fieldDef['custom_type'])) { $fieldDef['type'] = $fieldDef['custom_type']; } // If the field is empty then there is no need to check the data if (!empty($rowValue)) { //Start $rowValue = $this->sanitizeFieldValueByType($rowValue, $fieldDef, $defaultRowValue, $focus, $fieldTranslated); if ($rowValue === FALSE) { /* BUG 51213 - jeff @ neposystems.com */ $do_save = false; continue; } } // if the parent type is in singular form, get the real module name for parent_type if (isset($fieldDef['type']) && $fieldDef['type'] == 'parent_type') { $rowValue = get_module_from_singular($rowValue); } $focus->{$field} = $rowValue; unset($defaultRowValue); } // Now try to validate flex relate fields if (isset($focus->field_defs['parent_name']) && isset($focus->parent_name) && $focus->field_defs['parent_name']['type'] == 'parent') { // populate values from the picker widget if the import file doesn't have them $parent_idField = $focus->field_defs['parent_name']['id_name']; if (empty($focus->{$parent_idField}) && !empty($_REQUEST[$parent_idField])) { $focus->{$parent_idField} = $_REQUEST[$parent_idField]; } $parent_typeField = $focus->field_defs['parent_name']['type_name']; if (empty($focus->{$parent_typeField}) && !empty($_REQUEST[$parent_typeField])) { $focus->{$parent_typeField} = $_REQUEST[$parent_typeField]; } // now validate it $returnValue = $this->ifs->parent($focus->parent_name, $focus->field_defs['parent_name'], $focus, empty($_REQUEST['parent_name'])); if (!$returnValue && !empty($_REQUEST['parent_name'])) { $returnValue = $this->ifs->parent($_REQUEST['parent_name'], $focus->field_defs['parent_name'], $focus); } } // check to see that the indexes being entered are unique. if (isset($_REQUEST['enabled_dupes']) && $_REQUEST['enabled_dupes'] != "") { $toDecode = html_entity_decode($_REQUEST['enabled_dupes'], ENT_QUOTES); $enabled_dupes = json_decode($toDecode); $idc = new ImportDuplicateCheck($focus); if ($idc->isADuplicateRecord($enabled_dupes)) { $this->importSource->markRowAsDuplicate($idc->_dupedFields); $this->_undoCreatedBeans($this->ifs->createdBeans); return; } } else { if (!empty($_REQUEST['enabled_dup_fields'])) { $toDecode = html_entity_decode($_REQUEST['enabled_dup_fields'], ENT_QUOTES); $enabled_dup_fields = json_decode($toDecode); $idc = new ImportDuplicateCheck($focus); if ($idc->isADuplicateRecordByFields($enabled_dup_fields)) { $this->importSource->markRowAsDuplicate($idc->_dupedFields); $this->_undoCreatedBeans($this->ifs->createdBeans); return; } } } // if the id was specified $newRecord = true; if (!empty($focus->id)) { $focus->id = $this->_convertId($focus->id); // check if it already exists $query = "SELECT * FROM {$focus->table_name} WHERE id='" . $focus->db->quote($focus->id) . "'"; $result = $focus->db->query($query) or sugar_die("Error selecting sugarbean: "); $dbrow = $focus->db->fetchByAssoc($result); if (isset($dbrow['id']) && $dbrow['id'] != -1) { // if it exists but was deleted, just remove it if (isset($dbrow['deleted']) && $dbrow['deleted'] == 1 && $this->isUpdateOnly == false) { $this->removeDeletedBean($focus); $focus->new_with_id = true; } else { if (!$this->isUpdateOnly) { $this->importSource->writeError($mod_strings['LBL_ID_EXISTS_ALREADY'], 'ID', $focus->id); $this->_undoCreatedBeans($this->ifs->createdBeans); return; } $clonedBean = $this->cloneExistingBean($focus); if ($clonedBean === FALSE) { $this->importSource->writeError($mod_strings['LBL_RECORD_CANNOT_BE_UPDATED'], 'ID', $focus->id); $this->_undoCreatedBeans($this->ifs->createdBeans); return; } else { $focus = $clonedBean; $newRecord = FALSE; } } } else { $focus->new_with_id = true; } } try { // Update e-mails here, because we're calling retrieve, and it overwrites the emailAddress object if ($focus->hasEmails()) { $this->handleEmailUpdate($focus, $emailAddresses); } } catch (Exception $e) { $this->importSource->writeError($e->getMessage(), $fieldTranslated, $focus->id); $do_save = false; } if ($do_save) { $this->saveImportBean($focus, $newRecord); // Update the created/updated counter $this->importSource->markRowAsImported($newRecord); } else { $this->_undoCreatedBeans($this->ifs->createdBeans); } unset($defaultRowValue); }
unset($_GET['PHPSESSID']); } } LogicHook::initialize()->call_custom_logic('', 'entry_point_variables_setting'); if (!empty($sugar_config['session_dir'])) { session_save_path($sugar_config['session_dir']); } if (class_exists('SessionHandler')) { session_set_save_handler(new SugarSessionHandler()); } $GLOBALS['sugar_version'] = $sugar_version; $GLOBALS['sugar_flavor'] = $sugar_flavor; $GLOBALS['js_version_key'] = get_js_version_key(); SugarApplication::preLoadLanguages(); $timedate = TimeDate::getInstance(); $GLOBALS['timedate'] = $timedate; $db = DBManagerFactory::getInstance(); $db->resetQueryCount(); $locale = Localization::getObject(); // Emails uses the REQUEST_URI later to construct dynamic URLs. // IIS does not pass this field to prevent an error, if it is not set, we will assign it to ''. if (!isset($_SERVER['REQUEST_URI'])) { $_SERVER['REQUEST_URI'] = ''; } $current_user = BeanFactory::getBean('Users'); $current_entity = null; $system_config = Administration::getSettings(); LogicHook::initialize()->call_custom_logic('', 'after_entry_point'); } //// END SETTING DEFAULT VAR VALUES ///////////////////////////////////////////////////////////////////////////////
public function run() { $this->localization = $localization = Localization::getObject(); $localeCoreDefaults = $this->localeCoreDefaults = $localization->getLocaleConfigDefaults(); // check the current system wide default_locale_name_format and add it to the list if it's not there if (empty($this->config['name_formats'])) { $this->upgrader->config['name_formats'] = $localeCoreDefaults['name_formats']; } $currentDefaultLocaleNameFormat = $this->config['default_locale_name_format']; if ($localization->isAllowedNameFormat($currentDefaultLocaleNameFormat)) { $this->upgradeLocaleNameFormat($currentDefaultLocaleNameFormat); } else { $this->upgrader->config['default_locale_name_format'] = $localeCoreDefaults['default_locale_name_format']; //TODO: This doesn't seem to do anything useful?? $localization->createInvalidLocaleNameFormatUpgradeNotice(); } if ($this->toFlavor('pro')) { if (file_exists($cachedfile = sugar_cached('dashlets/dashlets.php'))) { require $cachedfile; } else { if (file_exists('modules/Dashboard/dashlets.php')) { require 'modules/Dashboard/dashlets.php'; } } $upgradeTrackingDashlets = array('TrackerDashlet' => array('file' => 'modules/Trackers/Dashlets/TrackerDashlet/TrackerDashlet.php', 'class' => 'TrackerDashlet', 'meta' => 'modules/Trackers/Dashlets/TrackerDashlet/TrackerDashlet.meta.php', 'module' => 'Trackers'), 'MyModulesUsedChartDashlet' => array('file' => 'modules/Charts/Dashlets/MyModulesUsedChartDashlet/MyModulesUsedChartDashlet.php', 'class' => 'MyModulesUsedChartDashlet', 'meta' => 'modules/Charts/Dashlets/MyModulesUsedChartDashlet/MyModulesUsedChartDashlet.meta.php', 'module' => 'Trackers'), 'MyTeamModulesUsedChartDashlet' => array('file' => 'modules/Charts/Dashlets/MyTeamModulesUsedChartDashlet/MyTeamModulesUsedChartDashlet.php', 'class' => 'MyTeamModulesUsedChartDashlet', 'meta' => 'modules/Charts/Dashlets/MyTeamModulesUsedChartDashlet/MyTeamModulesUsedChartDashlet.meta.php', 'module' => 'Trackers')); } $result = $this->db->query("SELECT id FROM users WHERE " . User::getLicensedUsersWhere()); while ($row = $this->db->fetchByAssoc($result)) { $current_user = BeanFactory::getBean('Users', $row['id']); // get the user's name locale format, check if it's in our list, add it if it's not, keep it as user's default $changed = false; $currentUserNameFormat = $current_user->getPreference('default_locale_name_format'); if ($localization->isAllowedNameFormat($currentUserNameFormat)) { $this->upgradeLocaleNameFormat($currentUserNameFormat); } else { $current_user->setPreference('default_locale_name_format', 's f l', 0, 'global'); $changed = true; } if (!$current_user->getPreference('calendar_publish_key')) { // set publish key if not set already $current_user->setPreference('calendar_publish_key', create_guid()); $changed = true; } // versions of 6.7.4 and earlier show user preferred by default if (version_compare($this->from_version, '6.7.5', '<')) { $current_user->setPreference('currency_show_preferred', true, 0, 'global'); } if ($this->toFlavor('pro')) { //Set the user theme to be 'Sugar' theme since this is run for CE flavor conversions $userTheme = $current_user->getPreference('user_theme', 'global'); //If theme is empty or if theme was set to Classic (Sugar5) or if this is a ce to pro/ent flavor upgrade change to RacerX theme if (empty($userTheme) || $userTheme == 'Sugar5' || $this->from_flavor == 'ce') { $changed = true; $current_user->setPreference('user_theme', 'RacerX', 0, 'global'); } //Set the number of tabs by default to 7 $maxTabs = $current_user->getPreference('max_tabs', 'global'); if (empty($maxTabs)) { $changed = true; $current_user->setPreference('max_tabs', '7', 0, 'global'); } //If preferences have changed, save before proceeding if ($changed) { $current_user->savePreferencesToDB(); } $pages = $current_user->getPreference('pages', 'Home'); if (empty($pages)) { continue; } $changed = false; $empty_dashlets = array(); $dashlets = $current_user->getPreference('dashlets', 'Home'); $dashlets = !empty($dashlets) ? $dashlets : $empty_dashlets; $existingDashlets = array(); foreach ($dashlets as $id => $dashlet) { if (!empty($dashlet['className']) && !is_array($dashlet['className'])) { $existingDashlets[$dashlet['className']] = $dashlet['className']; } } if (ACLController::checkAccess('Trackers', 'view', false, 'Tracker')) { $trackingDashlets = array(); foreach ($upgradeTrackingDashlets as $trackingDashletName => $entry) { if (empty($existingDashlets[$trackingDashletName])) { $trackingDashlets[create_guid()] = array('className' => $trackingDashletName, 'fileLocation' => $entry['file'], 'options' => array()); } } if (empty($trackingDashlets)) { continue; } $trackingColumns = array(); $trackingColumns[0] = array(); $trackingColumns[0]['width'] = '50%'; $trackingColumns[0]['dashlets'] = array(); foreach ($trackingDashlets as $guid => $dashlet) { array_push($trackingColumns[0]['dashlets'], $guid); } //Set the tracker dashlets to user preferences table $dashlets = array_merge($dashlets, $trackingDashlets); $current_user->setPreference('dashlets', $dashlets, 0, 'Home'); //Set the dashlets pages to user preferences table $pageIndex = count($pages); $pages[$pageIndex]['columns'] = $trackingColumns; $pages[$pageIndex]['numColumns'] = '1'; $pages[$pageIndex]['pageTitle'] = $this->mod_strings['LBL_HOME_PAGE_4_NAME']; $current_user->setPreference('pages', $pages, 0, 'Home'); $changed = true; } //if } // we need to force save the changes to disk, otherwise we lose them. if ($changed) { $current_user->savePreferencesToDB(); } } //while if ($this->toFlavor('pro')) { /* * This section checks to see if the Tracker settings for the corresponding versions have been * disabled and the regular tracker (for breadcrumbs) enabled. If so, then it will also disable * the tracking for the regular tracker. Disabling the tracker (for breadcrumbs) will no longer prevent * breadcrumb tracking. It will instead only track visible entries (see trackView() method in SugarView.php). * This has the benefit of reducing the tracking overhead and limiting it to only visible items. * For the CE version, we are checking to see that there are no entries enabled for PRO/ENT versions * we are checking for Tracker sessions, performance and queries. */ if ($this->from_flavor == 'ce') { //Set tracker settings. Disable tracker session, performance and queries $category = 'tracker'; $value = 1; $key = array('Tracker', 'tracker_sessions', 'tracker_perf', 'tracker_queries'); $admin = new Administration(); foreach ($key as $k) { $admin->saveSetting($category, $k, $value); } } else { $query = "select count(name) as total from config where category = 'tracker' and name = 'Tracker'"; $results = $this->db->query($query); if (!empty($results)) { $row = $this->db->fetchByAssoc($results); $total = $row['total']; if ($total > 1) { $this->db->query("DELETE FROM config where category = 'tracker' and name = 'Tracker'"); $this->db->query("INSERT INTO config (category, name, value) VALUES ('tracker', 'Tracker', '1')"); } } } //Write the entries to cache/dashlets/dashlets.php if (file_exists($cachedfile = sugar_cached('dashlets/dashlets.php'))) { require $cachedfile; foreach ($upgradeTrackingDashlets as $id => $entry) { if (!isset($dashletsFiles[$id])) { $dashletsFiles[$id] = $entry; } } write_array_to_file("dashletsFiles", $dashletsFiles, $cachedfile); } //if } }
/** * Method parses vCard and creates a Bean in Sugar from it * * @param $filename - Uploaded vCard file * @param string $module - Module we're importing * @return string - id of the created bean * @throws SugarException if all required fields are not present */ public function importVCard($filename, $module = 'Contacts') { global $current_user; $lines = file($filename); $start = false; $bean = BeanFactory::getBean($module); $bean->assigned_user_id = $current_user->id; $email_suffix = 1; for ($index = 0; $index < sizeof($lines); $index++) { $line = $lines[$index]; // check the encoding and change it if needed $locale = Localization::getObject(); $encoding = false; //detect charset if (preg_match("/CHARSET=([A-Z]+([A-Z0-9]-?)*):/", $line, $matches)) { //found charset hint in vcard $encoding = $matches[1]; } else { //use locale to detect charset automatically $encoding = $locale->detectCharset($line); } if ($encoding !== $GLOBALS['sugar_config']['default_charset']) { $line = $locale->translateCharset($line, $encoding); } $line = trim($line); if ($start) { //VCARD is done if (substr_count(strtoupper($line), 'END:VCARD')) { if (!isset($bean->last_name) && !empty($fullname)) { $bean->last_name = $fullname; } break; } $keyvalue = explode(':', $line); if (sizeof($keyvalue) == 2) { $value = $keyvalue[1]; for ($newindex = $index + 1; $newindex < sizeof($lines), substr_count($lines[$newindex], ':') == 0; $newindex++) { $value .= $lines[$newindex]; $index = $newindex; } $values = explode(';', $value); $size = count($values); $key = strtoupper($keyvalue[0]); $key = strtr($key, '=', ''); $key = strtr($key, ',', ';'); $keys = explode(';', $key); if ($keys[0] == 'TEL') { if (substr_count($key, 'WORK') > 0) { if (substr_count($key, 'FAX') > 0) { if (!isset($bean->phone_fax)) { $bean->phone_fax = $value; } } else { if (!isset($bean->phone_work)) { $bean->phone_work = $value; } } } if (substr_count($key, 'HOME') > 0) { if (substr_count($key, 'FAX') > 0) { if (!isset($bean->phone_fax)) { $bean->phone_fax = $value; } } else { if (!isset($bean->phone_home)) { $bean->phone_home = $value; } } } if (substr_count($key, 'CELL') > 0) { if (!isset($bean->phone_mobile)) { $bean->phone_mobile = $value; } } if (substr_count($key, 'FAX') > 0) { if (!isset($bean->phone_fax)) { $bean->phone_fax = $value; } } } if ($keys[0] == 'N') { if ($size > 0) { $bean->last_name = $values[0]; } if ($size > 1) { $bean->first_name = $values[1]; } if ($size > 3) { $bean->salutation = $values[3]; } } if ($keys[0] == 'FN') { $fullname = $value; } } if ($keys[0] == 'ADR') { if (substr_count($key, 'WORK') > 0 && (substr_count($key, 'POSTAL') > 0 || substr_count($key, 'PARCEL') == 0)) { if (!isset($bean->primary_address_street) && $size > 2) { $textBreaks = array("\n", "\r"); $vcardBreaks = array("=0A", "=0D"); $bean->primary_address_street = str_replace($vcardBreaks, $textBreaks, $values[2]); } if (!isset($bean->primary_address_city) && $size > 3) { $bean->primary_address_city = $values[3]; } if (!isset($bean->primary_address_state) && $size > 4) { $bean->primary_address_state = $values[4]; } if (!isset($bean->primary_address_postalcode) && $size > 5) { $bean->primary_address_postalcode = $values[5]; } if (!isset($bean->primary_address_country) && $size > 6) { $bean->primary_address_country = $values[6]; } } } if ($keys[0] == 'TITLE') { $bean->title = $value; } if ($keys[0] == 'EMAIL') { $field = 'email' . $email_suffix; if (!isset($bean->{$field})) { $bean->{$field} = $value; } if ($email_suffix == 1) { $_REQUEST['email1'] = $value; } $email_suffix++; } if ($keys[0] == 'ORG') { if (!empty($value)) { if ($bean instanceof Contact || $bean instanceof Lead) { $accountBean = BeanFactory::getBean('Accounts'); // It's a contact, we better try and match up an account $full_company_name = trim($values[0]); // Do we have a full company name match? $result = $accountBean->retrieve_by_string_fields(array('name' => $full_company_name, 'deleted' => 0)); if (!isset($result->id)) { // Try to trim the full company name down, see if we get some other matches $vCardTrimStrings = array('/ltd\\.*/i' => '', '/llc\\.*/i' => '', '/gmbh\\.*/i' => '', '/inc\\.*/i' => '', '/\\.com/i' => ''); // Allow users to override the trimming strings if (SugarAutoLoader::existing('custom/include/vCardTrimStrings.php')) { include 'custom/include/vCardTrimStrings.php'; } $short_company_name = trim(preg_replace(array_keys($vCardTrimStrings), $vCardTrimStrings, $full_company_name), " ,."); $result = $accountBean->retrieve_by_string_fields(array('name' => $short_company_name, 'deleted' => 0)); } if ($bean instanceof Lead || !isset($result->id)) { // We could not find a parent account, or this is a lead so only copy the name, no linking $bean->account_id = ''; $bean->account_name = $full_company_name; } else { $bean->account_id = $result->id; $bean->account_name = $result->name; } if ($size > 1) { $bean->department = $values[1]; } } else { $bean->department = $value; } } } } //FOUND THE BEGINING OF THE VCARD if (!$start && substr_count(strtoupper($line), 'BEGIN:VCARD')) { $start = true; } } foreach ($bean->get_import_required_fields() as $key => $value) { if (empty($bean->{$key})) { throw new SugarException('LBL_EMPTY_REQUIRED_VCARD'); } } if ($bean instanceof Contact && empty($bean->account_id) && !empty($bean->account_name)) { // We need to create a new account $accountBean = BeanFactory::getBean('Accounts'); // Populate the newly created account with all of the contact information foreach ($bean->field_defs as $field_name => $field_def) { if (!empty($bean->{$field_name})) { $accountBean->{$field_name} = $bean->{$field_name}; } } $accountBean->name = $bean->account_name; $accountBean->save(); $bean->account_id = $accountBean->id; } $beanId = $bean->save(); return $beanId; }