/**
  * This method implements the run function of RunnableSchedulerJob and handles processing a SchedulersJob
  *
  * @param Mixed $data parameter passed in from the job_queue.data column when a SchedulerJob is run
  * @return bool true on success, false on error
  */
 public function run($data)
 {
     global $app_strings, $language;
     $app_strings = return_application_language($language);
     $admin = BeanFactory::getBean('Administration');
     $config = $admin->getConfigForModule('Forecasts', 'base');
     $timeperiodInterval = $config['timeperiod_interval'];
     $timeperiodLeafInterval = $config['timeperiod_leaf_interval'];
     $parentTimePeriod = TimePeriod::getLatest($timeperiodInterval);
     $latestTimePeriod = TimePeriod::getLatest($timeperiodLeafInterval);
     $currentTimePeriod = TimePeriod::getCurrentTimePeriod($timeperiodLeafInterval);
     if (empty($latestTimePeriod)) {
         $GLOBALS['log']->error(string_format($app_strings['ERR_TIMEPERIOD_TYPE_DOES_NOT_EXIST'], array($timeperiodLeafInterval)) . '[latest]');
         return false;
     } else {
         if (empty($currentTimePeriod)) {
             $GLOBALS['log']->error(string_format($app_strings['ERR_TIMEPERIOD_TYPE_DOES_NOT_EXIST'], array($timeperiodLeafInterval)) . ' [current]');
             return false;
         } else {
             if (empty($parentTimePeriod)) {
                 $GLOBALS['log']->error(string_format($app_strings['ERR_TIMEPERIOD_TYPE_DOES_NOT_EXIST'], array($timeperiodLeafInterval)) . ' [parent]');
                 return false;
             }
         }
     }
     $timedate = TimeDate::getInstance();
     //We run the rebuild command if the latest TimePeriod is less than the specified configuration interval
     //from the current TimePeriod
     $correctStartDate = $timedate->fromDbDate($currentTimePeriod->start_date);
     $latestStartDate = $timedate->fromDbDate($latestTimePeriod->start_date);
     $shownForward = $config['timeperiod_shown_forward'];
     //Move the current start date forward by the leaf period amounts
     for ($x = 0; $x < $shownForward; $x++) {
         $correctStartDate->modify($parentTimePeriod->next_date_modifier);
     }
     $leafCycle = $latestTimePeriod->leaf_cycle;
     //If the current start data that was modified according to the shown forward period is past the latest
     //leaf period we need to build more timeperiods
     while ($correctStartDate > $latestStartDate) {
         //We need to keep creating leaf periods until we are in sync.
         //If the leaf period we need to create is the start of the leaf cycle
         //then we should also create the parent TimePeriod record.
         $startDate = $latestStartDate->modify($latestTimePeriod->next_date_modifier);
         $leafCycle = $leafCycle == $parentTimePeriod->leaf_periods ? 1 : $leafCycle + 1;
         if ($leafCycle == 1) {
             $parentTimePeriod = TimePeriod::getByType($timeperiodInterval);
             $parentTimePeriod->setStartDate($startDate->asDbDate());
             $parentTimePeriod->name = $parentTimePeriod->getTimePeriodName($leafCycle);
             $parentTimePeriod->save();
         }
         $leafTimePeriod = TimePeriod::getByType($timeperiodLeafInterval);
         $leafTimePeriod->setStartDate($startDate->asDbDate());
         $leafTimePeriod->name = $leafTimePeriod->getTimePeriodName($leafCycle, $parentTimePeriod);
         $leafTimePeriod->leaf_cycle = $leafCycle;
         $leafTimePeriod->parent_id = $parentTimePeriod->id;
         $leafTimePeriod->save();
     }
     $this->job->succeedJob();
     return true;
 }
Example #2
0
 function get_recently_viewed($user_id, $modules = '')
 {
     $path = 'modules/Trackers/BreadCrumbStack.php';
     if (defined('TEMPLATE_URL')) {
         $path = SugarTemplateUtilities::getFilePath($path);
     }
     require_once $path;
     if (empty($_SESSION['breadCrumbs'])) {
         $breadCrumb = new BreadCrumbStack($user_id, $modules);
         $_SESSION['breadCrumbs'] = $breadCrumb;
         $GLOBALS['log']->info(string_format($GLOBALS['app_strings']['LBL_BREADCRUMBSTACK_CREATED'], array($user_id)));
     } else {
         $breadCrumb = $_SESSION['breadCrumbs'];
         $module_query = '';
         if (!empty($modules)) {
             $history_max_viewed = 10;
             $module_query = is_array($modules) ? ' AND module_name IN (\'' . implode("','", $modules) . '\')' : ' AND module_name = \'' . $modules . '\'';
         } else {
             $history_max_viewed = !empty($GLOBALS['sugar_config']['history_max_viewed']) ? $GLOBALS['sugar_config']['history_max_viewed'] : 50;
         }
         $query = 'SELECT item_id, item_summary, module_name, id FROM ' . $this->table_name . ' WHERE id = (SELECT MAX(id) as id FROM ' . $this->table_name . ' WHERE user_id = \'' . $user_id . '\' AND deleted = 0 AND visible = 1' . $module_query . ')';
         $result = $this->db->limitQuery($query, 0, $history_max_viewed, true, $query);
         while ($row = $this->db->fetchByAssoc($result)) {
             $breadCrumb->push($row);
         }
     }
     $list = $breadCrumb->getBreadCrumbList($modules);
     $GLOBALS['log']->info("Tracker: retrieving " . count($list) . " items");
     return $list;
 }
 /**
  * This method implements the run function of RunnableSchedulerJob and handles processing a SchedulersJob
  *
  * @param Mixed $data parameter passed in from the job_queue.data column when a SchedulerJob is run
  * @return bool true on success, false on error
  */
 public function run($data)
 {
     // Searches across modules for rate update scheduler jobs and executes them.
     // Each module that has currency rates in its model(s) *must* have a scheduler
     // job defined in order to update its rates when a currency rate is updated.
     $globPaths = array('custom/modules/*/jobs/Custom*CurrencyRateUpdate.php', 'modules/*/jobs/*CurrencyRateUpdate.php');
     foreach ($globPaths as $entry) {
         $jobFiles = glob($entry, GLOB_NOSORT);
         if (!empty($jobFiles)) {
             foreach ($jobFiles as $jobFile) {
                 $jobClass = basename($jobFile, '.php');
                 require_once $jobFile;
                 if (!class_exists($jobClass)) {
                     $GLOBALS['log']->error(string_format($GLOBALS['app_strings']['ERR_DB_QUERY'], array(get_class($this), 'uknown class: ' . $jobClass)));
                     continue;
                 }
                 $jobObject = new $jobClass();
                 $data = $this->job->data;
                 $jobObject->run($data);
             }
         }
     }
     $this->job->succeedJob();
     return true;
 }
Example #4
0
 function display()
 {
     global $mod_strings, $export_module, $current_language, $theme, $current_user, $dashletData, $sugar_flavor;
     if ($this->checkPostMaxSizeError()) {
         $this->errors[] = $GLOBALS['app_strings']['UPLOAD_ERROR_HOME_TEXT'];
         $contentLength = $_SERVER['CONTENT_LENGTH'];
         $maxPostSize = ini_get('post_max_size');
         if (stripos($maxPostSize, "k")) {
             $maxPostSize = (int) $maxPostSize * pow(2, 10);
         } elseif (stripos($maxPostSize, "m")) {
             $maxPostSize = (int) $maxPostSize * pow(2, 20);
         }
         $maxUploadSize = ini_get('upload_max_filesize');
         if (stripos($maxUploadSize, "k")) {
             $maxUploadSize = (int) $maxUploadSize * pow(2, 10);
         } elseif (stripos($maxUploadSize, "m")) {
             $maxUploadSize = (int) $maxUploadSize * pow(2, 20);
         }
         $max_size = min($maxPostSize, $maxUploadSize);
         $errMessage = string_format($GLOBALS['app_strings']['UPLOAD_MAXIMUM_EXCEEDED'], array($contentLength, $max_size));
         $this->errors[] = '* ' . $errMessage;
         $this->displayErrors();
     }
     include 'modules/Home/index.php';
 }
Example #5
0
 public function testStringFormatDontReturnsEmptyValue()
 {
     $sourceString = "SELECT accounts.name FROM accounts WHERE id IN";
     $string = "{$sourceString} ({0})";
     $args = array('');
     $this->assertEquals("{$sourceString} ('')", string_format($string, $args));
 }
Example #6
0
 function processMaxPostErrors()
 {
     if ($this->checkPostMaxSizeError()) {
         $this->errors[] = $GLOBALS['app_strings']['UPLOAD_ERROR_HOME_TEXT'];
         $contentLength = $_SERVER['CONTENT_LENGTH'];
         $maxPostSize = ini_get('post_max_size');
         if (stripos($maxPostSize, "k")) {
             $maxPostSize = (int) $maxPostSize * pow(2, 10);
         } elseif (stripos($maxPostSize, "m")) {
             $maxPostSize = (int) $maxPostSize * pow(2, 20);
         }
         $maxUploadSize = ini_get('upload_max_filesize');
         if (stripos($maxUploadSize, "k")) {
             $maxUploadSize = (int) $maxUploadSize * pow(2, 10);
         } elseif (stripos($maxUploadSize, "m")) {
             $maxUploadSize = (int) $maxUploadSize * pow(2, 20);
         }
         $max_size = min($maxPostSize, $maxUploadSize);
         if ($contentLength > $max_size) {
             $errMessage = string_format($GLOBALS['app_strings']['UPLOAD_MAXIMUM_EXCEEDED'], array($contentLength, $max_size));
         } else {
             $errMessage = $GLOBALS['app_strings']['UPLOAD_REQUEST_ERROR'];
         }
         $this->errors[] = '* ' . $errMessage;
         $this->displayErrors();
     }
 }
 /**
  * doCustomUpdateUsDollarRate
  *
  * Return true to skip updates for this module.
  * Return false to do default update of amount * base_rate = usdollar
  * To custom processing, do here and return true.
  *
  * @access public
  * @param  string    $tableName
  * @param  string    $usDollarColumn
  * @param  string    $amountColumn
  * @param  string    $currencyId
  * @return boolean true if custom processing was done
  */
 public function doCustomUpdateUsDollarRate($tableName, $usDollarColumn, $amountColumn, $currencyId)
 {
     // setup SQL statement
     $query = sprintf("UPDATE %s SET %s = %s / base_rate\n            WHERE quote_stage NOT LIKE ('%%Closed%%')\n            AND currency_id = '%s'", $tableName, $usDollarColumn, $amountColumn, $currencyId);
     // execute
     $result = $this->db->query($query, true, string_format($GLOBALS['app_strings']['ERR_DB_QUERY'], array('QuotesCurrencyRateUpdate', $query)));
     return !empty($result);
 }
Example #8
0
 /**
  * Return the "breadcrumbs" to display at the top of the page
  *
  * @param  bool $show_help optional, true if we show the help links
  * @return HTML string containing breadcrumb title
  */
 public function getModuleTitle($show_help = true)
 {
     global $app_list_strings, $mod_strings;
     $warningText = string_format($mod_strings['LBL_LIST_WARNING'], array($app_list_strings['moduleList']['Forecasts'], $app_list_strings['moduleList'][$this->module]));
     $float = SugarThemeRegistry::current()->directionality == 'rtl' ? 'right' : 'left';
     $title = '<div><div class="moduleTitle"><h2>' . $app_list_strings['moduleList'][$this->module] . '</h2></div>';
     $title .= "<div class='overdueTask' style='float:{$float}; padding-bottom:10px;'>{$warningText}</div></div>";
     return $title;
 }
 /**
  * getTimePeriodName
  *
  * Returns the timeperiod name.  The TimePeriod base implementation simply returns the $count argument passed
  * in from the code
  *
  * @param $count The timeperiod series count
  * @return string The formatted name of the timeperiod
  */
 public function getTimePeriodName($count)
 {
     $timedate = TimeDate::getInstance();
     $year = $timedate->fromDbDate($this->start_date);
     if (isset($this->currentSettings['timeperiod_fiscal_year']) && $this->currentSettings['timeperiod_fiscal_year'] == 'next_year') {
         $year->modify('+1 year');
     }
     return string_format($this->name_template, array($year->format('Y')));
 }
 /**
  * doCustomUpdateUsDollarRate
  *
  * Return true to skip updates for this module.
  * Return false to do default update of amount * base_rate = usdollar
  * To custom processing, do here and return true.
  *
  * @access public
  * @param  string    $tableName
  * @param  string    $usDollarColumn
  * @param  string    $amountColumn
  * @param  string    $currencyId
  * @return boolean true if custom processing was done
  */
 public function doCustomUpdateUsDollarRate($tableName, $usDollarColumn, $amountColumn, $currencyId)
 {
     $stages = $this->getClosedStages();
     // setup SQL statement
     $query = sprintf("UPDATE %s SET %s = %s / base_rate\n            WHERE sales_stage NOT IN ('%s')\n            AND currency_id = '%s'", $tableName, $usDollarColumn, $amountColumn, implode("','", $stages), $currencyId);
     // execute
     $result = $this->db->query($query, true, string_format($GLOBALS['app_strings']['ERR_DB_QUERY'], array('OpportunitiesCurrencyRateUpdate', $query)));
     return !empty($result);
 }
Example #11
0
 /**
  * @dataProvider  getQueries
  * @outputBuffering disabled
  */
 public function testCheckQuery($where, $order_by, $ok)
 {
     $helper = new SugarSQLValidate();
     $res = $helper->validateQueryClauses($where, $order_by);
     $params = array($where, $order_by);
     if ($ok) {
         $this->assertTrue($res, string_format("Failed asserting that where: {0} and order by: {1} is valid", $params));
     } else {
         $this->assertFalse($res, string_format("Failed asserting that where: {0} and order by: {1} is invalid", $params));
     }
 }
Example #12
0
 public function initialize($leadId)
 {
     $this->defs = $this->getVarDefs();
     if (empty($this->defs)) {
         throw new Exception('Could not retrieve lead convert metadata.');
     }
     $this->lead = BeanFactory::getBean('Leads', $leadId, array('strict_retrieve' => true));
     if (empty($this->lead)) {
         $errorMessage = string_format('Could not find record: {0} in module: Leads', $leadId);
         throw new Exception($errorMessage);
     }
 }
Example #13
0
 /**
  * Sets the user locale appropriate message that is suitable for clients to display to end users.
  * Message is based upon the message label provided when this SugarApiException was constructed.
  *
  * If the message label isn't found in app_strings or mod_strings, we'll use the label itself as the message.
  *
  * @param string $messageLabel required Label for error message.  Used to load the appropriate translated message.
  * @param array $msgArgs optional set of arguments to substitute into error message string
  * @param string|null $moduleName Provide module name if $messageLabel is a module string, leave empty if
  *  $messageLabel is in app strings.
  */
 public function setMessage($messageLabel, $msgArgs = null, $moduleName = null)
 {
     // If no message label, don't bother looking it up
     if (empty($messageLabel)) {
         $this->message = null;
         return;
     }
     $message = translate($messageLabel, $moduleName);
     // If no arguments provided, return message.
     // If there are arguments, insert into message then return formatted message
     if (empty($msgArgs)) {
         $this->message = $message;
     } else {
         $this->message = string_format($message, $msgArgs);
     }
 }
Example #14
0
 function listViewProcess()
 {
     if (!($eapmBean = EAPM::getLoginInfo('LotusLive', true))) {
         $smarty = new Sugar_Smarty();
         echo $smarty->fetch('include/externalAPI/LotusLive/LotusLiveSignup.' . $GLOBALS['current_language'] . '.tpl');
         return;
     }
     $apiName = 'LotusLive';
     $api = ExternalAPIFactory::loadAPI($apiName, true);
     $api->loadEAPM($eapmBean);
     $quickCheck = $api->quickCheckLogin();
     if (!$quickCheck['success']) {
         $errorMessage = string_format(translate('LBL_ERR_FAILED_QUICKCHECK', 'EAPM'), array('LotusLive'));
         $errorMessage .= '<form method="POST" target="_EAPM_CHECK" action="index.php">';
         $errorMessage .= '<input type="hidden" name="module" value="EAPM">';
         $errorMessage .= '<input type="hidden" name="action" value="Save">';
         $errorMessage .= '<input type="hidden" name="record" value="' . $eapmBean->id . '">';
         $errorMessage .= '<input type="hidden" name="active" value="1">';
         $errorMessage .= '<input type="hidden" name="closeWhenDone" value="1">';
         $errorMessage .= '<input type="hidden" name="refreshParentWindow" value="1">';
         $errorMessage .= '<br><input type="submit" value="' . $GLOBALS['app_strings']['LBL_EMAIL_OK'] . '">&nbsp;';
         $errorMessage .= '<input type="button" onclick="lastLoadedMenu=undefined;DCMenu.closeOverlay();return false;" value="' . $GLOBALS['app_strings']['LBL_CANCEL_BUTTON_LABEL'] . '">';
         $errorMessage .= '</form>';
         echo $errorMessage;
         return;
     }
     $this->processSearchForm();
     $this->params['orderBy'] = 'meetings.date_start';
     $this->params['overrideOrder'] = true;
     $this->lv->searchColumns = $this->searchForm->searchColumns;
     $this->lv->show_action_dropdown = false;
     $this->lv->multiSelect = false;
     unset($this->searchForm->searchdefs['layout']['advanced_search']);
     if (!$this->headers) {
         return;
     }
     if (empty($_REQUEST['search_form_only']) || $_REQUEST['search_form_only'] == false) {
         $this->lv->ss->assign("SEARCH", false);
         if (!isset($_REQUEST['name_basic'])) {
             $_REQUEST['name_basic'] = '';
         }
         $this->lv->ss->assign('DCSEARCH', $_REQUEST['name_basic']);
         $this->lv->setup($this->seed, 'include/ListView/ListViewDCMenu.tpl', $this->where, $this->params);
         $savedSearchName = empty($_REQUEST['saved_search_select_name']) ? '' : ' - ' . $_REQUEST['saved_search_select_name'];
         echo $this->lv->display();
     }
 }
Example #15
0
 /**
  * Notify the report owner of deactivated report schedule.
  *
  * @param int  $report_id
  * @param User $owner
  * @param User $subscriber
  *
  * @throws MailerException Allows exceptions to bubble up for the caller to report if desired.
  */
 public function sendNotificationOfDisabledReport($report_id, User $owner = null, User $subscriber = null)
 {
     $recipients = array($owner, $subscriber);
     $recipients = array_filter($recipients);
     // return early in case there are no recipients specified
     if (!$recipients) {
         return;
     }
     $mod_strings = return_module_language($this->language, 'Reports');
     $subject = $mod_strings['ERR_REPORT_DEACTIVATED_SUBJECT'];
     $body = string_format($mod_strings['ERR_REPORT_DEACTIVATED'], array($report_id));
     // make sure that the same user doesn't receive the notification twice
     $unique = array();
     foreach ($recipients as $recipient) {
         $unique[$recipient->id] = $recipient;
     }
     foreach ($unique as $recipient) {
         $this->sendNotificationOfReport($recipient, $subject, $body);
     }
 }
Example #16
0
 /**
  * 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;
 }
Example #17
0
 protected function generateChartJson()
 {
     global $app_list_strings, $app_strings;
     $arrData = array();
     $arrProbabilities = array();
     $forecast_strings = $this->getModuleLanguage('Forecasts');
     $config = $this->getForecastConfig();
     $acl = new SugarACLForecastWorksheets();
     $bestAccess = $acl->checkAccess('ForecastWorksheets', 'field', array('field' => 'best_case', 'action' => 'view'));
     $worstAccess = $acl->checkAccess('ForecastWorksheets', 'field', array('field' => 'worst_case', 'action' => 'view'));
     if (!empty($this->dataArray)) {
         foreach ($this->dataArray as $data) {
             // If users have made likely/best/worst not required,
             // set the value to 0 for upcoming currency math
             if (empty($data['likely_case'])) {
                 $data['likely_case'] = 0;
             }
             $v = array('id' => $data['id'], 'record_id' => $data['parent_id'], 'forecast' => $data['commit_stage'], 'probability' => $data['probability'], 'sales_stage' => $data['sales_stage'], 'likely' => SugarCurrency::convertWithRate($data['likely_case'], $data['base_rate']), 'date_closed_timestamp' => intval($data['date_closed_timestamp']));
             if ($config['show_worksheet_best'] && $bestAccess) {
                 if (empty($data['best_case'])) {
                     $data['best_case'] = 0;
                 }
                 $v['best'] = SugarCurrency::convertWithRate($data['best_case'], $data['base_rate']);
             }
             if ($config['show_worksheet_worst'] && $worstAccess) {
                 if (empty($data['worst_case'])) {
                     $data['worst_case'] = 0;
                 }
                 $v['worst'] = SugarCurrency::convertWithRate($data['worst_case'], $data['base_rate']);
             }
             $arrData[] = $v;
             $arrProbabilities[$data['probability']] = $data['probability'];
         }
         asort($arrProbabilities);
     }
     $tp = $this->getTimeperiod();
     $chart_info = array('title' => string_format($forecast_strings['LBL_CHART_FORECAST_FOR'], array($tp->name)), 'quota' => $this->getUserQuota(), 'x-axis' => $tp->getChartLabels(array()), 'labels' => array('forecast' => $app_list_strings[$config['buckets_dom']], 'sales_stage' => $app_list_strings['sales_stage_dom'], 'probability' => $arrProbabilities, 'dataset' => array('likely' => $app_strings['LBL_LIKELY'], 'best' => $app_strings['LBL_BEST'], 'worst' => $app_strings['LBL_WORST'])), 'data' => $arrData);
     return $chart_info;
 }
Example #18
0
 public function generateChartJson()
 {
     $config = $this->getForecastConfig();
     // sort the data so it's in the correct order
     usort($this->dataArray, array($this, 'sortChartColumns'));
     // loop variables
     $values = array();
     foreach ($this->dataArray as $data) {
         $value = array('id' => $data['id'], 'user_id' => $data['user_id'], 'name' => html_entity_decode($data['name'], ENT_QUOTES), 'likely' => SugarCurrency::convertWithRate($data['likely_case'], $data['base_rate']), 'likely_adjusted' => SugarCurrency::convertWithRate($data['likely_case_adjusted'], $data['base_rate']));
         if ($config['show_worksheet_best']) {
             $value['best'] = SugarCurrency::convertWithRate($data['best_case'], $data['base_rate']);
             $value['best_adjusted'] = SugarCurrency::convertWithRate($data['best_case_adjusted'], $data['base_rate']);
         }
         if ($config['show_worksheet_worst']) {
             $value['worst'] = SugarCurrency::convertWithRate($data['worst_case'], $data['base_rate']);
             $value['worst_adjusted'] = SugarCurrency::convertWithRate($data['worst_case_adjusted'], $data['base_rate']);
         }
         $values[] = $value;
     }
     $forecast_strings = $this->getModuleLanguage('Forecasts');
     global $app_strings;
     $tp = $this->getTimeperiod();
     return array('title' => string_format($forecast_strings['LBL_CHART_FORECAST_FOR'], array($tp->name)), 'quota' => $this->getRollupQuota(), 'labels' => array('dataset' => array('likely' => $app_strings['LBL_LIKELY'], 'best' => $app_strings['LBL_BEST'], 'worst' => $app_strings['LBL_WORST'], 'likely_adjusted' => $app_strings['LBL_LIKELY_ADJUSTED'], 'best_adjusted' => $app_strings['LBL_BEST_ADJUSTED'], 'worst_adjusted' => $app_strings['LBL_WORST_ADJUSTED'])), 'data' => $values);
 }
 private function writeUnifiedSearchModulesDisplayFile($unified_search_modules_display)
 {
     if (is_null($unified_search_modules_display) || empty($unified_search_modules_display)) {
         return false;
     }
     if (!write_array_to_file("unified_search_modules_display", $unified_search_modules_display, 'custom/modules/unified_search_modules_display.php')) {
         //Log error message and throw Exception
         global $app_strings;
         $msg = string_format($app_strings['ERR_FILE_WRITE'], array('custom/modules/unified_search_modules_display.php'));
         $GLOBALS['log']->error($msg);
         throw new Exception($msg);
     }
     return true;
 }
Example #20
0
/**
 * Get a list of the relationship records that have been modified within a 
 * specified date range.  This is used to perform a sync with a mobile client.
 * The results are paged.
 *
 * @param xsd:string $session
 * @param xsd:string $module_name
 * @param xsd:string $related_module
 * @param xsd:string $from_date
 * @param xsd:string $to_date
 * @param xsd:int $offset
 * @param xsd:int $max_results
 * @param xsd:int $deleted
 * @param xsd:int $module_id
 * @param tns:select_fields $select_fields
 * @param tns:select_fields $ids
 * @param xsd:string $relationship_name
 * @param xsd:string $deletion_date
 * @param xsd:int $php_serialize
 * @return 
 */
function sync_get_modified_relationships($session, $module_name, $related_module, $from_date, $to_date, $offset, $max_results, $deleted, $module_id = '', $select_fields = array(), $ids = array(), $relationship_name = '', $deletion_date = '', $php_serialize = 1)
{
    global $beanList, $beanFiles;
    $error = new SoapError();
    $output_list = array();
    if (!validate_authenticated($session)) {
        $error->set_error('invalid_login');
        return array('result_count' => -1, 'entry_list' => array(), 'error' => $error->get_soap_array());
    }
    if (empty($beanList[$module_name]) || empty($beanList[$related_module])) {
        $error->set_error('no_module');
        return array('result_count' => -1, 'entry_list' => array(), 'error' => $error->get_soap_array());
    }
    global $current_user;
    if (!check_modules_access($current_user, $module_name, 'read') || !check_modules_access($current_user, $related_module, 'read')) {
        $error->set_error('no_access');
        return array('result_count' => -1, 'entry_list' => array(), 'error' => $error->get_soap_array());
    }
    // Cast to integer
    $deleted = (int) $deleted;
    if ($max_results > 0 || $max_results == '-99') {
        global $sugar_config;
        $sugar_config['list_max_entries_per_page'] = $max_results;
    }
    $date_query = "(m1.date_modified > " . db_convert("'" . $GLOBALS['db']->quote($from_date) . "'", 'datetime') . " AND m1.date_modified <= " . db_convert("'" . $GLOBALS['db']->quote($to_date) . "'", 'datetime') . " AND {0}.deleted = {$deleted})";
    if (isset($deletion_date) && !empty($deletion_date)) {
        $date_query .= " OR ({0}.date_modified > " . db_convert("'" . $GLOBALS['db']->quote($deletion_date) . "'", 'datetime') . " AND {0}.date_modified <= " . db_convert("'" . $GLOBALS['db']->quote($to_date) . "'", 'datetime') . " AND {0}.deleted = 1)";
    }
    $in = '';
    if (isset($ids) && !empty($ids)) {
        foreach ($ids as $value) {
            if (empty($in)) {
                $in .= "('" . $GLOBALS['db']->quote($value) . "'";
            } else {
                $in .= ",'" . $GLOBALS['db']->quote($value) . "'";
            }
        }
        $in .= ')';
    }
    $query = '';
    if (isset($in) && !empty($in)) {
        $query .= "( {$date_query} AND m1.id IN {$in}) OR (m1.id NOT IN {$in} AND {0}.deleted = 0)";
    } else {
        $query .= "( {0}.deleted = 0)";
    }
    if (isset($module_id) && !empty($module_id)) {
        //if(isset($in) && !empty($in)){
        $query .= " AND";
        //}
        $query .= " m2.id = '" . $GLOBALS['db']->quote($module_id) . "'";
    }
    if ($related_module == 'Meetings' || $related_module == 'Calls') {
        $query = string_format($query, array('m1'));
    }
    $results = retrieve_modified_relationships($module_name, $related_module, $query, $deleted, $offset, $max_results, $select_fields, $relationship_name);
    $list = $results['result'];
    $xml = '<?xml version="1.0" encoding="utf-8"?><items>';
    foreach ($list as $value) {
        $val = array_get_return_value($value, $results['table_name']);
        if ($php_serialize == 0) {
            $xml .= get_name_value_xml($val, $module_name);
        }
        $output_list[] = $val;
    }
    $xml .= '</items>';
    $next_offset = $offset + sizeof($output_list);
    if ($php_serialize == 0) {
        $myoutput = base64_encode($xml);
    } else {
        $myoutput = get_encoded($output_list);
    }
    return array('result_count' => sizeof($output_list), 'next_offset' => 0, 'total_count' => sizeof($output_list), 'field_list' => array(), 'entry_list' => $myoutput, 'error' => $error->get_soap_array());
}
Example #21
0
 /**
  * logMemoryStatistics
  *
  * This function returns a string message containing the memory statistics as well as writes to the memory_usage.log
  * file the memory statistics for the SugarView invocation.
  *
  * @param $newline String of newline character to use (defaults to </ br>)
  * @return $message String formatted message about memory statistics
  */
 protected function logMemoryStatistics($newline = '<br>')
 {
     $log_message = '';
     if (!empty($GLOBALS['sugar_config']['log_memory_usage'])) {
         if (function_exists('memory_get_usage')) {
             $memory_usage = memory_get_usage();
             $bytes = $GLOBALS['app_strings']['LBL_SERVER_MEMORY_BYTES'];
             $data = array($memory_usage, $bytes);
             $log_message = string_format($GLOBALS['app_strings']['LBL_SERVER_MEMORY_USAGE'], $data) . $newline;
         }
         if (function_exists('memory_get_peak_usage')) {
             $memory_peak_usage = memory_get_peak_usage();
             $bytes = $GLOBALS['app_strings']['LBL_SERVER_MEMORY_BYTES'];
             $data = array($memory_peak_usage, $bytes);
             $log_message .= string_format($GLOBALS['app_strings']['LBL_SERVER_PEAK_MEMORY_USAGE'], $data) . $newline;
         }
         if (!empty($log_message)) {
             $data = array(!empty($this->module) ? $this->module : $GLOBALS['app_strings']['LBL_LINK_NONE'], !empty($this->action) ? $this->action : $GLOBALS['app_strings']['LBL_LINK_NONE']);
             $output = string_format($GLOBALS['app_strings']['LBL_SERVER_MEMORY_LOG_MESSAGE'], $data) . $newline;
             $output .= $log_message;
             $fp = fopen("memory_usage.log", "ab");
             fwrite($fp, $output);
             fclose($fp);
         }
     }
     return $log_message;
 }
Example #22
0
 /**
  * @see SugarView::display()
  */
 public function display()
 {
     global $mod_strings, $app_strings, $current_user;
     global $sugar_config, $locale;
     $this->ss->assign("IMPORT_MODULE", $_REQUEST['import_module']);
     $this->ss->assign("TYPE", !empty($_REQUEST['type']) ? $_REQUEST['type'] : "import");
     $this->ss->assign("SOURCE_ID", $_REQUEST['source_id']);
     $this->instruction = 'LBL_SELECT_PROPERTY_INSTRUCTION';
     $this->ss->assign('INSTRUCTION', $this->getInstruction());
     $this->ss->assign("MODULE_TITLE", $this->getModuleTitle(false), ENT_NOQUOTES);
     $this->ss->assign("CURRENT_STEP", $this->currentStep);
     $sugar_config['import_max_records_per_file'] = empty($sugar_config['import_max_records_per_file']) ? 1000 : $sugar_config['import_max_records_per_file'];
     $importSource = isset($_REQUEST['source']) ? $_REQUEST['source'] : 'csv';
     // Clear out this user's last import
     $seedUsersLastImport = BeanFactory::getBean('Import_2');
     $seedUsersLastImport->mark_deleted_by_user_id($current_user->id);
     ImportCacheFiles::clearCacheFiles();
     // handle uploaded file
     $uploadFile = new UploadFile('userfile');
     if (isset($_FILES['userfile']) && $uploadFile->confirm_upload()) {
         $uploadFile->final_move('IMPORT_' . $this->bean->object_name . '_' . $current_user->id);
         $uploadFileName = $uploadFile->get_upload_path('IMPORT_' . $this->bean->object_name . '_' . $current_user->id);
     } elseif (!empty($_REQUEST['tmp_file'])) {
         $uploadFileName = "upload://" . basename($_REQUEST['tmp_file']);
     } else {
         $this->_showImportError($mod_strings['LBL_IMPORT_MODULE_ERROR_NO_UPLOAD'], $_REQUEST['import_module'], 'Step2', true, null, true);
         return;
     }
     //check the file size, we dont want to process an empty file
     if (isset($_FILES['userfile']['size']) && $_FILES['userfile']['size'] == 0) {
         //this file is empty, throw error message
         $this->_showImportError($mod_strings['LBL_NO_LINES'], $_REQUEST['import_module'], 'Step2', false, null, true);
         return;
     }
     $mimeTypeOk = true;
     //check to see if the file mime type is not a form of text or application octed streramand fire error if not
     if (isset($_FILES['userfile']['type']) && strpos($_FILES['userfile']['type'], 'octet-stream') === false && strpos($_FILES['userfile']['type'], 'text') === false && strpos($_FILES['userfile']['type'], 'application/vnd.ms-excel') === false) {
         //this file does not have a known text or application type of mime type, issue the warning
         $error_msgs[] = $mod_strings['LBL_MIME_TYPE_ERROR_1'];
         $error_msgs[] = $mod_strings['LBL_MIME_TYPE_ERROR_2'];
         $this->_showImportError($error_msgs, $_REQUEST['import_module'], 'Step2', true, $mod_strings['LBL_OK']);
         $mimeTypeOk = false;
     }
     $this->ss->assign("FILE_NAME", $uploadFileName);
     // Now parse the file and look for errors
     $importFile = new ImportFile($uploadFileName, $_REQUEST['custom_delimiter'], html_entity_decode($_REQUEST['custom_enclosure'], ENT_QUOTES), FALSE);
     if ($this->shouldAutoDetectProperties($importSource)) {
         $GLOBALS['log']->debug("Auto detecing csv properties...");
         $autoDetectOk = $importFile->autoDetectCSVProperties();
         $importFileMap = array();
         $this->ss->assign("SOURCE", 'csv');
         if ($autoDetectOk === FALSE) {
             //show error only if previous mime type check has passed
             if ($mimeTypeOk) {
                 $this->ss->assign("AUTO_DETECT_ERROR", $mod_strings['LBL_AUTO_DETECT_ERROR']);
             }
         } else {
             $dateFormat = $importFile->getDateFormat();
             $timeFormat = $importFile->getTimeFormat();
             if ($dateFormat) {
                 $importFileMap['importlocale_dateformat'] = $dateFormat;
             }
             if ($timeFormat) {
                 $importFileMap['importlocale_timeformat'] = $timeFormat;
             }
         }
     } else {
         $impotMapSeed = $this->getImportMap($importSource);
         $importFile->setImportFileMap($impotMapSeed);
         $importFileMap = $impotMapSeed->getMapping($_REQUEST['import_module']);
     }
     $delimeter = $importFile->getFieldDelimeter();
     $enclosure = $importFile->getFieldEnclosure();
     $hasHeader = $importFile->hasHeaderRow();
     $encodeOutput = TRUE;
     //Handle users navigating back through the wizard.
     if (!empty($_REQUEST['previous_action']) && $_REQUEST['previous_action'] == 'Confirm') {
         $encodeOutput = FALSE;
         $importFileMap = $this->overloadImportFileMapFromRequest($importFileMap);
         $delimeter = !empty($_REQUEST['custom_delimiter']) ? $_REQUEST['custom_delimiter'] : $delimeter;
         $enclosure = isset($_REQUEST['custom_enclosure']) ? $_REQUEST['custom_enclosure'] : $enclosure;
         $enclosure = html_entity_decode($enclosure, ENT_QUOTES);
         $hasHeader = !empty($_REQUEST['has_header']) ? $_REQUEST['has_header'] : $hasHeader;
         if ($hasHeader == 'on') {
             $hasHeader = true;
         } else {
             if ($hasHeader == 'off') {
                 $hasHeader = false;
             }
         }
     }
     $this->ss->assign("IMPORT_ENCLOSURE_OPTIONS", $this->getEnclosureOptions($enclosure));
     $this->ss->assign("IMPORT_DELIMETER_OPTIONS", $this->getDelimeterOptions($delimeter));
     $this->ss->assign("CUSTOM_DELIMITER", $delimeter);
     $this->ss->assign("CUSTOM_ENCLOSURE", htmlentities($enclosure, ENT_QUOTES, 'utf-8'));
     $hasHeaderFlag = $hasHeader ? " CHECKED" : "";
     $this->ss->assign("HAS_HEADER_CHECKED", $hasHeaderFlag);
     if (!$importFile->fileExists()) {
         $this->_showImportError($mod_strings['LBL_CANNOT_OPEN'], $_REQUEST['import_module'], 'Step2', false, null, true);
         return;
     }
     //Check if we will exceed the maximum number of records allowed per import.
     $maxRecordsExceeded = FALSE;
     $maxRecordsWarningMessg = "";
     $lineCount = $importFile->getNumberOfLinesInfile();
     $maxLineCount = isset($sugar_config['import_max_records_total_limit']) ? $sugar_config['import_max_records_total_limit'] : 5000;
     if (!empty($maxLineCount) && $lineCount > $maxLineCount) {
         $maxRecordsExceeded = TRUE;
         $maxRecordsWarningMessg = string_format($mod_strings['LBL_IMPORT_ERROR_MAX_REC_LIMIT_REACHED'], array($lineCount, $maxLineCount));
     }
     //Retrieve a sample set of data
     $rows = $this->getSampleSet($importFile);
     $this->ss->assign('column_count', $this->getMaxColumnsInSampleSet($rows));
     $this->ss->assign('HAS_HEADER', $importFile->hasHeaderRow(FALSE));
     $this->ss->assign('getNumberJs', $locale->getNumberJs());
     $this->setImportFileCharacterSet($importFile, $importFileMap);
     $this->setDateTimeProperties($importFileMap);
     $this->setCurrencyOptions($importFileMap);
     $this->setNumberFormatOptions($importFileMap);
     $this->setNameFormatProperties($importFileMap);
     $importMappingJS = $this->getImportMappingJS();
     $this->ss->assign("SAMPLE_ROWS", $rows);
     $JS = $this->_getJS($maxRecordsExceeded, $maxRecordsWarningMessg, $importMappingJS, $importFileMap);
     $this->ss->assign("JAVASCRIPT", $JS);
     $content = $this->ss->fetch('modules/Import/tpls/confirm.tpl');
     $this->ss->assign("CONTENT", $content);
     $this->ss->display('modules/Import/tpls/wizardWrapper.tpl');
 }
Example #23
0
 /**
  * @param  $linkName String name of a link field in the module's vardefs
  * @param  $bean SugarBean focus bean for this link (one half of a relationship)
  * @param  $linkDef Array Optional vardef for the link in case it can't be found in the passed in bean for the global dictionary
  * @return void
  *
  */
 function __construct($linkName, $bean, $linkDef = false)
 {
     $this->focus = $bean;
     //Try to load the link vardef from the beans field defs. Otherwise start searching
     if (empty($bean->field_defs) || empty($bean->field_defs[$linkName]) || empty($bean->field_defs[$linkName]['relationship'])) {
         if (empty($linkDef)) {
             //Assume $linkName is really relationship_name, and find the link name with the vardef manager
             $this->def = VardefManager::getLinkFieldForRelationship($bean->module_dir, $bean->object_name, $linkName);
         } else {
             $this->def = $linkDef;
         }
         //Check if multiple links were found for a given relationship
         if (is_array($this->def) && !isset($this->def['name'])) {
             //More than one link found, we need to figure out if we are currently on the LHS or RHS
             //default to lhs for now
             if (isset($this->def[0]['side']) && $this->def[0]['side'] == 'left') {
                 $this->def = $this->def[0];
             } else {
                 if (isset($this->def[1]['side']) && $this->def[1]['side'] == 'left') {
                     $this->def = $this->def[1];
                 } else {
                     $this->def = $this->def[0];
                 }
             }
         }
         if (empty($this->def['name'])) {
             $GLOBALS['log']->fatal("failed to find link for {$linkName}");
             return false;
         }
         $this->name = $this->def['name'];
     } else {
         //Linkdef was found in the bean (this is the normal expectation)
         $this->def = $bean->field_defs[$linkName];
         $this->name = $linkName;
     }
     //Instantiate the relationship for this link.
     $this->relationship = SugarRelationshipFactory::getInstance()->getRelationship($this->def['relationship']);
     // Fix to restore functionality from Link.php that needs to be rewritten but for now this will do.
     $this->relationship_fields = !empty($this->def['rel_fields']) ? $this->def['rel_fields'] : array();
     if (!$this->loadedSuccesfully()) {
         global $app_strings;
         $GLOBALS['log']->error(string_format($app_strings['ERR_DATABSE_RELATIONSHIP_QUERY'], array($this->name, $this->def['relationship'])));
     }
     //Following behavior is tied to a property(ignore_role) value in the vardef. It alters the values of 2 properties, ignore_role_filter and add_distinct.
     //the property values can be altered again before any requests are made.
     if (!empty($this->def) && is_array($this->def)) {
         if (isset($this->def['ignore_role'])) {
             if ($this->def['ignore_role']) {
                 $this->ignore_role_filter = true;
                 $this->add_distinct = true;
             }
         }
         if (!empty($this->def['primary_only'])) {
             $this->relationship->primaryOnly = true;
         }
     }
 }
Example #24
0
 /**
  * Given a query(method_name) and some arguments attempt to build the query
  *
  * @param string $query - the query to index
  * @param array $args
  * @return string - the query to execute
  */
 private function setup($query, $args)
 {
     if (!empty($this->queries[$query])) {
         if (empty($args[0])) {
             $args = array();
         }
         return string_format($this->queries[$query], $args);
     } else {
         return null;
     }
 }
Example #25
0
 /**
  * Method disables module in global search configurations by disabled_module_visible key
  *
  * return bool
  */
 public function disable_global_search()
 {
     if (empty($this->installdefs['beans'])) {
         return true;
     }
     if (is_file('custom/modules/unified_search_modules_display.php') == false) {
         return true;
     }
     $unified_search_modules_display = array();
     require 'custom/modules/unified_search_modules_display.php';
     foreach ($this->installdefs['beans'] as $beanDefs) {
         if (array_key_exists($beanDefs['module'], $unified_search_modules_display) == false) {
             continue;
         }
         if (isset($unified_search_modules_display[$beanDefs['module']]['visible']) == false) {
             continue;
         }
         $unified_search_modules_display[$beanDefs['module']]['disabled_module_visible'] = $unified_search_modules_display[$beanDefs['module']]['visible'];
         $unified_search_modules_display[$beanDefs['module']]['visible'] = false;
     }
     if (write_array_to_file("unified_search_modules_display", $unified_search_modules_display, 'custom/modules/unified_search_modules_display.php') == false) {
         global $app_strings;
         $msg = string_format($app_strings['ERR_FILE_WRITE'], array('custom/modules/unified_search_modules_display.php'));
         $GLOBALS['log']->error($msg);
         throw new Exception($msg);
         return false;
     }
     return true;
 }
Example #26
0
 /**
  * The fuction will returns an array of filter conditions.
  *
  */
 function generateSearchWhere($add_custom_fields = false, $module = '')
 {
     global $timedate;
     $values = $this->searchFields;
     $where_clauses = array();
     //$like_char = '%';
     $table_name = $this->bean->object_name;
     foreach ($this->searchFields as $field => $parms) {
         $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->bean->field_name_map[$field]['type']) ? $this->bean->field_name_map[$field]['type'] : '';
         if (!empty($this->bean->field_name_map[$field]['source']) && $this->bean->field_name_map[$field]['source'] == 'custom_fields') {
             $customField = true;
         }
         if ($type == 'int') {
             if (!empty($parms['value'])) {
                 $tempVal = explode(',', $parms['value']);
                 $newVal = '';
                 foreach ($tempVal as $key => $val) {
                     if (!empty($newVal)) {
                         $newVal .= ',';
                     }
                     if (!empty($val) && !is_numeric($val)) {
                         $newVal .= -1;
                     } else {
                         $newVal .= $val;
                     }
                 }
                 $parms['value'] = $newVal;
             }
         } elseif ($type == 'bool' && empty($parms['value']) && $customField) {
             continue;
         } elseif ($type == 'bool' && !empty($parms['value'])) {
             if ($parms['value'] == 'on') {
                 $parms['value'] = 1;
             }
         }
         if (isset($parms['value']) && $parms['value'] != "") {
             $operator = 'like';
             if (!empty($parms['operator'])) {
                 $operator = strtolower($parms['operator']);
             }
             if (is_array($parms['value'])) {
                 $field_value = '';
                 // If it is a custom field of multiselect we have to do some special processing
                 if ($customField && !empty($this->bean->field_name_map[$field]['isMultiSelect']) && $this->bean->field_name_map[$field]['isMultiSelect']) {
                     $operator = 'custom_enum';
                     $db_field = $this->bean->table_name . "_cstm." . $field;
                     foreach ($parms['value'] as $key => $val) {
                         if ($val != ' ' and $val != '') {
                             $qVal = $GLOBALS['db']->quote($val);
                             if (!empty($field_value)) {
                                 $field_value .= ' or ';
                             }
                             $field_value .= "{$db_field} like '{$qVal}' or {$db_field} like '%{$qVal}^%' or {$db_field} like '%^{$qVal}%' or {$db_field} like '%^{$qVal}^%'";
                         }
                     }
                 } else {
                     $operator = $operator != 'subquery' ? 'in' : $operator;
                     foreach ($parms['value'] as $key => $val) {
                         if ($val != ' ' and $val != '') {
                             if (!empty($field_value)) {
                                 $field_value .= ',';
                             }
                             $field_value .= "'" . $GLOBALS['db']->quote($val) . "'";
                         }
                     }
                 }
             } else {
                 $field_value = $GLOBALS['db']->quote($parms['value']);
             }
             //set db_fields array.
             if (!isset($parms['db_field'])) {
                 $parms['db_field'] = array($field);
             }
             if (isset($parms['my_items']) and $parms['my_items'] == true) {
                 global $current_user;
                 $field_value = $GLOBALS['db']->quote($current_user->id);
                 $operator = '=';
             }
             $where = '';
             $itr = 0;
             if ($field_value != '') {
                 foreach ($parms['db_field'] as $db_field) {
                     if (strstr($db_field, '.') === false) {
                         if (!$customField) {
                             $db_field = $this->bean->table_name . "." . $db_field;
                         } else {
                             $db_field = $this->bean->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) {
                             $db_field = $this->bean->db->convert($db_field, "date_format", "%Y-%m");
                         } else {
                             $field_value = $timedate->to_db_date($field_value, false);
                             $db_field = $this->bean->db->convert($db_field, "date_format", "%Y-%m-%d");
                         }
                     }
                     if ($type == 'datetime' || $type == 'datetimecombo') {
                         $dates = $timedate->getDayStartEndGMT($field_value);
                         $field_value = array($this->bean->db->convert($dates["start"], "datetime"), $this->bean->db->convert($dates["end"], "datetime"));
                         $operator = 'between';
                     }
                     if ($this->bean->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 ";
                     }
                     switch ($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} '{$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 {
                                 $where .= "{$db_field} {$in} ({$parms['subquery']} '{$field_value}%')";
                             }
                             break;
                         case 'like':
                             $where .= $db_field . " like " . $this->bean->db->quoted($field_value . '%');
                             break;
                         case 'in':
                             $where .= $db_field . " in (" . $field_value . ')';
                             break;
                         case '=':
                             $where .= $db_field . " = " . $this->bean->db->quoted($field_value);
                             break;
                         case 'between':
                             if (!is_array($field_value)) {
                                 $field_value = explode('<>', $field_value);
                             }
                             $where .= "(" . $db_field . " >= " . $this->bean->db->quoted($field_value[0]) . " AND " . $db_field . " <= " . $this->bean->db->quoted($field_value[1]) . ")";
                             break;
                     }
                 }
             }
             if (!empty($where)) {
                 if ($itr > 1) {
                     array_push($where_clauses, '( ' . $where . ' )');
                 } else {
                     array_push($where_clauses, $where);
                 }
             }
         }
     }
     return $where_clauses;
 }
                $functionParamsArr = $subpane['function_parameters'];
                //$panelProperty;
                //Check the array of function parameters and see if
                //one exists for market value id.
                if (isset($functionParamsArr['EMAIL_MARKETING_ID_VALUE'])) {
                    //We found the property, lets fill in the marketing id value...
                    //.. into the subpanel object, using the keys of the array that..
                    //.. we used to get to thi property
                    $subpanel->subpanel_definitions->layout_defs[$subpanels_name][$subpane_key]['function_parameters']['EMAIL_MARKETING_ID_VALUE'] = $latest_marketing_id;
                }
            }
            //end if (isset($subpane['function_parameters'])){
        }
        //end foreach($subpanels as $subpane_key => $subpane){
    }
    //_pp($subpanel->subpanel_definitions->layout_defs);
}
//end else
$deletedCampaignLogLeadsCount = $focus->getDeletedCampaignLogLeadsCount();
if ($deletedCampaignLogLeadsCount > 0) {
    $subpanel->subpanel_definitions->layout_defs['subpanel_setup']['lead']['top_buttons'][] = array('widget_class' => 'SubPanelTopMessage', 'message' => string_format($mod_strings['LBL_LEADS_DELETED_SINCE_CREATED'], array($deletedCampaignLogLeadsCount)));
}
$alltabs = $subpanel->subpanel_definitions->get_available_tabs();
if (!empty($alltabs)) {
    foreach ($alltabs as $name) {
        if ($name == 'prospectlists' || $name == 'emailmarketing' || $name == 'tracked_urls') {
            $subpanel->subpanel_definitions->exclude_tab($name);
        }
    }
}
echo $subpanel->display();
 function process($lvsParams = array())
 {
     global $current_user;
     $currentSearchFields = array();
     $configureView = true;
     // configure view or regular view
     $query = false;
     $whereArray = array();
     $lvsParams['massupdate'] = false;
     // apply filters
     if (isset($this->filters) || $this->myItemsOnly) {
         $whereArray = $this->buildWhere();
     }
     $this->lvs->export = false;
     $this->lvs->multiSelect = false;
     $this->lvs->quickViewLinks = false;
     // columns
     foreach ($this->columns as $name => $val) {
         if (!empty($val['default']) && $val['default']) {
             $displayColumns[strtoupper($name)] = $val;
             $displayColumns[strtoupper($name)]['label'] = trim($displayColumns[strtoupper($name)]['label'], ':');
         }
     }
     $this->lvs->displayColumns = $displayColumns;
     $this->lvs->lvd->setVariableName($this->seedBean->object_name, array());
     $lvsParams['overrideOrder'] = true;
     $lvsParams['orderBy'] = 'date_entered';
     $lvsParams['sortOrder'] = 'DESC';
     $lvsParams['custom_from'] = '';
     // Get the real module list
     if (empty($this->selectedCategories)) {
         $mod_list = $this->categories;
     } else {
         $mod_list = array_flip($this->selectedCategories);
         //27949, here the key of $this->selectedCategories is not module name, the value is module name, so array_flip it.
     }
     $external_modules = array();
     $admin_modules = array();
     $owner_modules = array();
     $regular_modules = array();
     foreach ($mod_list as $module => $ignore) {
         // Handle the UserFeed differently
         if ($module == 'UserFeed') {
             $regular_modules[] = 'UserFeed';
             continue;
         }
         if (in_array($module, $this->externalAPIList)) {
             $external_modules[] = $module;
         }
         if (ACLAction::getUserAccessLevel($current_user->id, $module, 'view') <= ACL_ALLOW_NONE) {
             // Not enough access to view any records, don't add it to any lists
             continue;
         }
         if (ACLAction::getUserAccessLevel($current_user->id, $module, 'view') == ACL_ALLOW_OWNER) {
             $owner_modules[] = $module;
         } else {
             $regular_modules[] = $module;
         }
     }
     if (!empty($this->displayTpl)) {
         //MFH BUG #14296
         $where = '';
         if (!empty($whereArray)) {
             $where = '(' . implode(') AND (', $whereArray) . ')';
         }
         $additional_where = '';
         $module_limiter = " sugarfeed.related_module in ('" . implode("','", $regular_modules) . "')";
         if (is_admin($GLOBALS['current_user'])) {
             $all_modules = array_merge($regular_modules, $owner_modules, $admin_modules);
             $module_limiter = " sugarfeed.related_module in ('" . implode("','", $all_modules) . "')";
         } else {
             if (count($owner_modules) > 0) {
                 $module_limiter = " ((sugarfeed.related_module IN ('" . implode("','", $regular_modules) . "') " . ") ";
                 if (count($owner_modules) > 0) {
                     $module_limiter .= "OR (sugarfeed.related_module IN('" . implode("','", $owner_modules) . "') AND sugarfeed.assigned_user_id = '" . $current_user->id . "' " . ") ";
                 }
                 $module_limiter .= ")";
             }
         }
         if (!empty($where)) {
             $where .= ' AND ';
         }
         $where .= $module_limiter;
         $this->lvs->setup($this->seedBean, $this->displayTpl, $where, $lvsParams, 0, $this->displayRows, array('name', 'description', 'date_entered', 'created_by', 'related_module', 'link_url', 'link_type'));
         foreach ($this->lvs->data['data'] as $row => $data) {
             $this->lvs->data['data'][$row]['NAME'] = str_replace("{this.CREATED_BY}", get_assigned_user_name($this->lvs->data['data'][$row]['CREATED_BY']), $data['NAME']);
             //Translate the SugarFeeds labels if necessary.
             preg_match('/\\{([^\\^ }]+)\\.([^\\}]+)\\}/', $this->lvs->data['data'][$row]['NAME'], $modStringMatches);
             if (count($modStringMatches) == 3 && $modStringMatches[1] == 'SugarFeed' && !empty($data['RELATED_MODULE'])) {
                 $modKey = $modStringMatches[2];
                 $modString = translate($modKey, $modStringMatches[1]);
                 if (strpos($modString, '{0}') === FALSE || !isset($GLOBALS['app_list_strings']['moduleListSingular'][$data['RELATED_MODULE']])) {
                     continue;
                 }
                 $modStringSingular = $GLOBALS['app_list_strings']['moduleListSingular'][$data['RELATED_MODULE']];
                 $modString = string_format($modString, array($modStringSingular));
                 $this->lvs->data['data'][$row]['NAME'] = preg_replace('/' . $modStringMatches[0] . '/', strtolower($modString), $this->lvs->data['data'][$row]['NAME']);
             }
         }
         // assign a baseURL w/ the action set as DisplayDashlet
         foreach ($this->lvs->data['pageData']['urls'] as $type => $url) {
             // awu Replacing action=DisplayDashlet with action=DynamicAction&DynamicAction=DisplayDashlet
             if ($type == 'orderBy') {
                 $this->lvs->data['pageData']['urls'][$type] = preg_replace('/(action=.*&)/Ui', 'action=DynamicAction&DynamicAction=displayDashlet&', $url);
             } else {
                 $this->lvs->data['pageData']['urls'][$type] = preg_replace('/(action=.*&)/Ui', 'action=DynamicAction&DynamicAction=displayDashlet&', $url) . '&sugar_body_only=1&id=' . $this->id;
             }
         }
         $this->lvs->ss->assign('dashletId', $this->id);
     }
     $td = $GLOBALS['timedate'];
     $needResort = false;
     $resortQueue = array();
     $feedErrors = array();
     $fetchRecordCount = $this->displayRows + $this->lvs->data['pageData']['offsets']['current'];
     foreach ($external_modules as $apiName) {
         $api = ExternalAPIFactory::loadAPI($apiName);
         if ($api !== FALSE) {
             // FIXME: Actually calculate the oldest sugar feed we can see, once we get an API that supports this sort of filter.
             $reply = $api->getLatestUpdates(0, $fetchRecordCount);
             if ($reply['success'] && count($reply['messages']) > 0) {
                 array_splice($resortQueue, count($resortQueue), 0, $reply['messages']);
             } else {
                 if (!$reply['success']) {
                     $feedErrors[] = $reply['errorMessage'];
                 }
             }
         }
     }
     if (count($feedErrors) > 0) {
         $this->lvs->ss->assign('feedErrors', $feedErrors);
     }
     // If we need to resort, get to work!
     foreach ($this->lvs->data['data'] as $normalMessage) {
         list($user_date, $user_time) = explode(' ', $normalMessage['DATE_ENTERED']);
         list($db_date, $db_time) = $td->to_db_date_time($user_date, $user_time);
         $unix_timestamp = strtotime($db_date . ' ' . $db_time);
         $normalMessage['sort_key'] = $unix_timestamp;
         $normalMessage['NAME'] = '</b>' . $normalMessage['NAME'];
         $resortQueue[] = $normalMessage;
     }
     usort($resortQueue, create_function('$a,$b', 'return $a["sort_key"]<$b["sort_key"];'));
     // Trim it down to the necessary number of records
     $numRecords = count($resortQueue);
     $numRecords = $numRecords - $this->lvs->data['pageData']['offsets']['current'];
     $numRecords = min($this->displayRows, $numRecords);
     $this->lvs->data['data'] = $resortQueue;
 }
 /**
  * Utility Method to create the filter for the filer API to use
  *
  * @param ServiceBase $api                  Service Api Class
  * @param mixed $user_id                    Passed in User ID, if false, it will use the current use from $api->user
  * @param mixed $timeperiod_id              TimePeriod Id, if false, the current time period will be found an used
  * @param string $forecast_type             Type of forecast to return, direct or rollup
  * @return array                            The Filer array to be passed back into the filerList Api
  * @throws SugarApiExceptionNotAuthorized
  * @throws SugarApiExceptionInvalidParameter
  */
 protected function createFilter(ServiceBase $api, $user_id, $timeperiod_id, $forecast_type)
 {
     $filter = array();
     // if we did not find a user in the filters array, set it to the current user's id
     if ($user_id == false) {
         // use the current user, since on one was passed in
         $user_id = $api->user->id;
     } else {
         // make sure that the passed in user is a valid user
         /* @var $user User */
         // we use retrieveBean so it will return NULL and not an empty bean if the $args['user_id'] is invalid
         $user = BeanFactory::retrieveBean('Users', $user_id);
         if (is_null($user) || is_null($user->id)) {
             throw new SugarApiExceptionInvalidParameter('Provided User is not valid');
         }
         # if they are not a manager, don't show them committed number for others
         global $mod_strings, $current_language;
         $mod_strings = return_module_language($current_language, 'Forecasts');
         if ($user_id != $api->user->id && !User::isManager($api->user->id)) {
             throw new SugarApiExceptionNotAuthorized(string_format($mod_strings['LBL_ERROR_NOT_MANAGER'], array($api->user->id, $user_id)));
         }
     }
     // set the assigned_user_id
     array_push($filter, array('user_id' => $user_id));
     if ($forecast_type !== false) {
         // make sure $forecast_type is valid (e.g. Direct or Rollup)
         switch (strtolower($forecast_type)) {
             case 'direct':
             case 'rollup':
                 break;
             default:
                 throw new SugarApiExceptionInvalidParameter('Forecast Type of ' . $forecast_type . ' is not valid. Valid options Direct or Rollup.');
         }
         // set the forecast type, make sure it's always capitalized
         array_push($filter, array('forecast_type' => ucfirst($forecast_type)));
     }
     // if we didn't find a time period, set the time period to be the current time period
     if ($timeperiod_id == false) {
         $timeperiod_id = TimePeriod::getCurrentId();
     }
     // fix up the timeperiod filter
     /* @var $tp TimePeriod */
     // we use retrieveBean so it will return NULL and not an empty bean if the $args['timeperiod_id'] is invalid
     $tp = BeanFactory::retrieveBean('TimePeriods', $timeperiod_id);
     if (is_null($tp) || is_null($tp->id)) {
         throw new SugarApiExceptionInvalidParameter('Provided TimePeriod is not valid');
     }
     array_push($filter, array('timeperiod_id' => $tp->id));
     return $filter;
 }
Example #30
0
 /**
  * checkDatabaseVersion
  * Check the db version sugar_version.php and compare to what the version is stored in the config table.
  * Ensure that both are the same.
  */
 function checkDatabaseVersion($dieOnFailure = true)
 {
     $row_count = sugar_cache_retrieve('checkDatabaseVersion_row_count');
     if (empty($row_count)) {
         $version_query = "SELECT count(*) as the_count FROM config WHERE category='info' AND name='sugar_version' AND " . $GLOBALS['db']->convert('value', 'text2char') . " = " . $GLOBALS['db']->quoted($GLOBALS['sugar_db_version']);
         $result = $GLOBALS['db']->query($version_query);
         $row = $GLOBALS['db']->fetchByAssoc($result);
         $row_count = $row['the_count'];
         sugar_cache_put('checkDatabaseVersion_row_count', $row_count);
     }
     if ($row_count == 0 && empty($GLOBALS['sugar_config']['disc_client'])) {
         if ($dieOnFailure) {
             $replacementStrings = array(0 => $GLOBALS['sugar_version'], 1 => $GLOBALS['sugar_db_version']);
             sugar_die(string_format($GLOBALS['app_strings']['ERR_DB_VERSION'], $replacementStrings));
         } else {
             return false;
         }
     }
     return true;
 }