/**
  * checks the request for the order by and if that is not set then it checks the session for it
  *
  * @return array containing the keys orderBy => field being ordered off of and sortOrder => the sort order of that field
  */
 function getOrderBy($orderBy = '', $direction = '')
 {
     if (!empty($orderBy) || !empty($_REQUEST[$this->var_order_by])) {
         if (!empty($_REQUEST[$this->var_order_by])) {
             $direction = 'ASC';
             $orderBy = $_REQUEST[$this->var_order_by];
             if (!empty($_REQUEST['lvso']) && (empty($_SESSION['lvd']['last_ob']) || strcmp($orderBy, $_SESSION['lvd']['last_ob']) == 0)) {
                 $direction = $_REQUEST['lvso'];
                 $trackerManager = TrackerManager::getInstance();
                 if ($monitor = $trackerManager->getMonitor('tracker')) {
                     $monitor->setValue('module_name', $GLOBALS['module']);
                     $monitor->setValue('item_summary', "lvso=" . $direction . "&" . $this->var_order_by . "=" . $_REQUEST[$this->var_order_by]);
                     $monitor->setValue('action', 'listview');
                     $monitor->setValue('user_id', $GLOBALS['current_user']->id);
                     $monitor->setValue('date_modified', TimeDate::getInstance()->nowDb());
                     $monitor->save();
                 }
             }
         }
         $_SESSION[$this->var_order_by] = array('orderBy' => $orderBy, 'direction' => $direction);
         $_SESSION['lvd']['last_ob'] = $orderBy;
     } else {
         if (!empty($_SESSION[$this->var_order_by])) {
             $orderBy = $_SESSION[$this->var_order_by]['orderBy'];
             $direction = $_SESSION[$this->var_order_by]['direction'];
         } else {
             $orderBy = 'date_entered';
             $direction = 'DESC';
         }
     }
     return array('orderBy' => $orderBy, 'sortOrder' => $direction);
 }
Exemplo n.º 2
0
 public function setUp()
 {
     $this->scheduler = new TestScheduler(false);
     $GLOBALS['timedate'] = $this->timedate = TimeDate::getInstance();
     $this->timedate->allow_cache = true;
     $this->now = $this->timedate->getNow();
 }
 public function ejecutar($focus, $string_parametros)
 {
     $this->procesar_parametros($string_parametros);
     $alarma = loadBean('gcoop_alarmas');
     $alarma->parent_type = $focus->module_dir;
     $alarma->parent_id = $focus->id;
     $alarma->destinatario = $this->destinatario;
     $alarma->notificacion = $this->notificacion;
     $alarma->parametro = $this->parametro;
     $alarma->valor = $this->valor;
     #sumarle dias no fin de semana!
     $fecha = new DateTime();
     $dia = new DateInterval('P1D');
     while ($this->cantidad_dias > 0) {
         $fecha->add($dia);
         if ($fecha->format('N') < 6) {
             $this->cantidad_dias -= 1;
         }
     }
     $timedate = TimeDate::getInstance();
     $alarma->fecha_disparo = $timedate->asDb($fecha);
     $alarma->save();
     if (method_exists($focus, 'notificar')) {
         $focus->notificar("Se creó alarama con fecha de disparo {$alarma->fecha_disparo}", 'Alarma');
     }
 }
 /**
  * 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;
 }
Exemplo n.º 5
0
    protected function generateItem($item)
    {
        $name = !empty($item['name_value_list']['name']['value']) ? htmlentities($item['name_value_list']['name']['value']) : '';
        $url = $GLOBALS['sugar_config']['site_url'] . htmlentities('/index.php?module=' . $item['module_name'] . '&action=DetailView&record=' . $item['id']);
        $date = TimeDate::httpTime(TimeDate::getInstance()->fromDb($item['name_value_list']['date_modified']['value'])->getTimestamp());
        $description = '';
        $displayFieldNames = true;
        if (count($item['name_value_list']) == 2 && isset($item['name_value_list']['name'])) {
            $displayFieldNames = false;
        }
        foreach ($item['name_value_list'] as $k => $v) {
            if ($k == 'name' || $k == 'date_modified') {
                continue;
            }
            if ($displayFieldNames) {
                $description .= '<b>' . htmlentities($k) . ':<b>&nbsp;';
            }
            $description .= htmlentities($v['value']) . "<br>";
        }
        echo <<<EORSS
    <item>
        <title>{$name}</title>
        <link>{$url}</link>
        <description><![CDATA[{$description}]]></description>
        <pubDate>{$date} GMT</pubDate>
        <guid>{$item['id']}</guid>
    </item>

EORSS;
    }
Exemplo n.º 6
0
 public function getAgenda($api, $args)
 {
     // Fetch the next 14 days worth of meetings (limited to 20)
     $end_time = new SugarDateTime("+14 days");
     $start_time = new SugarDateTime("-1 hour");
     $meeting = BeanFactory::newBean('Meetings');
     $meetingList = $meeting->get_list('date_start', "date_start > " . $GLOBALS['db']->convert($GLOBALS['db']->quoted($start_time->asDb()), 'datetime') . " AND date_start < " . $GLOBALS['db']->convert($GLOBALS['db']->quoted($end_time->asDb()), 'datetime'));
     // Setup the breaks for the various time periods
     $datetime = new SugarDateTime();
     $today_stamp = $datetime->get_day_end()->getTimestamp();
     $tomorrow_stamp = $datetime->setDate($datetime->year, $datetime->month, $datetime->day + 1)->get_day_end()->getTimestamp();
     $timeDate = TimeDate::getInstance();
     $returnedMeetings = array('today' => array(), 'tomorrow' => array(), 'upcoming' => array());
     foreach ($meetingList['list'] as $meetingBean) {
         $meetingStamp = $timeDate->fromUser($meetingBean->date_start)->getTimestamp();
         $meetingData = $this->formatBean($api, $args, $meetingBean);
         if ($meetingStamp < $today_stamp) {
             $returnedMeetings['today'][] = $meetingData;
         } else {
             if ($meetingStamp < $tomorrow_stamp) {
                 $returnedMeetings['tomorrow'][] = $meetingData;
             } else {
                 $returnedMeetings['upcoming'][] = $meetingData;
             }
         }
     }
     return $returnedMeetings;
 }
 public function tearDown()
 {
     SugarTestUserUtilities::removeAllCreatedAnonymousUsers();
     unset($GLOBALS['current_user']);
     unset($GLOBALS['app_list_strings']);
     unset($GLOBALS['beanList']);
     $GLOBALS['timedate'] = TimeDate::getInstance();
 }
Exemplo n.º 8
0
 public function setUp()
 {
     $this->sugarWidgetField = new SugarWidgetFieldDateTime48616Mock(new LayoutManager());
     global $current_user, $timedate;
     $timedate = TimeDate::getInstance();
     $current_user = SugarTestUserUtilities::createAnonymousUser();
     //$this->setOutputBuffering = false;
 }
 public function setUp()
 {
     global $timedate, $current_user;
     $timedate = TimeDate::getInstance();
     require 'include/modules.php';
     $GLOBALS['beanList'] = $beanList;
     $GLOBALS['beanFiles'] = $beanFiles;
     $current_user = SugarTestUserUtilities::createAnonymousUser();
     $this->nowTime = $timedate->asDb($timedate->getNow()->get("-10 minutes"));
     $this->tenMinutesLaterTime = $timedate->asDb($timedate->getNow()->get("+10 minutes"));
     $current_user->is_admin = 1;
     $current_user->save();
     $this->meeting = SugarTestMeetingUtilities::createMeeting();
     $this->meeting->team_id = $current_user->team_id;
     $this->meeting->team_set_id = $current_user->team_set_id;
     $this->meeting->team_id = $current_user->team_id;
     $this->meeting->team_set_id = $current_user->team_set_id;
     $this->meeting->assigned_user_id = $current_user->id;
     $this->meeting->save();
     $this->meeting->load_relationship('users');
     $this->meeting->users->add($current_user);
     $this->call = SugarTestCallUtilities::createCall();
     $this->call->team_id = $current_user->team_id;
     $this->call->team_set_id = $current_user->team_set_id;
     $this->call->assigned_user_id = $current_user->id;
     $this->call->save();
     $this->call->load_relationships('users');
     $this->call->users->add($current_user);
     $this->contact = SugarTestContactUtilities::createContact();
     $this->contact->email1 = '*****@*****.**';
     $this->contact->contacts_users_id = $current_user->id;
     $this->contact->load_relationship('user_sync');
     $this->contact->user_sync->add($current_user);
     $this->contact->sync_contact = 1;
     $this->contact->save();
     $this->task = SugarTestTaskUtilities::createTask();
     $this->task->assigned_user_id = $current_user->id;
     $this->task->team_id = $current_user->id;
     $this->task->team_set_id = $current_user->id;
     $this->task->save();
     //$this->useOutputBuffering = false;
     /**
      * This provider returns an Array of Array data.  Each Array contains the following data
      * 0 => String - Left side module name
      * 1 => String - Right side module name
      * 2 => String - Relationship Query
      * 3 => boolean to return deleted records or not (this is actually ignored by the function)
      * 4 => integer offset to start with
      * 5 => integer value for the maximum number of results
      * 6 => array of fields to select and return
      * 7 => load_relationships - Relationship name to use
      * 8 => array of expected results
      * 9 => integer of expected total count
      * 10 => array of expected soap error
      * @return array The provider array
      */
     $this->testData = array(array('Users', 'Meetings', "( (m1.date_modified > '{$this->nowTime}' AND m1.date_modified <= '{$this->tenMinutesLaterTime}' AND m1.deleted = 0) OR (m1.date_modified > '{$this->nowTime}' AND m1.date_modified <= '{$this->tenMinutesLaterTime}' AND m1.deleted = 1) AND m1.id IN ('{$this->meeting->id}')) OR (m1.id NOT IN ('{$this->meeting->id}') AND m1.deleted = 0) AND m2.id = '{$current_user->id}'", 0, 0, 3000, $this->callsAndMeetingsSelectFields, 'meetings_users', array('id' => $this->meeting->id), 1, $this->noSoapErrorArray), array('Users', 'Calls', "( m1.deleted = 0) AND m2.id = '{$current_user->id}'", 0, 0, 3000, $this->callsAndMeetingsSelectFields, 'calls_users', array('id' => $this->call->id), 1, $this->noSoapErrorArray), array('Users', 'Contacts', "( (m1.date_modified > '{$this->nowTime}' AND m1.date_modified <= '{$this->tenMinutesLaterTime}' AND {0}.deleted = 0) OR ({0}.date_modified > '{$this->nowTime}' AND {0}.date_modified <= '{$this->tenMinutesLaterTime}' AND {0}.deleted = 1) AND m1.id IN ('31a219bd-b9c1-2c3e-aa5d-4f2778ab0347','c794bc39-e4fb-f515-f1d5-4f285ca88965','d51a0555-8f84-9e62-0fbc-4f2787b5d839','a1219ae6-5a6b-0d1b-c49f-4f2854bc2912')) OR (m1.id NOT IN ('31a219bd-b9c1-2c3e-aa5d-4f2778ab0347','c794bc39-e4fb-f515-f1d5-4f285ca88965','d51a0555-8f84-9e62-0fbc-4f2787b5d839','a1219ae6-5a6b-0d1b-c49f-4f2854bc2912') AND {0}.deleted = 0) AND m2.id = '1'", 0, 0, 3000, $this->contactsSelectFields, 'contacts_users', array('id' => $this->contact->id, 'email1' => '*****@*****.**'), 1, $this->noSoapErrorArray), array('Users', 'Tasks', " ( (m1.date_modified > '{$this->nowTime}' AND m1.date_modified <= '{$this->tenMinutesLaterTime}' AND {0}.deleted = 0) OR ({0}.date_modified > '{$this->nowTime}' AND {0}.date_modified <= '{$this->tenMinutesLaterTime}' AND {0}.deleted = 1) AND m1.id IN ('{$this->task->id}')) OR (m1.id NOT IN ('{$this->task->id}') AND {0}.deleted = 0) AND m2.id = '1'", 0, 0, 3000, $this->tasksSelectFields, 'tasks_assigned_user', array('id' => $this->task->id), 1, $this->noSoapErrorArray));
 }
Exemplo n.º 10
0
 /**
  * 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')));
 }
Exemplo n.º 11
0
 /**
  * @dataProvider providerCorrectNextMonth
  * @outputBuffering disabled
  */
 public function testCorrectNextMonth($testDate, $direction, $expectedString)
 {
     global $timedate;
     $timedate = TimeDate::getInstance();
     $this->calendar = new Calendar('month');
     $this->calendar->date_time = $timedate->fromString($testDate);
     $uri = $this->calendar->get_neighbor_date_str($direction);
     $this->assertContains($expectedString, $uri, "Failed to get {$direction} expected URL: {$expectedString} from date: {$testDate}");
 }
Exemplo n.º 12
0
 function Common()
 {
     global $db;
     $this->db = $db;
     if (empty($this->db)) {
         $this->db = DBManagerFactory::getInstance();
     }
     $this->timedate = TimeDate::getInstance();
 }
Exemplo n.º 13
0
 /**
  * Returns number of hours from now until the specified date.
  */
 public function evaluate()
 {
     $params = DateExpression::parse($this->getParameters()->evaluate());
     if (!$params) {
         return false;
     }
     $now = TimeDate::getInstance()->getNow(true);
     $tsdiff = $params->ts - $now->ts;
     return (int) ($tsdiff / 3600);
 }
Exemplo n.º 14
0
 public function setUp()
 {
     $this->sugarWidgetField = new SugarWidgetFieldDateTime49008Mock(new LayoutManager());
     global $current_user, $timedate;
     $timedate = TimeDate::getInstance();
     $current_user = SugarTestUserUtilities::createAnonymousUser();
     $current_user->setPreference('timezone', 'America/Los_Angeles');
     $current_user->save();
     $current_user->db->commit();
 }
Exemplo n.º 15
0
 /**
  * Handles export field sanitizing for field type
  *
  * @param $value string value to be sanitized
  * @param $vardef array representing the vardef definition
  * @param $focus SugarBean object
  * @param $row Array of a row of data to be exported
  *
  * @return string sanitized value
  */
 public function exportSanitize($value, $vardef, $focus, $row = array())
 {
     $timedate = TimeDate::getInstance();
     $db = DBManagerFactory::getInstance();
     //If it's in ISO format, convert it to db format
     if (preg_match('/(\\d{4})\\-?(\\d{2})\\-?(\\d{2})T(\\d{2}):?(\\d{2}):?(\\d{2})\\.?\\d*([Z+-]?)(\\d{0,2}):?(\\d{0,2})/i', $value)) {
         $value = $timedate->fromIso($value)->asDbDate(false);
     }
     return $timedate->to_display_date($db->fromConvert($value, 'date'), false);
 }
Exemplo n.º 16
0
 public function run()
 {
     if (!($this->from_flavor == 'ce' && $this->toFlavor('pro'))) {
         return;
     }
     $system = new System();
     $system->system_key = $this->config['unique_key'];
     $system->user_id = '1';
     $system->last_connect_date = TimeDate::getInstance()->nowDb();
     $system_id = $system->retrieveNextKey(false, true);
     $this->db->query("INSERT INTO config (category, name, value) VALUES ( 'system', 'system_id', '" . $system_id . "')");
 }
 public function evaluate()
 {
     $params = $this->getParameters();
     //This should be of relate type, which means an array of SugarBean objects
     $linkField = $params[0]->evaluate();
     $relfield = $params[1]->evaluate();
     $ret = 0;
     $isTimestamp = true;
     //if the field or relationship isn't defined, bail
     if (!is_array($linkField) || empty($linkField)) {
         return $ret;
     }
     foreach ($linkField as $bean) {
         // we have to use the fetched_row as it's still in db format
         // where as the $bean->$relfield is formatted into the users format.
         if (isset($bean->fetched_row[$relfield])) {
             $value = $bean->fetched_row[$relfield];
         } elseif (isset($bean->{$relfield})) {
             if (is_int($bean->{$relfield})) {
                 // if we have a timestamp field, just set the value
                 $value = $bean->relfield;
             } else {
                 // more than likely this is a date field, so try and un-format based on the users preferences
                 $td = TimeDate::getInstance();
                 // we pass false to asDbDate as we want the value that would be stored in the DB
                 $value = $td->fromString($bean->{$relfield})->asDbDate(false);
             }
         } else {
             continue;
         }
         //if it isn't a timestamp, mark the flag as such and convert it for comparison
         if (!is_int($value)) {
             $isTimestamp = false;
             $value = strtotime($value);
         }
         //compare
         if ($ret < $value) {
             $ret = $value;
         }
     }
     //if nothing was done, return an empty string
     if ($ret == 0 && $isTimestamp) {
         return "";
     }
     //return the timestamp if the field started off that way
     if ($isTimestamp) {
         return $ret;
     }
     //convert the timestamp to a date and return
     $date = new DateTime();
     $date->setTimestamp($ret);
     return $date->format("Y-m-d");
 }
Exemplo n.º 18
0
 public function setUp()
 {
     $this->markTestIncomplete('Need to wrap this up later... too tired');
     $this->sugarWidgetField = new SugarWidgetFieldDateTime49008Mock(new LayoutManager());
     global $current_user, $timedate;
     $timedate = TimeDate::getInstance();
     $current_user = SugarTestUserUtilities::createAnonymousUser();
     $current_user->setPreference('timezone', 'America/Los_Angeles');
     $current_user->save();
     $current_user->db->commit();
     $this->setOutputBuffering = false;
 }
 /**
  * Track a view for a particular bean.
  *
  * @param SugarBean $seed
  * @param string $current_view
  */
 function trackView($seed, $current_view)
 {
     $trackerManager = TrackerManager::getInstance();
     if ($monitor = $trackerManager->getMonitor('tracker')) {
         $monitor->setValue('date_modified', TimeDate::getInstance()->nowDb());
         $monitor->setValue('user_id', $GLOBALS['current_user']->id);
         $monitor->setValue('module_name', $seed->module_dir);
         $monitor->setValue('action', $current_view);
         $monitor->setValue('item_id', $seed->id);
         $monitor->setValue('item_summary', $seed->get_summary_text());
         $monitor->setValue('visible', true);
         $trackerManager->saveMonitor($monitor, TRUE, TRUE);
     }
 }
Exemplo n.º 20
0
 /**
  * Returns the entire enumeration bare.
  */
 function evaluate()
 {
     $params = DateExpression::parse($this->getParameters()->evaluate());
     if (!$params) {
         return false;
     }
     $now = TimeDate::getInstance()->getNow(true);
     //set the time to 0, as we are returning an integer based on the date.
     $params->setTime(0, 0, 0);
     // this will be the timestamp delimiter of the day.
     $tsdiff = $params->ts - $now->ts;
     $diff = (int) ceil($tsdiff / 86400);
     return $diff;
 }
Exemplo n.º 21
0
 public function testDateAndTimeShownInCalendarActivityAdditionalDetailsPopup()
 {
     global $timedate, $sugar_config, $DO_USER_TIME_OFFSET, $current_user;
     $DO_USER_TIME_OFFSET = true;
     $timedate = TimeDate::getInstance();
     $meeting = new Meeting();
     $format = $current_user->getUserDateTimePreferences();
     $meeting->date_start = $timedate->swap_formats("2006-12-23 11:00pm", 'Y-m-d h:ia', $format['date'] . ' ' . $format['time']);
     $meeting->time_start = "";
     $meeting->object_name = "Meeting";
     $meeting->duration_hours = 2;
     $ca = new CalendarActivity($meeting);
     $this->assertEquals($meeting->date_start, $ca->sugar_bean->date_start);
 }
 public function run()
 {
     $this->log('Updating TimePeriod TimeStamp fields');
     $sql = "select id, start_date, end_date from timeperiods";
     $results = $this->db->query($sql);
     $dt = TimeDate::getInstance();
     $dt->setAlwaysDb(true);
     $updateSql = "UPDATE timeperiods SET start_date_timestamp = '%d', end_date_timestamp = '%d' where id = '%s'";
     while ($row = $this->db->fetchRow($results)) {
         $this->db->query(sprintf($updateSql, strtotime(substr($row['start_date'], 0, 10) . ' 00:00:00'), strtotime(substr($row['end_date'], 0, 10) . ' 23:59:59'), $row['id']));
     }
     $dt->setAlwaysDb(false);
     $this->log('Done Updating TimePeriod TimeStamp fields');
 }
Exemplo n.º 23
0
 /**
  * To perform mass delete
  * @param $api ServiceBase The API class of the request, used in cases where the API changes how the fields are pulled from the args array.
  * @param $args array The arguments array passed in from the API
  * @return String
  */
 public function massDelete($api, $args)
 {
     $this->requireArgs($args, array('massupdate_params', 'module'));
     $this->delete = true;
     $args['massupdate_params']['Delete'] = true;
     // SC-1021: add 'creation date' filter if 'delete all'
     if (!empty($args['massupdate_params']['entire'])) {
         unset($args['massupdate_params']['uid']);
         if (empty($args['massupdate_params']['filter'])) {
             $args['massupdate_params']['filter'] = array();
         }
         $args['massupdate_params']['filter'][] = array('date_entered' => array('$lt' => TimeDate::getInstance()->getNow(true)));
     }
     return $this->massUpdate($api, $args);
 }
Exemplo n.º 24
0
 public function display()
 {
     $data = array();
     $ss = new Sugar_Smarty();
     $focus = BeanFactory::getBean('TeamNotices');
     $today = db_convert("'" . TimeDate::getInstance()->nowDbDate() . "'", 'date');
     $query = $focus->create_new_list_query("date_start", $focus->table_name . ".date_start <= {$today} and " . $focus->table_name . ".date_end >= {$today} and " . $focus->table_name . '.status=\'Visible\'');
     if ($result = $focus->db->query($query)) {
         while ($row = $focus->db->fetchByAssoc($result)) {
             $data[] = $row;
         }
     }
     $ss->assign("data", $data);
     return parent::display() . $ss->fetch('modules/TeamNotices/Dashlets/TeamNoticesDashlet/TeamNoticesDashlet.tpl');
 }
Exemplo n.º 25
0
 public function testRelationshipSave()
 {
     $timedate = TimeDate::getInstance();
     $unid = uniqid();
     $project = new Project();
     $project->id = 'p_' . $unid;
     $project->name = 'test project ' . $unid;
     $project->estimated_start_date = $timedate->nowDate();
     $project->estimated_end_date = $timedate->asUserDate($timedate->getNow(true)->modify("+7 days"));
     $project->new_with_id = true;
     $project->disable_custom_fields = true;
     $newProjectId = $project->save();
     $this->project = $project;
     $savedProjectId = $GLOBALS['db']->getOne("\n                                SELECT project_id FROM projects_accounts\n                                WHERE project_id= '{$newProjectId}'\n                                AND account_id='{$this->account->id}'");
     $this->assertEquals($newProjectId, $savedProjectId);
 }
Exemplo n.º 26
0
 public function testCallAppearsWithinMonthView()
 {
     global $timedate, $sugar_config, $DO_USER_TIME_OFFSET, $current_user;
     $DO_USER_TIME_OFFSET = true;
     $timedate = TimeDate::getInstance();
     $format = $current_user->getUserDateTimePreferences();
     $name = 'Bug37953Test' . $timedate->nowDb();
     $this->call->name = $name;
     $this->call->date_start = $timedate->swap_formats("2011-09-29 11:00pm", 'Y-m-d h:ia', $format['date'] . ' ' . $format['time']);
     $this->call->time_start = "";
     $this->call->object_name = "Call";
     $this->call->duration_hours = 99;
     $ca = new CalendarActivity($this->call);
     $where = $ca->get_occurs_within_where_clause($this->call->table_name, $this->call->rel_users_table, $ca->start_time, $ca->end_time, 'date_start', 'month');
     $this->assertRegExp('/2011\\-09\\-23 00:00:00/', $where, 'Assert that we go back 6 days from the date_start value');
     $this->assertRegExp('/2011\\-11\\-01 00:00:00/', $where, 'Assert that we go to the end of next month');
 }
Exemplo n.º 27
0
 /**
  * This method prepares the response of the current element based on the
  * $bean object and the $flowData, an external action such as
  * ROUTE or ADHOC_REASSIGN could be also processed.
  *
  * This method probably should be override for each new element, but it's
  * not mandatory. However the response structure always must pass using
  * the 'prepareResponse' Method.
  *
  * As defined in the example:
  *
  * $response['route_action'] = 'ROUTE'; //The action that should process the Router
  * $response['flow_action'] = 'CREATE'; //The record action that should process the router
  * $response['flow_data'] = $flowData; //The current flowData
  * $response['flow_filters'] = array('first_id', 'second_id'); //This attribute is used to filter the execution of the following elements
  * $response['flow_id'] = $flowData['id']; // The flowData id if present
  *
  *
  * @param type $flowData
  * @param type $bean
  * @param type $externalAction
  * @return type
  */
 public function run($flowData, $bean, $externalAction = '', $arguments = array())
 {
     if (empty($externalAction)) {
         $eventDefinition = $this->retrieveDefinitionData($flowData['bpmn_id']);
         $flowData['cas_flow_status'] = 'SLEEPING';
         $eventCriteria = json_decode(html_entity_decode($eventDefinition['evn_criteria']));
         if (!is_array($eventCriteria)) {
             if (!empty($eventDefinition['evn_criteria'])) {
                 $date = TimeDate::getInstance()->getNow();
                 $date = PMSEEngineUtils::addDateInterval($date, $eventDefinition['evn_criteria'], $eventDefinition['evn_params']);
                 $flowData['cas_due_date'] = $date->asDb();
             } else {
                 throw new PMSEElementException('The TimeEvent probably doesn\'t have any configuration', $flowData, $this);
             }
             //$this->bpmLog('INFO', "[$cas_id][$newCasIndex] schedule a timer event for $dueDate");
         } else {
             $moduleName = $flowData['cas_sugar_module'];
             $object_id = $flowData['cas_sugar_object_id'];
             $bean = $this->caseFlowHandler->retrieveBean($moduleName, $object_id);
             $dueDate = $this->evaluator->evaluateExpression($eventDefinition['evn_criteria'], $bean);
             $date = TimeDate::getInstance()->fromIso($dueDate);
             $dateDB = $date->asDb();
             $flowData['cas_delegate_date'] = $dateDB;
             $flowData['cas_due_date'] = $dateDB;
             //$this->bpmLog('INFO', "[$cas_id][$newCasIndex] schedule a timer event for $dueDate");
         }
         $result = $this->prepareResponse($flowData, 'SLEEP', 'CREATE');
     } else {
         /*$flowDueDate = new DateTime($flowData['cas_due_date']);
                     $casDueDate = $flowDueDate->getTimestamp();
                     $evaluatedCondition = $this->getCurrentTime() > $casDueDate;
         
                     if ($evaluatedCondition) {*/
         $isEventBased = $this->checkIfUsesAnEventBasedGateway($flowData['cas_id'], $flowData['cas_previous']);
         $this->checkIfExistEventBased($flowData['cas_id'], $flowData['cas_previous'], $isEventBased);
         $result = $this->prepareResponse($flowData, 'ROUTE', 'UPDATE');
         /*} else {
               $result = $this->prepareResponse($flowData, 'SLEEP', 'NONE');
           }*/
     }
     return $result;
 }
Exemplo n.º 28
0
 /**
  * Collect up the timeperiod data
  *
  * @return array
  * @throws SugarQueryException
  */
 private function getCurrentTimePeriod()
 {
     $admin = BeanFactory::getBean('Administration');
     $settings = $admin->getConfigForModule('Forecasts', 'base');
     $forward = $settings['timeperiod_shown_forward'];
     $backward = $settings['timeperiod_shown_backward'];
     $type = $settings['timeperiod_interval'];
     $leafType = $settings['timeperiod_leaf_interval'];
     $timeDate = TimeDate::getInstance();
     $timePeriods = array();
     $current = TimePeriod::getCurrentTimePeriod($type);
     //If the current TimePeriod cannot be found for the type, just create one using the current date as a reference point
     if (empty($current)) {
         $current = TimePeriod::getByType($type);
         $current->setStartDate($timeDate->getNow()->asDbDate());
     }
     $startDate = $timeDate->fromDbDate($current->start_date);
     //Move back for the number of backward TimePeriod(s)
     while ($backward-- > 0) {
         $startDate->modify($current->previous_date_modifier);
     }
     $endDate = $timeDate->fromDbDate($current->end_date);
     //Increment for the number of forward TimePeriod(s)
     while ($forward-- > 0) {
         $endDate->modify($current->next_date_modifier);
     }
     $db = DBManagerFactory::getInstance();
     $sq = new SugarQuery();
     $sq->from(BeanFactory::getBean('TimePeriods'));
     $sq->select(array('id', 'name'));
     $sq->where()->notNull('parent_id')->gte('start_date', $startDate->asDbDate())->lte('start_date', $endDate->asDbDate())->addRaw("coalesce({$db->convert('type', 'length')},0) > 0");
     $sq->orderBy('start_date', 'ASC');
     $beans = $sq->execute();
     //I am gather all of these as I might have to update more than one time period in the future
     foreach ($beans as $row) {
         $timePeriods['list'][$row['id']] = $row;
     }
     //the one is the current time period
     $current = TimePeriod::getCurrentTimePeriod();
     $timePeriods['current'] = $current->id;
     return $timePeriods;
 }
Exemplo n.º 29
0
 function flushStaleEntries($bean, $event, $arguments)
 {
     $admin = new Administration();
     $admin->retrieveSettings();
     $timedate = TimeDate::getInstance();
     $currDate = $timedate->nowDbDate();
     if (isset($admin->settings['sugarfeed_flushdate']) && $admin->settings['sugarfeed_flushdate'] != $currDate) {
         global $db;
         if (!isset($db)) {
             $db = DBManagerFactory::getInstance();
         }
         $tmpTime = time();
         $tmpSF = new SugarFeed();
         $flushBefore = $timedate->asDbDate($timedate->getNow()->modify("-14 days")->setTime(0, 0));
         $db->query("DELETE FROM " . $tmpSF->table_name . " WHERE date_entered < '" . $db->quote($flushBefore) . "'");
         $admin->saveSetting('sugarfeed', 'flushdate', $currDate);
         // Flush the cache
         $admin->retrieveSettings(FALSE, TRUE);
     }
 }
function UWrebuild()
{
    global $db;
    Log::info('Deleting Relationship Cache. Relationships will automatically refresh.');
    echo "\n\t<div id='rrresult'></div>\n\t<script>\n\t\tvar xmlhttp=false;\n\t\t/*@cc_on @*/\n\t\t/*@if (@_jscript_version >= 5)\n\t\t// JScript gives us Conditional compilation, we can cope with old IE versions.\n\t\t// and security blocked creation of the objects.\n\t\t try {\n\t\t  xmlhttp = new ActiveXObject(\"Msxml2.XMLHTTP\");\n\t\t } catch (e) {\n\t\t  try {\n\t\t   xmlhttp = new ActiveXObject(\"Microsoft.XMLHTTP\");\n\t\t  } catch (E) {\n\t\t   xmlhttp = false;\n\t\t  }\n\t\t }\n\t\t@end @*/\n\t\tif (!xmlhttp && typeof XMLHttpRequest!='undefined') {\n\t\t\ttry {\n\t\t\t\txmlhttp = new XMLHttpRequest();\n\t\t\t} catch (e) {\n\t\t\t\txmlhttp = false;\n\t\t\t}\n\t\t}\n\t\tif (!xmlhttp && window.createRequest) {\n\t\t\ttry {\n\t\t\t\txmlhttp = window.createRequest();\n\t\t\t} catch (e) {\n\t\t\t\txmlhttp = false;\n\t\t\t}\n\t\t}\n\t\txmlhttp.onreadystatechange = function() {\n\t\t            if(xmlhttp.readyState == 4) {\n\t\t              document.getElementById('rrresult').innerHTML = xmlhttp.responseText;\n\t\t            }\n\t\t          }\n\t\txmlhttp.open('GET', 'index.php?module=Administration&action=RebuildRelationship&to_pdf=true', true);\n\t\txmlhttp.send(null);\n\t\t</script>";
    Log::info('Rebuilding everything.');
    require_once 'ModuleInstall/ModuleInstaller.php';
    $mi = new ModuleInstaller();
    $mi->rebuild_all();
    $query = "DELETE FROM versions WHERE name='Rebuild Extensions'";
    Log::info($query);
    $db->query($query);
    // insert a new database row to show the rebuild extensions is done
    $id = create_guid();
    $gmdate = TimeDate::getInstance()->nowDb();
    $date_entered = db_convert("'{$gmdate}'", 'datetime');
    $query = 'INSERT INTO versions (id, deleted, date_entered, date_modified, modified_user_id, created_by, name, file_version, db_version) ' . "VALUES ('{$id}', '0', {$date_entered}, {$date_entered}, '1', '1', 'Rebuild Extensions', '4.0.0', '4.0.0')";
    Log::info($query);
    $db->query($query);
}