/** * sends POST request to REST service via CURL * @param string $url URL to call * @param string $postArgs POST args */ public function callRest($url, $postArgs) { if (!function_exists("curl_init")) { $this->last_error = 'ERROR_NO_CURL'; Log::fatal("REST call failed - no cURL!"); return false; } $curl = curl_init($url); curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_HEADER, false); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_POSTFIELDS, $postArgs); curl_setopt($curl, CURLOPT_TIMEOUT, 10); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); Log::debug("HTTP client call: {$url} -> {$postArgs}"); $response = curl_exec($curl); if ($response === false) { $this->last_error = 'ERROR_REQUEST_FAILED'; $curl_errno = curl_errno($curl); $curl_error = curl_error($curl); Log::error("HTTP client: cURL call failed: error {$curl_errno}: {$curl_error}"); return false; } Log::debug("HTTP client response: {$response}"); curl_close($curl); return $response; }
public static function sendmail($toList, $subject, $content) { $mail = new \PHPMailer(); $mail->isSMTP(); $mail->Host = self::SMTP_HOST; $mail->SMTPAuth = true; $mail->Username = self::SMTP_USER; $mail->Password = self::SMTP_PASSWD; $mail->SMTPSecure = self::SMTP_SECURE; $mail->Port = self::SMTP_PORT; $mail->Timeout = 3; // seconds $mail->From = self::MAIL_FROM; $mail->CharSet = 'utf-8'; $mail->FromName = 'xxx'; // TODO foreach ($toList as $to) { $mail->addAddress($to); } //$mail->isHTML(true); $mail->Subject = $subject; $mail->Body = $content; $mail->AltBody = $content; if (!$mail->send()) { Log::fatal('mailer error: ' . $mail->ErrorInfo); return false; } return true; }
function tableColumns($table_name) { Log::fatal('********TABLE PASSED******* ' . $table_name); global $sugar_config; global $setup_db_database_name; global $setup_db_host_name; global $setup_db_host_instance; global $setup_db_admin_user_name; global $setup_db_admin_password; //$db = &DBManagerFactory::getInstance('information_schema'); $db_name = $sugar_config['dbconfig']['db_name']; $setup_db_host_name = $sugar_config['dbconfig']['db_host_name']; $setup_db_admin_user_name = $sugar_config['dbconfig']['db_user_name']; $setup_db_host_instance = $sugar_config['dbconfig']['db_host_instance']; $setup_db_admin_password = $sugar_config['dbconfig']['db_password']; $link = @mysql_connect($setup_db_host_name, $setup_db_admin_user_name, $setup_db_admin_password); mysql_select_db('information_schema'); $qu = "SELECT column_name FROM information_schema.columns WHERE table_schema = '" . $db_name . "' AND table_name = '" . $table_name . "'"; $ct = mysql_query($qu, $link); //$cols= ''; $colsDrop = array(); while ($row = mysql_fetch_assoc($ct)) { $colsDrop[] = $row['column_name']; } return $colsDrop; }
public function getController() { if ($this->controller == null) { Log::fatal('Not found the controller: [%s]', var_export($this->controller, 1)); trigger_error('Not found the controller: [' . var_export($this->controller, 1) . ']', E_USER_ERROR); } return $this->controller; }
public function LogAction() { Log::fatal('something'); Log::warn('something'); Log::notice('something'); Log::debug('something'); Log::sql('something'); echo '请到Log文件夹查看效果。如果是SAE环境,可以在日志中心的DEBUG日志查看。'; }
public function display() { if (!isset($this->view_object_map['jsonData']) || !is_array($this->view_object_map['jsonData'])) { Log::fatal("JSON data has not been passed from Calendar controller"); sugar_cleanup(true); } $jsonData = $this->view_object_map['jsonData']; ob_clean(); echo json_encode($jsonData); }
public static function load($class) { if (!in_array($class, self::$valid)) { Log::fatal('Not a valid class. class:[%s]', var_export($class, 1)); trigger_error('Not a valid class. class:[' . var_export($class, 1) . ']', E_USER_ERROR); } if (empty(self::$loaded[$class])) { self::$loaded[$class] = new $class(); } return self::$loaded[$class]; }
/** * 终止程序运行 * @param string $str 终止原因 * @param bool $display 是否显示调用栈,默认不显示 * @return void */ function halt($str, $display = false) { Log::fatal($str . ' debug_backtrace:' . var_export(debug_backtrace(), true)); header("Content-Type:text/html; charset=utf-8"); if ($display) { echo "<pre>"; debug_print_backtrace(); echo "</pre>"; } echo $str; exit; }
public function process() { if ($this->field_data['tmp_name'] !== '') { $destination = BASE_PATH . '/' . $this->settings['destination']; $filename = File::cleanFilename($this->field_data['name']); if (File::upload($this->field_data['tmp_name'], $destination, $filename)) { return Path::tidy('/' . $this->settings['destination'] . '/' . $filename); } else { Log::fatal($this->field_data['tmp_name'] . ' could up not be uploaded to ' . $destination, 'core'); return ''; } } }
/** * Loads the structure cache into the local structure variable if not done yet * * @return void * @throws Exception */ public static function loadStructure() { if (self::$structure_loaded) { return; } self::$structure_loaded = true; self::$structure = unserialize(File::get(Path::tidy(BASE_PATH . "/_cache/_app/content/structure.php"))); if (!is_array(self::$structure)) { // something has gone wrong, log a message and set to an empty array self::$cache = array(); Log::fatal('Could not find or access your cache. Try checking your file permissions.', 'core', 'ContentService'); throw new Exception('Could not find or access your cache. Try checking your file permissions.'); } }
public static function dispatch(Router $router) { // ob_start(); $className = ucfirst($router->getController()) . 'Controller'; $actionName = $router->getAction() . 'Action'; $controllerFile = CONTROLLER_DIR . '/' . $className . '.class.php'; if (file_exists($controllerFile)) { include_once $controllerFile; $app = new $className($router->getParams(), $router->getController()); $app->{$actionName}(); // $output = ob_get_clean(); // echo $output; } else { // throw new Exception('Controller not found. className:['.$className.']'); Log::fatal('Controller not found. className:[%s]', var_export($className, 1)); trigger_error('Controller not found. className:[' . var_export($className, 1) . ']', E_USER_ERROR); } }
/** * One2MRelationship constructor. * * @param array $def */ public function __construct($def) { global $dictionary; $this->def = $def; $this->name = $def['name']; $this->selfReferencing = $def['lhs_module'] == $def['rhs_module']; $lhsModule = $def['lhs_module']; $rhsModule = $def['rhs_module']; if ($this->selfReferencing) { $links = VardefManager::getLinkFieldForRelationship($lhsModule, BeanFactory::getObjectName($lhsModule), $this->name); if (empty($links)) { Log::fatal("No Links found for relationship {$this->name}"); } else { if (!is_array($links)) { //Only one link for a self referencing relationship, this is very bad. $this->lhsLinkDef = $this->rhsLinkDef = $links; } else { if (!empty($links[0]) && !empty($links[1])) { if (!empty($links[0]['side']) && $links[0]['side'] == "right" || !empty($links[0]['link_type']) && $links[0]['link_type'] == "one") { //$links[0] is the RHS $this->lhsLinkDef = $links[1]; $this->rhsLinkDef = $links[0]; } else { //$links[0] is the LHS $this->lhsLinkDef = $links[0]; $this->rhsLinkDef = $links[1]; } } } } } else { $this->lhsLinkDef = VardefManager::getLinkFieldForRelationship($lhsModule, BeanFactory::getObjectName($lhsModule), $this->name); $this->rhsLinkDef = VardefManager::getLinkFieldForRelationship($rhsModule, BeanFactory::getObjectName($rhsModule), $this->name); if (!isset($this->lhsLinkDef['name']) && isset($this->lhsLinkDef[0])) { $this->lhsLinkDef = $this->lhsLinkDef[0]; } if (!isset($this->rhsLinkDef['name']) && isset($this->rhsLinkDef[0])) { $this->rhsLinkDef = $this->rhsLinkDef[0]; } } $this->lhsLink = $this->lhsLinkDef['name']; $this->rhsLink = $this->rhsLinkDef['name']; }
function display($name, $xmlFile, $width = '320', $height = '480', $resize = false) { $this->chartId = $name; $this->height = $height; $this->width = $width; $this->xmlFile = $xmlFile; $this->chartType = $this->chart_properties['type']; $style = array(); $chartConfig = array(); try { $xmlStr = $this->processXML($this->xmlFile); $json = $this->buildJson($xmlStr); } catch (Exception $e) { Log::fatal("Unable to return chart data, invalid xml for file {$this->xmlFile}"); return ''; } $this->saveJsonFile($json); $this->ss->assign("chartId", $this->chartId); $this->ss->assign("filename", $this->jsonFilename); global $mod_strings, $app_strings; if (isset($mod_strings['LBL_REPORT_SHOW_CHART'])) { $this->ss->assign("showchart", $mod_strings['LBL_REPORT_SHOW_CHART']); } $dimensions = $this->getChartDimensions($xmlStr); $this->ss->assign("width", $dimensions['width']); $this->ss->assign("height", $dimensions['height']); $config = $this->getConfigProperties(); $style['gridLineColor'] = str_replace("0x", "#", $config->gridLines); $style['font-family'] = $config->labelFontFamily; $style['color'] = str_replace("0x", "#", $config->labelFontColor); $this->ss->assign("css", $style); foreach ($this->getChartConfigParams($xmlStr) as $key => $value) { $chartConfig[$key] = $value; } $chartConfig['imageExportType'] = $this->image_export_type; $this->ss->assign("config", $chartConfig); if ($json == "No Data") { $this->ss->assign("error", $app_strings['LBL_NO_DATA']); } if (!$this->isSupported($this->chartType)) { $this->ss->assign("error", "Unsupported Chart Type"); } }
/** * this is called when a user logs in * * @param STRING $name * @param STRING $password * @return boolean */ function loadUserOnLogin($name, $password) { global $login_error; Log::debug("Starting user load for " . $name); if (empty($name) || empty($password)) { return false; } if (empty($_SESSION['lastUserId'])) { $input_hash = SugarAuthenticate::encodePassword($password); $user_id = $this->authenticateUser($name, $input_hash); if (empty($user_id)) { Log::fatal('SECURITY: User authentication for ' . $name . ' failed'); return false; } } if (empty($_SESSION['emailAuthToken'])) { $_SESSION['lastUserId'] = $user_id; $_SESSION['lastUserName'] = $name; $_SESSION['emailAuthToken'] = ''; for ($i = 0; $i < $this->passwordLength; $i++) { $_SESSION['emailAuthToken'] .= chr(mt_rand(48, 90)); } $_SESSION['emailAuthToken'] = str_replace(array('<', '>'), array('#', '@'), $_SESSION['emailAuthToken']); $_SESSION['login_error'] = 'Please Enter Your User Name and Emailed Session Token'; $this->sendEmailPassword($user_id, $_SESSION['emailAuthToken']); return false; } else { if (strcmp($name, $_SESSION['lastUserName']) == 0 && strcmp($password, $_SESSION['emailAuthToken']) == 0) { $this->loadUserOnSession($_SESSION['lastUserId']); unset($_SESSION['lastUserId']); unset($_SESSION['lastUserName']); unset($_SESSION['emailAuthToken']); return true; } } $_SESSION['login_error'] = 'Please Enter Your User Name and Emailed Session Token'; return false; }
function checkTempImage($path) { if (!verify_uploaded_image($path)) { $error = translate('LBL_ALERT_TYPE_IMAGE'); Log::fatal("A user ({$GLOBALS['current_user']->id}) attempted to use an invalid file for the logo - {$path}"); $this->error = $error; return false; } return $path; }
/** * Job 1 */ function pollMonitoredInboxes() { $_bck_up = array('team_id' => $GLOBALS['current_user']->team_id, 'team_set_id' => $GLOBALS['current_user']->team_set_id); Log::info('----->Scheduler fired job of type pollMonitoredInboxes()'); global $dictionary; global $app_strings; require_once 'modules/Emails/EmailUI.php'; $ie = new InboundEmail(); $emailUI = new EmailUI(); $r = $ie->db->query('SELECT id, name FROM inbound_email WHERE is_personal = 0 AND deleted=0 AND status=\'Active\' AND mailbox_type != \'bounce\''); Log::debug('Just got Result from get all Inbounds of Inbound Emails'); while ($a = $ie->db->fetchByAssoc($r)) { Log::debug('In while loop of Inbound Emails'); $ieX = new InboundEmail(); $ieX->retrieve($a['id']); $GLOBALS['current_user']->team_id = $ieX->team_id; $GLOBALS['current_user']->team_set_id = $ieX->team_set_id; $mailboxes = $ieX->mailboxarray; foreach ($mailboxes as $mbox) { $ieX->mailbox = $mbox; $newMsgs = array(); $msgNoToUIDL = array(); $connectToMailServer = false; if ($ieX->isPop3Protocol()) { $msgNoToUIDL = $ieX->getPop3NewMessagesToDownloadForCron(); // get all the keys which are msgnos; $newMsgs = array_keys($msgNoToUIDL); } if ($ieX->connectMailserver() == 'true') { $connectToMailServer = true; } // if Log::debug('Trying to connect to mailserver for [ ' . $a['name'] . ' ]'); if ($connectToMailServer) { Log::debug('Connected to mailserver'); if (!$ieX->isPop3Protocol()) { $newMsgs = $ieX->getNewMessageIds(); } if (is_array($newMsgs)) { $current = 1; $total = count($newMsgs); require_once "include/SugarFolders/SugarFolders.php"; $sugarFolder = new SugarFolder(); $groupFolderId = $ieX->groupfolder_id; $isGroupFolderExists = false; $users = array(); if ($groupFolderId != null && $groupFolderId != "") { $sugarFolder->retrieve($groupFolderId); $isGroupFolderExists = true; } // if $messagesToDelete = array(); if ($ieX->isMailBoxTypeCreateCase()) { $users[] = $sugarFolder->assign_to_id; $distributionMethod = $ieX->get_stored_options("distrib_method", ""); if ($distributionMethod != 'roundRobin') { $counts = $emailUI->getAssignedEmailsCountForUsers($users); } else { $lastRobin = $emailUI->getLastRobin($ieX); } Log::debug('distribution method id [ ' . $distributionMethod . ' ]'); } foreach ($newMsgs as $k => $msgNo) { $uid = $msgNo; if ($ieX->isPop3Protocol()) { $uid = $msgNoToUIDL[$msgNo]; } else { $uid = imap_uid($ieX->conn, $msgNo); } // else if ($isGroupFolderExists) { if ($ieX->importOneEmail($msgNo, $uid)) { // add to folder $sugarFolder->addBean($ieX->email); if ($ieX->isPop3Protocol()) { $messagesToDelete[] = $msgNo; } else { $messagesToDelete[] = $uid; } if ($ieX->isMailBoxTypeCreateCase()) { $userId = ""; if ($distributionMethod == 'roundRobin') { if (sizeof($users) == 1) { $userId = $users[0]; $lastRobin = $users[0]; } else { $userIdsKeys = array_flip($users); // now keys are values $thisRobinKey = $userIdsKeys[$lastRobin] + 1; if (!empty($users[$thisRobinKey])) { $userId = $users[$thisRobinKey]; $lastRobin = $users[$thisRobinKey]; } else { $userId = $users[0]; $lastRobin = $users[0]; } } // else } else { if (sizeof($users) == 1) { foreach ($users as $k => $value) { $userId = $value; } // foreach } else { asort($counts); // lowest to highest $countsKeys = array_flip($counts); // keys now the 'count of items' $leastBusy = array_shift($countsKeys); // user id of lowest item count $userId = $leastBusy; $counts[$leastBusy] = $counts[$leastBusy] + 1; } } // else Log::debug('userId [ ' . $userId . ' ]'); $ieX->handleCreateCase($ieX->email, $userId); } // if } // if } else { if ($ieX->isAutoImport()) { $ieX->importOneEmail($msgNo, $uid); } else { /*If the group folder doesn't exist then download only those messages which has caseid in message*/ $ieX->getMessagesInEmailCache($msgNo, $uid); $email = new Email(); $header = imap_headerinfo($ieX->conn, $msgNo); $email->name = $ieX->handleMimeHeaderDecode($header->subject); $email->from_addr = $ieX->convertImapToSugarEmailAddress($header->from); $email->reply_to_email = $ieX->convertImapToSugarEmailAddress($header->reply_to); if (!empty($email->reply_to_email)) { $contactAddr = $email->reply_to_email; } else { $contactAddr = $email->from_addr; } $mailBoxType = $ieX->mailbox_type; $ieX->handleAutoresponse($email, $contactAddr); } // else } // else Log::debug('***** On message [ ' . $current . ' of ' . $total . ' ] *****'); $current++; } // foreach // update Inbound Account with last robin if ($ieX->isMailBoxTypeCreateCase() && $distributionMethod == 'roundRobin') { $emailUI->setLastRobin($ieX, $lastRobin); } // if } // if if ($isGroupFolderExists) { $leaveMessagesOnMailServer = $ieX->get_stored_options("leaveMessagesOnMailServer", 0); if (!$leaveMessagesOnMailServer) { if ($ieX->isPop3Protocol()) { $ieX->deleteMessageOnMailServerForPop3(implode(",", $messagesToDelete)); } else { $ieX->deleteMessageOnMailServer(implode($app_strings['LBL_EMAIL_DELIMITER'], $messagesToDelete)); } } } } else { Log::fatal("SCHEDULERS: could not get an IMAP connection resource for ID [ {$a['id']} ]. Skipping mailbox [ {$a['name']} ]."); // cn: bug 9171 - continue while } // else } // foreach imap_expunge($ieX->conn); imap_close($ieX->conn, CL_EXPUNGE); } // while $GLOBALS['current_user']->team_id = $_bck_up['team_id']; $GLOBALS['current_user']->team_set_id = $_bck_up['team_set_id']; return true; }
function display($showContainer = true, $forceTabless = false) { global $layout_edit_mode, $sugar_version, $sugar_config, $current_user, $app_strings; if (isset($layout_edit_mode) && $layout_edit_mode) { return; } global $modListHeader; ob_start(); echo '<script type="text/javascript" src="' . getJSPath('include/SubPanel/SubPanelTiles.js') . '"></script>'; ?> <script> if(document.DetailView != null && document.DetailView.elements != null && document.DetailView.elements.layout_def_key != null && typeof document.DetailView.elements['layout_def_key'] != 'undefined'){ document.DetailView.elements['layout_def_key'].value = '<?php echo $this->layout_def_key; ?> '; } </script> <?php $tabs = array(); $default_div_display = 'inline'; if (!empty($sugar_config['hide_subpanels_on_login'])) { if (!isset($_SESSION['visited_details'][$this->focus->module_dir])) { setcookie($this->focus->module_dir . '_divs', ''); unset($_COOKIE[$this->focus->module_dir . '_divs']); $_SESSION['visited_details'][$this->focus->module_dir] = true; } $default_div_display = 'none'; } $div_cookies = get_sub_cookies($this->focus->module_dir . '_divs'); //Display the group header. this section is executed only if the tabbed interface is being used. $current_key = ''; if (!empty($this->show_tabs)) { require_once 'include/tabs.php'; $tab_panel = new SugarWidgetTabs($tabs, $current_key, 'showSubPanel'); echo get_form_header('Related', '', false); echo "<br />" . $tab_panel->display(); } if (empty($_REQUEST['subpanels'])) { $selected_group = $forceTabless ? '' : $this->getSelectedGroup(); $usersLayout = $current_user->getPreference('subpanelLayout', $this->focus->module_dir); // we need to use some intelligence here when restoring the user's layout, as new modules with new subpanels might have been installed since the user's layout was recorded // this means that we can't just restore the old layout verbatim as the new subpanels would then go walkabout // so we need to do a merge while attempting as best we can to preserve the sense of the specified order // this is complicated by the different ordering schemes used in the two sources for the panels: the user's layout uses an ordinal layout, the panels from getTabs have an explicit ordering driven by the 'order' parameter // it's not clear how to best reconcile these two schemes; so we punt on it, and add all new panels to the end of the user's layout. At least this will give them a clue that something has changed... // we also now check for tabs that have been removed since the user saved his or her preferences. $tabs = $this->getTabs($showContainer, $selected_group); if (!empty($usersLayout)) { $availableTabs = $tabs; $tabs = array_intersect($usersLayout, $availableTabs); // remove any tabs that have been removed since the user's layout was saved foreach (array_diff($availableTabs, $usersLayout) as $tab) { $tabs[] = $tab; } } } else { $tabs = explode(',', $_REQUEST['subpanels']); } $tab_names = array(); if ($showContainer) { echo '<ul class="noBullet" id="subpanel_list">'; } //echo "<li id='hidden_0' style='height: 5px' class='noBullet'> </li>"; if (empty($GLOBALS['relationships'])) { if (!class_exists('Relationship')) { require 'modules/Relationships/Relationship.php'; } $rel = new Relationship(); $rel->load_relationship_meta(); } // this array will store names of sub-panels that can contain items // of each module $module_sub_panels = array(); foreach ($tabs as $tab) { //load meta definition of the sub-panel. $thisPanel = $this->subpanel_definitions->load_subpanel($tab); if ($thisPanel === false) { continue; } //this if-block will try to skip over ophaned subpanels. Studio/MB are being delete unloaded modules completely. //this check will ignore subpanels that are collections (activities, history, etc) if (!isset($thisPanel->_instance_properties['collection_list']) and isset($thisPanel->_instance_properties['get_subpanel_data'])) { //ignore when data source is a function if (!isset($this->focus->field_defs[$thisPanel->_instance_properties['get_subpanel_data']])) { if (stripos($thisPanel->_instance_properties['get_subpanel_data'], 'function:') === false) { Log::fatal("Bad subpanel definition, it has incorrect value for get_subpanel_data property " . $tab); continue; } } else { $rel_name = ''; if (isset($this->focus->field_defs[$thisPanel->_instance_properties['get_subpanel_data']]['relationship'])) { $rel_name = $this->focus->field_defs[$thisPanel->_instance_properties['get_subpanel_data']]['relationship']; } if (empty($rel_name) or !isset($GLOBALS['relationships'][$rel_name])) { Log::fatal("Missing relationship definition " . $rel_name . ". skipping " . $tab . " subpanel"); continue; } } } if ($thisPanel->isCollection()) { // collect names of sub-panels that may contain items of each module $collection_list = $thisPanel->get_inst_prop_value('collection_list'); if (is_array($collection_list)) { foreach ($collection_list as $data) { if (!empty($data['module'])) { $module_sub_panels[$data['module']][$tab] = true; } } } } else { $module = $thisPanel->get_module_name(); if (!empty($module)) { $module_sub_panels[$module][$tab] = true; } } echo '<li class="noBullet" id="whole_subpanel_' . $tab . '">'; $display = 'none'; $div_display = $default_div_display; $cookie_name = $tab . '_v'; if (isset($thisPanel->_instance_properties['collapsed']) && $thisPanel->_instance_properties['collapsed']) { $div_display = 'none'; } if (isset($div_cookies[$cookie_name])) { //If defaultSubPanelExpandCollapse is set, ignore the cookie that remembers whether the panel is expanded or collapsed. //To be used with the above 'collapsed' metadata setting so they will always be set the same when the page is loaded. if (!isset($sugar_config['defaultSubPanelExpandCollapse']) || $sugar_config['defaultSubPanelExpandCollapse'] == false) { $div_display = $div_cookies[$cookie_name]; } } if (!empty($sugar_config['hide_subpanels'])) { $div_display = 'none'; } if ($thisPanel->isDefaultHidden()) { $div_display = 'none'; } if ($div_display == 'none') { $opp_display = 'inline'; } else { $opp_display = 'none'; } if (!empty($this->layout_def_key)) { $layout_def_key = $this->layout_def_key; } else { $layout_def_key = ''; } if (empty($this->show_tabs)) { $show_icon_html = SugarThemeRegistry::current()->getImage('advanced_search', 'border="0" align="absmiddle"', null, null, '.gif', translate('LBL_SHOW')); $hide_icon_html = SugarThemeRegistry::current()->getImage('basic_search', 'border="0" align="absmiddle"', null, null, '.gif', translate('LBL_HIDE')); $max_min = "<a name=\"{$tab}\"> </a><span id=\"show_link_" . $tab . "\" style=\"display: {$opp_display}\"><a href='#' class='utilsLink' onclick=\"current_child_field = '" . $tab . "';showSubPanel('" . $tab . "',null,null,'" . $layout_def_key . "');document.getElementById('show_link_" . $tab . "').style.display='none';document.getElementById('hide_link_" . $tab . "').style.display='';return false;\">" . "" . $show_icon_html . "</a></span>"; $max_min .= "<span id=\"hide_link_" . $tab . "\" style=\"display: {$div_display}\"><a href='#' class='utilsLink' onclick=\"hideSubPanel('" . $tab . "');document.getElementById('hide_link_" . $tab . "').style.display='none';document.getElementById('show_link_" . $tab . "').style.display='';return false;\">" . "" . $hide_icon_html . "</a></span>"; echo '<div id="subpanel_title_' . $tab . '"'; if (empty($sugar_config['lock_subpanels']) || $sugar_config['lock_subpanels'] == false) { echo ' onmouseover="this.style.cursor = \'move\';"'; } echo '>' . get_form_header($thisPanel->get_title(), $max_min, false) . '</div>'; } echo <<<EOQ <div cookie_name="{$cookie_name}" id="subpanel_{$tab}" style="display:{$div_display}"> <script>document.getElementById("subpanel_{$tab}" ).cookie_name="{$cookie_name}";</script> EOQ; $display_spd = ''; if ($div_display != 'none') { echo "<script>SUGAR.util.doWhen(\"typeof(markSubPanelLoaded) != 'undefined'\", function() {markSubPanelLoaded('{$tab}');});</script>"; $old_contents = ob_get_contents(); @ob_end_clean(); ob_start(); include_once 'include/SubPanel/SubPanel.php'; $subpanel_object = new SubPanel($this->module, $_REQUEST['record'], $tab, $thisPanel, $layout_def_key); $subpanel_object->setTemplateFile('include/SubPanel/SubPanelDynamic.html'); $subpanel_object->display(); $subpanel_data = ob_get_contents(); @ob_end_clean(); ob_start(); echo $this->get_buttons($thisPanel, $subpanel_object->subpanel_query); $buttons = ob_get_contents(); @ob_end_clean(); ob_start(); echo $old_contents; //echo $buttons; $display_spd = $subpanel_data; } echo <<<EOQ <div id="list_subpanel_{$tab}">{$display_spd}</div> </div> EOQ; array_push($tab_names, $tab); echo '</li>'; } // end $tabs foreach if ($showContainer) { echo '</ul>'; if (!empty($selected_group)) { // closing table from tpls/singletabmenu.tpl echo '</td></tr></table>'; } } // drag/drop code $tab_names = '["' . join($tab_names, '","') . '"]'; global $sugar_config; if (empty($sugar_config['lock_subpanels']) || $sugar_config['lock_subpanels'] == false) { echo <<<EOQ <script> \tvar SubpanelInit = function() { \t\tSubpanelInitTabNames({$tab_names}); \t} var SubpanelInitTabNames = function(tabNames) { \t\tsubpanel_dd = new Array(); \t\tj = 0; \t\tfor(i in tabNames) { \t\t\tsubpanel_dd[j] = new ygDDList('whole_subpanel_' + tabNames[i]); \t\t\tsubpanel_dd[j].setHandleElId('subpanel_title_' + tabNames[i]); \t\t\tsubpanel_dd[j].onMouseDown = SUGAR.subpanelUtils.onDrag; \t\t\tsubpanel_dd[j].afterEndDrag = SUGAR.subpanelUtils.onDrop; \t\t\tj++; \t\t} \t\tYAHOO.util.DDM.mode = 1; \t} \tcurrentModule = '{$this->module}'; \tSUGAR.util.doWhen( \t "typeof(SUGAR.subpanelUtils) == 'object' && typeof(SUGAR.subpanelUtils.onDrag) == 'function'" + \t " && document.getElementById('subpanel_list')", \t SubpanelInit \t); </script> EOQ; } $module_sub_panels = array_map('array_keys', $module_sub_panels); $module_sub_panels = json_encode($module_sub_panels); echo <<<EOQ <script> var ModuleSubPanels = {$module_sub_panels}; </script> EOQ; $ob_contents = ob_get_contents(); ob_end_clean(); return $ob_contents; }
/** * * DEPRECATED loads fields into the bean This used to be called during the retrieve process now it is done through a join Restored from pre-r30895 to maintain support for custom code that may have called retrieve() directly */ function retrieve() { if (!isset($this->bean)) { Log::fatal("DynamicField retrieve, bean not instantiated: " . var_export(debug_print_backtrace(), true)); return false; } if (!$this->bean->hasCustomFields()) { return false; } $query = "SELECT * FROM " . $this->bean->table_name . "_cstm WHERE id_c='" . $this->bean->id . "'"; $result = $GLOBALS['db']->query($query); $row = $GLOBALS['db']->fetchByAssoc($result); if ($row) { foreach ($row as $name => $value) { // originally in pre-r30895 we checked if this field was in avail_fields i.e., in fields_meta_data and not deleted // with the removal of avail_fields post-r30895 we have simplified this - we now retrieve every custom field even if previously deleted // this is considered harmless as the value although set in the bean will not otherwise be used (nothing else works off the list of fields in the bean) $this->bean->{$name} = $value; } } }
/** * Save label for id field * * @param string $idLabelName * @param DynamicField $df */ protected function saveIdLabel($idLabelName, $df) { if ($df instanceof DynamicField) { $module = $df->module; } elseif ($df instanceof MBModule) { $module = $df->name; } else { Log::fatal('Unsupported DynamicField type'); } $viewPackage = isset($df->package) ? $df->package : null; $idLabelValue = string_format($GLOBALS['mod_strings']['LBL_RELATED_FIELD_ID_NAME_LABEL'], array($this->label_value, $GLOBALS['app_list_strings']['moduleListSingular'][$this->ext2])); $idFieldLabelArr = array("label_{$idLabelName}" => $idLabelValue); foreach (ModuleBuilder::getModuleAliases($module) as $moduleName) { if ($df instanceof DynamicField) { $parser = new ParserLabel($moduleName, $viewPackage); $parser->handleSave($idFieldLabelArr, $GLOBALS['current_language']); } elseif ($df instanceof MBModule) { $df->setLabel($GLOBALS['current_language'], $idLabelName, $idLabelValue); $df->save(); } } }
public function index() { /* |-------------------------------------------------------------------------- | Check for image |-------------------------------------------------------------------------- | | Transform just needs the path to an image to get started. If it exists, | the fun begins. | */ $image_src = $this->fetchParam('src', null, false, false, false); // Set full system path $image_path = Path::standardize(Path::fromAsset($image_src)); // Check if image exists before doing anything. if (!File::isImage($image_path)) { Log::error("Could not find requested image to transform: " . $image_path, "core", "Transform"); return; } /* |-------------------------------------------------------------------------- | Resizing and cropping options |-------------------------------------------------------------------------- | | The first transformations we want to run is for size to reduce the | memory usage for future effects. | */ $width = $this->fetchParam('width', null, 'is_numeric'); $height = $this->fetchParam('height', null, 'is_numeric'); // resize specific $ratio = $this->fetchParam('ratio', true, false, true); $upsize = $this->fetchParam('upsize', true, false, true); // crop specific $pos_x = $this->fetchParam('pos_x', 0, 'is_numeric'); $pos_y = $this->fetchParam('pos_y', 0, 'is_numeric'); $quality = $this->fetchParam('quality', '75', 'is_numeric'); /* |-------------------------------------------------------------------------- | Action |-------------------------------------------------------------------------- | | Available actions: resize, crop, and guess. | | "Guess" will find the best fitting aspect ratio of your given width and | height on the current image automatically, cut it out and resize it to | the given dimension. | */ $action = $this->fetchParam('action', 'resize'); /* |-------------------------------------------------------------------------- | Extra bits |-------------------------------------------------------------------------- | | Delicious and probably rarely used options. | */ $angle = $this->fetchParam('rotate', false); $flip_side = $this->fetchParam('flip', false); $blur = $this->fetchParam('blur', false, 'is_numeric'); $pixelate = $this->fetchParam('pixelate', false, 'is_numeric'); $greyscale = $this->fetchParam(array('greyscale', 'grayscale'), false, false, true); /* |-------------------------------------------------------------------------- | Assemble filename and check for duplicate |-------------------------------------------------------------------------- | | We need to make sure we don't already have this image created, so we | defer any action until we've processed the parameters, which create | a unique filename. | */ // Late modified time of original image $last_modified = File::getLastModified($image_path); // Find .jpg, .png, etc $extension = File::getExtension($image_path); // Filename with the extension removed so we can append our unique filename flags $stripped_image_path = str_replace('.' . $extension, '', $image_path); // The possible filename flags $parameter_flags = array('width' => $width, 'height' => $height, 'quality' => $quality, 'rotate' => $angle, 'flip' => $flip_side, 'pos_x' => $pos_x, 'pos_y' => $pos_y, 'blur' => $blur, 'pixelate' => $pixelate, 'greyscale' => $greyscale, 'modified' => $last_modified); // Start with a 1 character action flag $file_breadcrumbs = '-' . $action[0]; foreach ($parameter_flags as $param => $value) { if ($value) { $flag = is_bool($value) ? '' : $value; // don't show boolean flags $file_breadcrumbs .= '-' . $param[0] . $flag; } } // Allow converting filetypes (jpg, png, gif) $extension = $this->fetchParam('type', $extension); // Allow saving in a different directory $destination = $this->fetchParam('destination', Config::get('transform_destination', false), false, false, false); if ($destination) { $destination = Path::tidy(BASE_PATH . '/' . $destination); // Method checks to see if folder exists before creating it Folder::make($destination); $stripped_image_path = Path::tidy($destination . '/' . basename($stripped_image_path)); } // Reassembled filename with all flags filtered and delimited $new_image_path = $stripped_image_path . $file_breadcrumbs . '.' . $extension; // Check if we've already built this image before if (File::exists($new_image_path)) { return Path::toAsset($new_image_path); } /* |-------------------------------------------------------------------------- | Create Image |-------------------------------------------------------------------------- | | Transform just needs the path to an image to get started. The image is | created in memory so we can start manipulating it. | */ $image = Image::make($image_path); /* |-------------------------------------------------------------------------- | Perform Actions |-------------------------------------------------------------------------- | | This is fresh transformation. Time to work the magic! | */ if ($action === 'resize' && ($width || $height)) { $image->resize($width, $height, $ratio, $upsize); } if ($action === 'crop' && $width && $height) { $image->crop($width, $height, $pos_x, $pos_y); } if ($action === 'smart') { $image->grab($width, $height); } $resize = $this->fetchParam('resize', null); if ($resize) { $resize_options = Helper::explodeOptions($resize, true); $image->resize(array_get($resize_options, 'width'), array_get($resize_options, 'height'), array_get($resize_options, 'ratio', true), array_get($resize_options, 'upsize', true)); } $crop = $this->fetchParam('crop', null); if ($crop) { $crop_options = Helper::explodeOptions($crop, true); $image->crop(array_get($crop_options, 'width'), array_get($crop_options, 'height'), array_get($crop_options, 'x'), array_get($crop_options, 'y')); } if ($angle) { $image->rotate($angle); } if ($flip_side === 'h' || $flip_side === 'v') { $image->flip($flip_side); } if ($greyscale) { $image->greyscale(); } if ($blur) { $image->blur($blur); } if ($pixelate) { $image->pixelate($pixelate); } /* |-------------------------------------------------------------------------- | Save |-------------------------------------------------------------------------- | | Get out of dodge! | */ try { $image->save($new_image_path, $quality); } catch (Exception $e) { Log::fatal('Could not write new images. Try checking your file permissions.', 'core', 'Transform'); throw new Exception('Could not write new images. Try checking your file permissions.'); } return File::cleanURL($new_image_path); }
/** * this is called when a user logs in * * @param STRING $name * @param STRING $password * @param STRING $fallback - is this authentication a fallback from a failed authentication * @return boolean */ function loadUserOnLogin($name, $password, $fallback = false, $PARAMS = array()) { global $login_error; Log::debug("Starting user load for " . $name); if (empty($name) || empty($password)) { return false; } $input_hash = $password; $passwordEncrypted = false; if (!empty($PARAMS) && isset($PARAMS['passwordEncrypted']) && $PARAMS['passwordEncrypted']) { $passwordEncrypted = true; } // if if (!$passwordEncrypted) { $input_hash = SugarAuthenticate::encodePassword($password); } // if $user_id = $this->authenticateUser($name, $input_hash, $fallback); if (empty($user_id)) { Log::fatal('SECURITY: User authentication for ' . $name . ' failed'); return false; } $this->loadUserOnSession($user_id); return true; }
/** * Run CRON cycle: * - cleanup * - schedule new jobs * - execute pending jobs */ public function runCycle() { // throttle if (!$this->throttle()) { Log::fatal("Job runs too frequently, throttled to protect the system."); return; } // clean old stale jobs if (!$this->queue->cleanup()) { $this->jobFailed(); } // run schedulers if (!$this->disable_schedulers) { $this->queue->runSchedulers(); } // run jobs $cutoff = time() + $this->max_runtime; register_shutdown_function(array($this, "unexpectedExit")); $myid = $this->getMyId(); for ($count = 0; $count < $this->max_jobs; $count++) { $this->job = $this->queue->nextJob($myid); if (empty($this->job)) { return; } $this->executeJob($this->job); if (time() >= $cutoff) { break; } } $this->job = null; }
private function connect() { if ($this->redis !== false) { return true; } $this->redis = new \Redis(); try { $this->redis->pconnect($this->host, $this->port, 1.0); if (!empty($this->prefix)) { $this->redis->setOption(\Redis::OPT_PREFIX, $this->prefix); } } catch (\RedisException $e) { $this->redis = false; $desc = 'redis - ' . $this->host . ':' . $this->port . ' - ' . $e->getMessage(); Log::fatal($desc); return false; } return true; }
/** * Handle exception * * @param Exception $e */ protected function handleException(Exception $e) { $logicHook = LogicHook::instance(); $dir = ''; Log::fatal("Exception in Controller: [{$e->getMessage()}]:[File: {$e->getFile()}:{$e->getLine()}]"); if (isset($this->bean)) { $logicHook->setBean($this->bean); $dir = $this->bean->module_dir; } LogicHook::instance(); $logicHook->call_custom_logic($dir, "handle_exception", $e); }
function constructQuery() { global $current_user; global $app_list_strings; $tempx = array(); $datax = array(); $selected_datax = array(); //get list of sales stage keys to display $tempx = $current_user->getPreference('lsbo_lead_sources'); if (!empty($lsbo_lead_sources) && count($lsbo_lead_sources) > 0 && !isset($_REQUEST['lsbo_lead_sources'])) { Log::fatal("user->getPreference('lsbo_lead_sources') is:"); Log::fatal($tempx); } elseif (isset($_REQUEST['lsbo_lead_sources']) && count($_REQUEST['lsbo_lead_sources']) > 0) { $tempx = $_REQUEST['lsbo_lead_sources']; $current_user->setPreference('lsbo_lead_sources', $_REQUEST['lsbo_lead_sources']); Log::fatal("_REQUEST['lsbo_lead_sources'] is:"); Log::fatal($_REQUEST['lsbo_lead_sources']); Log::fatal("user->getPreference('lsbo_lead_sources') is:"); Log::fatal($current_user->getPreference('lsbo_lead_sources')); } //set $datax using selected sales stage keys if (!empty($tempx) && sizeof($tempx) > 0) { foreach ($tempx as $key) { $datax[$key] = $app_list_strings['lead_source_dom'][$key]; array_push($selected_datax, $key); } } else { $datax = $app_list_strings['lead_source_dom']; $selected_datax = array_keys($app_list_strings['lead_source_dom']); } $datay = $datax; $ids = $current_user->getPreference('lsbo_ids'); //get list of user ids for which to display data if (!empty($ids) && count($ids) != 0 && !isset($_REQUEST['lsbo_ids'])) { Log::debug("_SESSION['lsbo_ids'] is:"); Log::debug($ids); } elseif (isset($_REQUEST['lsbo_ids']) && count($_REQUEST['lsbo_ids']) > 0) { $ids = $_REQUEST['lsbo_ids']; $current_user->setPreference('lsbo_ids', $_REQUEST['lsbo_ids']); Log::debug("_REQUEST['lsbo_ids'] is:"); Log::debug($_REQUEST['lsbo_ids']); Log::debug("user->getPreference('lsbo_ids') is:"); Log::debug($current_user->getPreference('lsbo_ids')); } else { $ids = get_user_array(false); $ids = array_keys($ids); } $user_id = $ids; $opp = new Opportunity(); $where = ""; //build the where clause for the query that matches $user $count = count($user_id); $id = array(); if ($count > 0) { foreach ($user_id as $the_id) { $id[] = "'" . $the_id . "'"; } $ids = join(",", $id); $where .= "opportunities.assigned_user_id IN ({$ids}) "; } //build the where clause for the query that matches $datay $count = count($datay); $datayArr = array(); if ($count > 0) { foreach ($datay as $key => $value) { $datayArr[] = "'" . $key . "'"; } $datayArr = join(",", $datayArr); $where .= "AND opportunities.lead_source IN\t({$datayArr}) "; } $query = "SELECT lead_source,sales_stage,sum(amount_usdollar/1000) as total,count(*) as opp_count FROM opportunities "; $query .= "WHERE " . $where . " AND opportunities.deleted=0 "; $query .= " GROUP BY sales_stage,lead_source ORDER BY lead_source,sales_stage"; return $query; }
/** * Called with the error number of the last call if the error number is 0 * there was no error otherwise it converts the error to a string and logs it as fatal * * @param INT $error * @return boolean */ function loginError($error) { if (empty($error)) { return false; } $errorstr = ldap_err2str($error); // BEGIN SUGAR INT $_SESSION['login_error'] = $errorstr; /* // END SUGAR INT $_SESSION['login_error'] = translate('ERR_INVALID_PASSWORD', 'Users'); // BEGIN SUGAR INT */ // END SUGAR INT Log::fatal('[LDAP ERROR][' . $error . ']' . $errorstr); return true; }
private function connect() { if ($this->db) { return true; } $options = array(\PDO::ATTR_PERSISTENT => true, \PDO::ATTR_TIMEOUT => 3); try { $this->db = new \PDO($this->dsn, $this->user, $this->passwd, $options); } catch (\PDOException $e) { $desc = 'mysql dsn=' . $this->dsn . ' connection failed: ' . $e->getMessage(); Log::fatal($desc); $this->db = false; return false; } $this->db->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_SILENT); $this->db->exec("SET NAMES utf8"); return true; }
/** * Retrieve the layout metadata for a given module given a specific type and view. * * @param String $session -- Session ID returned by a previous call to login. * @param array $module_name(s) -- The name of the module(s) to return records from. This name should be the name the module was developed under (changing a tab name is studio does not affect the name that should be passed into this method).. * @return array $type The type(s) of views requested. Current supported types are 'default' (for application) and 'wireless' * @return array $view The view(s) requested. Current supported types are edit, detail, list, and subpanel. * @exception 'SoapFault' -- The SOAP error, if any */ function get_module_layout($session, $a_module_names, $a_type, $a_view, $acl_check = TRUE, $md5 = FALSE) { Log::fatal('Begin: SugarWebServiceImpl->get_module_layout'); global $beanList, $beanFiles; $error = new SoapError(); $results = array(); foreach ($a_module_names as $module_name) { if (!self::$helperObject->checkSessionAndModuleAccess($session, 'invalid_session', $module_name, 'read', 'no_access', $error)) { Log::info('End: SugarWebServiceImpl->get_module_layout'); continue; } $class_name = $beanList[$module_name]; require_once $beanFiles[$class_name]; $seed = new $class_name(); foreach ($a_view as $view) { $aclViewCheck = strtolower($view) == 'subpanel' ? 'DetailView' : ucfirst(strtolower($view)) . 'View'; if (!$acl_check || $seed->ACLAccess($aclViewCheck, true)) { foreach ($a_type as $type) { $a_vardefs = self::$helperObject->get_module_view_defs($module_name, $type, $view); if ($md5) { $results[$module_name][$type][$view] = md5(serialize($a_vardefs)); } else { $results[$module_name][$type][$view] = $a_vardefs; } } } } } Log::info('End: SugarWebServiceImpl->get_module_layout'); return $results; }
/** * send reminders * @param SugarBean $bean * @param Administration $admin * @param array $recipients * @return boolean */ protected function sendReminders(SugarBean $bean, Administration $admin, $recipients) { if (empty($_SESSION['authenticated_user_language'])) { $current_language = $GLOBALS['sugar_config']['default_language']; } else { $current_language = $_SESSION['authenticated_user_language']; } if (!empty($bean->created_by)) { $user_id = $bean->created_by; } else { if (!empty($bean->assigned_user_id)) { $user_id = $bean->assigned_user_id; } else { $user_id = $GLOBALS['current_user']->id; } } $user = new User(); $user->retrieve($bean->created_by); $OBCharset = $GLOBALS['locale']->getPrecedentPreference('default_email_charset'); $mail = new SugarPHPMailer(); $mail->setMailerForSystem(); if (empty($admin->settings['notify_send_from_assigning_user'])) { $from_address = $admin->settings['notify_fromaddress']; $from_name = $admin->settings['notify_fromname'] ? "" : $admin->settings['notify_fromname']; } else { $from_address = $user->emailAddress->getReplyToAddress($user); $from_name = $user->full_name; } $mail->From = $from_address; $mail->FromName = $from_name; $xtpl = new XTemplate(get_notify_template_file($current_language)); $xtpl = $this->setReminderBody($xtpl, $bean, $user); $template_name = $GLOBALS['beanList'][$bean->module_dir] . 'Reminder'; $xtpl->parse($template_name); $xtpl->parse($template_name . "_Subject"); $mail->Body = from_html(trim($xtpl->text($template_name))); $mail->Subject = from_html($xtpl->text($template_name . "_Subject")); $oe = new OutboundEmail(); $oe = $oe->getSystemMailerSettings(); if (empty($oe->mail_smtpserver)) { Log::fatal("Email Reminder: error sending email, system smtp server is not set"); return; } foreach ($recipients as $r) { $mail->ClearAddresses(); $mail->AddAddress($r['email'], $GLOBALS['locale']->translateCharsetMIME(trim($r['name']), 'UTF-8', $OBCharset)); $mail->prepForOutbound(); if (!$mail->Send()) { Log::fatal("Email Reminder: error sending e-mail (method: {$mail->Mailer}), (error: {$mail->ErrorInfo})"); } } return true; }
/** * Validate the user session based on user name and password hash. * * @param string $user_name -- The user name to create a session for * @param string $password -- The MD5 sum of the user's password * @return true -- If the session is created * @return false -- If the session is not created */ function validate_user($user_name, $password) { global $server, $current_user, $sugar_config, $system_config; $user = new User(); $user->user_name = $user_name; $system_config = new Administration(); $system_config->retrieveSettings('system'); $authController = new AuthenticationController(); // Check to see if the user name and password are consistent. if ($user->authenticate_user($password)) { // we also need to set the current_user. $user->retrieve($user->id); $current_user = $user; login_success(); return true; } else { if (function_exists('mcrypt_cbc')) { $password = decrypt_string($password); if ($authController->login($user_name, $password) && isset($_SESSION['authenticated_user_id'])) { $user->retrieve($_SESSION['authenticated_user_id']); $current_user = $user; login_success(); return true; } } else { Log::fatal("SECURITY: failed attempted login for {$user_name} using SOAP api"); $server->setError("Invalid username and/or password"); return false; } } }