/**
  * Fetch the next job in the queue and mark it running
  * @param string $clientID ID of the client requesting the job
  * @return SugarJob
  */
 public function nextJob($clientID)
 {
     $now = $this->db->now();
     $queued = SchedulersJob::JOB_STATUS_QUEUED;
     $try = $this->jobTries;
     while ($try--) {
         // TODO: tranaction start?
         $id = $this->db->getOne("SELECT id FROM {$this->job_queue_table} WHERE execute_time <= {$now} AND status = '{$queued}' ORDER BY date_entered ASC");
         if (empty($id)) {
             return null;
         }
         $job = new SchedulersJob();
         $job->retrieve($id);
         if (empty($job->id)) {
             return null;
         }
         $job->status = SchedulersJob::JOB_STATUS_RUNNING;
         $job->client = $clientID;
         $client = $this->db->quote($clientID);
         // using direct query here to be able to fetch affected count
         // if count is 0 this means somebody changed the job status and we have to try again
         $res = $this->db->query("UPDATE {$this->job_queue_table} SET status='{$job->status}', date_modified={$now}, client='{$client}' WHERE id='{$job->id}' AND status='{$queued}'");
         if ($this->db->getAffectedRowCount($res) == 0) {
             // somebody stole our job, try again
             continue;
         } else {
             // to update dates & possible hooks
             $job->save();
             break;
         }
         // TODO: commit/check?
     }
     return $job;
 }
 /**
  * Returns Latest tracker id dictionary
  *
  * @return array
  */
 public function getLatestTrackerIdInfo()
 {
     $info = array();
     $query = "SELECT id FROM tracker ORDER BY date_modified desc";
     $id = $this->db->getOne($query, false, 'fetching most recent tracker entry');
     $info['latest_tracker_id'] = (int) $id;
     return $info;
 }
 public function testDBGuidGeneration()
 {
     $guids = array();
     $sql = "SELECT {$this->_db->getGuidSQL()} {$this->_db->getFromDummyTable()}";
     for ($i = 0; $i < 1000; $i++) {
         $newguid = $this->_db->getOne($sql);
         $this->assertFalse(in_array($newguid, $guids), "'{$newguid}' already existed in the array of GUIDs!");
         $guids[] = $newguid;
     }
 }
 public function testGetOne()
 {
     $beanIds = $this->_createRecords(1);
     $id = $this->_db->getOne("SELECT id From contacts where last_name = 'foobar'");
     $this->assertEquals($id, $beanIds[0]);
     // bug 38994
     if ($this->_db instanceof MysqlManager) {
         $id = $this->_db->getOne($this->_db->limitQuerySql("SELECT id From contacts where last_name = 'foobar'", 0, 1));
         $this->assertEquals($id, $beanIds[0]);
     }
     $this->_removeRecords($beanIds);
 }
 /**
  * updateRate
  *
  * execute the standard sql query for updating rates.
  * to use a specific query, override doCustomUpdateRate()
  * in your extended class and make your own.
  *
  * @access protected
  * @param  string $table
  * @param  string $column
  * @param  string $currencyId
  * @return Object database result object
  */
 protected function updateRate($table, $column, $currencyId)
 {
     // get the conversion rate
     $rate = $this->db->getOne(sprintf("SELECT conversion_rate FROM currencies WHERE id = '%s'", $currencyId));
     if (empty($rate)) {
         $GLOBALS['log']->error(string_format($GLOBALS['app_strings']['ERR_DB_QUERY'], array('CurrencyRateUpdate', 'unknown currency: ' . $currencyId)));
         return false;
     }
     // setup SQL statement
     $query = sprintf("UPDATE %s SET %s = %s WHERE currency_id = '%s'", $table, $column, $rate, $currencyId);
     // execute
     return $this->db->query($query, true, string_format($GLOBALS['app_strings']['ERR_DB_QUERY'], array('CurrencyRateUpdate', $query)));
 }
 /**
  * Initialize Sugar environment
  */
 protected function initSugar()
 {
     if ($this->sugar_initialized) {
         return;
     }
     // BR-385 - This fixes the issues around SugarThemeRegistry fatals.  The cache needs rebuild on stage-post init of sugar
     if ($this->current_stage == 'post') {
         $this->cleanFileCache();
     }
     if (!defined('sugarEntry')) {
         define('sugarEntry', true);
     }
     $this->log("Initializing SugarCRM environment");
     global $beanFiles, $beanList, $objectList, $timedate, $moduleList, $modInvisList, $sugar_config, $locale, $sugar_version, $sugar_flavor, $sugar_build, $sugar_db_version, $sugar_timestamp, $db, $locale, $installing, $bwcModules, $app_list_strings, $modules_exempt_from_availability_check;
     $installing = true;
     include 'include/entryPoint.php';
     $installing = false;
     $GLOBALS['current_language'] = $this->config['default_language'];
     if (empty($GLOBALS['current_language'])) {
         $GLOBALS['current_language'] = 'en_us';
     }
     $GLOBALS['log'] = LoggerManager::getLogger('SugarCRM');
     $this->db = $GLOBALS['db'] = DBManagerFactory::getInstance();
     //Once we have a DB, we can do a full cache clear
     if ($this->current_stage == 'post') {
         $this->cleanCaches();
     }
     SugarApplication::preLoadLanguages();
     $timedate = TimeDate::getInstance();
     if (empty($locale)) {
         if (method_exists('Localization', 'getObject')) {
             $locale = Localization::getObject();
         } else {
             $locale = new Localization();
         }
     }
     if (!isset($_SERVER['REQUEST_URI'])) {
         $_SERVER['REQUEST_URI'] = '';
     }
     // Load user
     $GLOBALS['current_user'] = $this->getUser();
     // Prepare DB
     if ($this->config['dbconfig']['db_type'] == 'mysql') {
         //Change the db wait_timeout for this session
         $now_timeout = $this->db->getOne("select @@wait_timeout");
         $this->db->query("set wait_timeout=28800");
         $now_timeout = $this->db->getOne("select @@wait_timeout");
         $this->log("DB timeout set to {$now_timeout}");
     }
     // stop trackers
     $trackerManager = TrackerManager::getInstance(true);
     $trackerManager->pause();
     $trackerManager->unsetMonitors();
     $this->sugar_initialized = true;
     $this->loadStrings();
     $GLOBALS['app_list_strings'] = return_app_list_strings_language($GLOBALS['current_language']);
     $this->log("Done initializing SugarCRM environment");
 }
 /**
  * Process the save action for sugar bean custom fields.
  *
  * @param bool $isUpdate
  */
 public function save($isUpdate)
 {
     if ($this->bean->hasCustomFields() && isset($this->bean->id)) {
         $query = '';
         if ($isUpdate) {
             $query = 'UPDATE ' . $this->bean->table_name . '_cstm SET ';
         }
         $queryInsert = 'INSERT INTO ' . $this->bean->table_name . '_cstm (id_c';
         $values = "('" . $this->bean->id . "'";
         $first = true;
         foreach ($this->bean->field_defs as $name => $field) {
             if (empty($field['source']) || $field['source'] != 'custom_fields') {
                 continue;
             }
             if ($field['type'] == 'html' || $field['type'] == 'parent') {
                 continue;
             }
             if (isset($this->bean->{$name})) {
                 $quote = "'";
                 if (in_array($field['type'], array('int', 'float', 'double', 'uint', 'ulong', 'long', 'short', 'tinyint', 'currency', 'decimal'))) {
                     $quote = '';
                     if (!isset($this->bean->{$name}) || !is_numeric($this->bean->{$name})) {
                         if ($field['required']) {
                             $this->bean->{$name} = 0;
                         } else {
                             $this->bean->{$name} = 'NULL';
                         }
                     }
                 }
                 if ($field['type'] == 'bool') {
                     if ($this->bean->{$name} === false) {
                         $this->bean->{$name} = '0';
                     } elseif ($this->bean->{$name} === true) {
                         $this->bean->{$name} = '1';
                     }
                 }
                 $val = $this->bean->{$name};
                 if (($field['type'] == 'date' || $field['type'] == 'datetimecombo') && (empty($this->bean->{$name}) || $this->bean->{$name} == '1900-01-01')) {
                     $quote = '';
                     $val = 'NULL';
                     $this->bean->{$name} = '';
                     // do not set it to string 'NULL'
                 }
                 if ($isUpdate) {
                     if ($first) {
                         $query .= " {$name}={$quote}" . $this->db->quote($val) . "{$quote}";
                     } else {
                         $query .= " ,{$name}={$quote}" . $this->db->quote($val) . "{$quote}";
                     }
                 }
                 $first = false;
                 $queryInsert .= " ,{$name}";
                 $values .= " ,{$quote}" . $this->db->quote($val) . "{$quote}";
             }
         }
         if ($isUpdate) {
             $query .= " WHERE id_c='" . $this->bean->id . "'";
         }
         $queryInsert .= " ) VALUES {$values} )";
         if (!$first) {
             if (!$isUpdate) {
                 $this->db->query($queryInsert);
             } else {
                 $checkQuery = "SELECT id_c FROM {$this->bean->table_name}_cstm WHERE id_c = '{$this->bean->id}'";
                 if ($this->db->getOne($checkQuery)) {
                     $this->db->query($query);
                 } else {
                     $this->db->query($queryInsert);
                 }
             }
         }
     }
 }