function edit_id($values = array())
 {
     if (!isset($values['select']) || !is_array($values['select'])) {
         return $receipt['message'][] = array('msg' => lang('Nothing to do'));
     }
     $this->db->transaction_begin();
     foreach ($values['select'] as $field) {
         $start_date = phpgwapi_datetime::date_to_timestamp($values['start_date'][$field]);
         if ($start_date && $start_date < time()) {
             $receipt['error'][] = array('msg' => lang('Cannot go back in time for "%1"', $field));
             continue;
         }
         $sql = "SELECT value,descr, max(start_date) as start_date FROM fm_idgenerator WHERE name='{$field}' GROUP BY value, descr ORDER BY start_date ASC";
         $this->db->query($sql, __LINE__, __FILE__);
         while ($this->db->next_record()) {
             $value = $this->db->f('value');
             $descr = $this->db->f('descr');
             $old_start_date = $this->db->f('start_date');
         }
         if ($start_date > $old_start_date) {
             $sql = "INSERT INTO fm_idgenerator (name, descr, value, start_date ) VALUES ('{$field}','{$descr}', '{$values[$field]}','{$start_date}')";
             $this->db->query($sql, __LINE__, __FILE__);
         } else {
             if ($start_date < $old_start_date) {
                 $sql = "DELETE FROM fm_idgenerator WHERE name = name AND start_date > {$start_date}";
                 $this->db->query($sql, __LINE__, __FILE__);
                 $sql = "INSERT INTO fm_idgenerator (name, descr, value, start_date ) VALUES ('{$field}','{$descr}', '{$values[$field]}','{$start_date}')";
                 $this->db->query($sql, __LINE__, __FILE__);
             } else {
                 $sql = "UPDATE fm_idgenerator SET value = '{$values[$field]}' WHERE name='{$field}' AND start_date  = {$start_date}";
                 $this->db->query($sql, __LINE__, __FILE__);
             }
         }
     }
     $this->db->transaction_commit();
     $receipt['message'][] = array('msg' => lang('ID is updated'));
     return $receipt;
 }
 public function populate()
 {
     $this->set_title(phpgw::get_var('title', 'string'));
     $this->set_description(phpgw::get_var('description', 'html'));
     if (phpgw::get_var('start_date', 'string') != '') {
         $start_date_ts = phpgwapi_datetime::date_to_timestamp(phpgw::get_var('start_date', 'string'));
         $this->set_start_date($start_date_ts);
     } else {
         $this->set_start_date(0);
     }
     if (phpgw::get_var('end_date', 'string') != '') {
         $end_date_ts = phpgwapi_datetime::date_to_timestamp(phpgw::get_var('end_date', 'string'));
         $this->set_end_date($end_date_ts);
     } else {
         $this->set_end_date(0);
     }
     $this->set_repeat_type(phpgw::get_var('repeat_type', 'string'));
     $this->set_repeat_interval(phpgw::get_var('repeat_interval', 'string'));
     $this->set_procedure_id(phpgw::get_var('procedure_id', 'int'));
     $this->set_control_area_id(phpgw::get_var('control_area_id', 'int'));
     $this->set_responsibility_id(phpgw::get_var('responsibility_id', 'int'));
 }
 /**
  * Save responsibility contact
  *
  * @param array $values values to be stored/edited and referencing ID if editing
  *
  * @return array $receip with result on the action(failed/success)
  */
 public function save_contact($values)
 {
     phpgw::import_class('phpgwapi.datetime');
     if (isset($values['active_from'])) {
         $values['active_from'] = phpgwapi_datetime::date_to_timestamp($values['active_from']);
     }
     if (isset($values['active_to'])) {
         $values['active_to'] = phpgwapi_datetime::date_to_timestamp($values['active_to']);
     }
     if (isset($values['id']) && $values['id']) {
         $receipt = $this->so->edit_contact($values);
     } else {
         $receipt = $this->so->add_contact($values);
     }
     return $receipt;
 }
 public function populate()
 {
     $this->set_id(phpgw::get_var('id'));
     $this->set_name(phpgw::get_var('name'));
     $this->set_project_type_id(phpgw::get_var('project_type_id'));
     $this->set_description(phpgw::get_var('description'));
     if (phpgw::get_var('start_date', 'string') != '') {
         $start_date_ts = phpgwapi_datetime::date_to_timestamp(phpgw::get_var('start_date', 'string'));
         $this->set_start_date($start_date_ts);
     }
     if (phpgw::get_var('end_date', 'string') != '') {
         $end_date_ts = phpgwapi_datetime::date_to_timestamp(phpgw::get_var('end_date', 'string'));
         $this->set_end_date($end_date_ts);
     }
 }
 public function save($data)
 {
     $data['start_date'] = phpgwapi_datetime::date_to_timestamp($data['start_date']);
     $data['end_date'] = phpgwapi_datetime::date_to_timestamp($data['end_date']);
     //			_debug_array($data);die();
     if (isset($data['id']) && $data['id'] > 0 && $this->so->read_single($data['id'])) {
         $receipt = $this->so->edit($data);
     } else {
         $receipt = $this->so->add($data);
     }
     /*
     			$action_object		= CreateObject('property.sogeneric');
     			$action_object->get_location_info('event_action',false);
     			$action	= $action_object->read_single(array('id'=> $data['action']),$values = array());
     */
     $rpt_day = array(1 => 0, 2 => 1, 4 => 2, 8 => 3, 16 => 4, 32 => 5, 64 => 6);
     $repeat_day = array();
     if ($data['repeat_day']) {
         foreach ($data['repeat_day'] as $day) {
             if (isset($rpt_day[$day])) {
                 $repeat_day[] = $rpt_day[$day];
             }
         }
         $repeat_day = implode(',', $repeat_day);
     }
     if (!isset($data['repeat_type']) || !$data['repeat_type']) {
         $times = $data['start_date'];
     } else {
         $dow = $rpt_day[$data['repeat_day'][0]];
         switch ($data['repeat_type']) {
             case '0':
                 $times = $data['start_date'];
                 break;
             case '1':
                 //'Daily'
                 if ($data['repeat_interval']) {
                     $times = array('day' => "*/{$data['repeat_interval']}");
                 } else {
                     $times = array('day' => "*/1");
                 }
                 break;
             case '2':
                 //'Weekly'
                 if ($data['repeat_interval']) {
                     $day = $data['repeat_interval'] * 7;
                     $times = array('day' => "*/{$day}");
                 } else {
                     $times = array('day' => "*/7");
                 }
                 if ($data['repeat_day']) {
                     $times['dow'] = $repeat_day;
                 }
                 break;
             case '3':
                 //'Monthly (by day)'
                 if (!isset($data['repeat_day']) || !is_array($data['repeat_day'])) {
                     $dow = 1;
                 }
                 if ($data['repeat_interval']) {
                     $times = array('month' => "*/{$data['repeat_interval']}", 'dow' => $dow);
                 } else {
                     $times = array('month' => "*/1", 'dow' => $dow);
                 }
                 break;
             case '4':
                 //'Monthly (by date)'
                 if ($data['repeat_interval']) {
                     $times = array('month' => "*/{$data['repeat_interval']}", 'day' => 1);
                 } else {
                     $times = array('day' => 1);
                 }
                 break;
             case '5':
                 //'Yearly'
                 $month = date(n, $data['start_date']);
                 if ($data['repeat_interval']) {
                     $times = array('year' => "*/{$data['repeat_interval']}", 'month' => $month);
                 } else {
                     $times = array('month' => $month);
                 }
                 break;
             default:
                 $times = $data['start_date'];
                 break;
         }
     }
     //$times['min']= '*'; // for testing the  - every minute
     $account_id = execMethod('property.soresponsible.get_contact_user_id', $data['contact_id']);
     $timer_data = array('start' => $data['start_date'], 'enabled' => true, 'owner' => $account_id, 'enabled' => !!$data['enabled'], 'action' => $this->event_functions[$data['action']]['action'], 'action_data' => array('contact_id' => $data['contact_id']));
     if ($data['end_date']) {
         $timer_data['end'] = $data['end_date'];
     }
     if ($action['data']) {
         str_replace(";", '', $action['data']);
         eval('$action_data = ' . htmlspecialchars_decode($action['data']) . ';');
         $timer_data = array_merge($timer_data, $action_data);
     }
     $location = phpgw::get_var('location');
     $id = "property{$location}::{$data['item_id']}::{$receipt['id']}";
     $timer_data['id'] = $id;
     $this->asyncservice->cancel_timer($id);
     $this->asyncservice->set_timer($times, $id, 'property.boevent.action', $timer_data, $account_id);
     $event = $this->so->read_single($receipt['id']);
     $criteria = array('start_date' => $event['start_date'], 'end_date' => $event['end_date'], 'location_id' => $event['location_id'], 'location_item_id' => $event['location_item_id']);
     $this->find_scedules($criteria);
     $schedule = $this->cached_events;
     $this->so->create_schedule(array('event_id' => $receipt['id'], 'schedule' => $schedule));
     return $receipt;
 }
 /**
  * Public function for saving a check list
  * 
  * @param HTTP:: location code, control id, status etc.. (check list details) 
  * @return data array
  */
 function save_check_list()
 {
     $check_list_id = phpgw::get_var('check_list_id');
     if (!$this->add && !$this->edit) {
         phpgwapi_cache::message_set('No access', 'error');
         $this->redirect(array('menuaction' => 'controller.uicheck_list.edit_check_list', 'check_list_id' => $check_list_id));
     }
     $control_id = phpgw::get_var('control_id', 'int');
     $serie_id = phpgw::get_var('serie_id', 'int');
     $status = (int) phpgw::get_var('status');
     $type = phpgw::get_var('type');
     $deadline_date = phpgw::get_var('deadline_date', 'string');
     $planned_date = phpgw::get_var('planned_date', 'string');
     $completed_date = phpgw::get_var('completed_date', 'string');
     $comment = phpgw::get_var('comment', 'string');
     $assigned_to = phpgw::get_var('assigned_to', 'int');
     $billable_hours = phpgw::get_var('billable_hours', 'float');
     $deadline_date_ts = date_converter::date_to_timestamp($deadline_date);
     $error = false;
     if ($planned_date != '') {
         $planned_date_ts = date_converter::date_to_timestamp($planned_date);
     } else {
         $planned_date_ts = $deadline_date_ts;
     }
     if ($completed_date != '') {
         $completed_date_ts = phpgwapi_datetime::date_to_timestamp($completed_date);
         $status = controller_check_list::STATUS_DONE;
     } else {
         $completed_date_ts = 0;
     }
     if ($check_list_id > 0) {
         $check_list = $this->so->get_single($check_list_id);
         if ($status == controller_check_list::STATUS_DONE) {
             if (!$this->_check_for_required($check_list)) {
                 $this->redirect(array('menuaction' => 'controller.uicheck_list.edit_check_list', 'check_list_id' => $check_list_id));
             }
         }
     } else {
         if ($status == controller_check_list::STATUS_DONE) {
             $status = controller_check_list::STATUS_NOT_DONE;
             $completed_date_ts = 0;
             $error_message = "Status kunne ikke settes til utført - prøv igjen";
             $error = true;
             phpgwapi_cache::message_set($error_message, 'error');
         }
         $check_list = new controller_check_list();
         $check_list->set_control_id($control_id);
         $location_code = phpgw::get_var('location_code');
         $check_list->set_location_code($location_code);
         $check_list->set_serie_id($serie_id);
         if ($type == "component") {
             $location_id = phpgw::get_var('location_id');
             $component_id = phpgw::get_var('component_id');
             $check_list->set_location_id($location_id);
             $check_list->set_component_id($component_id);
         }
     }
     $check_list->set_comment($comment);
     $check_list->set_deadline($deadline_date_ts);
     $check_list->set_planned_date($planned_date_ts);
     $check_list->set_completed_date($completed_date_ts);
     $orig_assigned_to = $check_list->get_assigned_to();
     $check_list->set_assigned_to($assigned_to);
     $config = CreateObject('phpgwapi.config', 'controller');
     $config->read();
     $required_actual_hours = isset($config->config_data['required_actual_hours']) && $config->config_data['required_actual_hours'] ? $config->config_data['required_actual_hours'] : false;
     if ($status == controller_check_list::STATUS_DONE && $required_actual_hours && $check_list->get_billable_hours() == 0 && !$billable_hours) {
         phpgwapi_cache::message_set(lang("Please enter billable hours"), 'error');
         $error = true;
     } else {
         $check_list->set_delta_billable_hours($billable_hours);
     }
     if ($status == controller_check_list::STATUS_DONE && $this->_check_for_required($check_list) && !$error) {
         $check_list->set_status($status);
     } else {
         if ($status == controller_check_list::STATUS_CANCELED && !$error) {
             $check_list->set_status($status);
         }
     }
     if (!$error && $check_list->validate()) {
         $check_list_id = $this->so->store($check_list);
         $serie = $this->so_control->get_serie($check_list->get_serie_id());
         /**
          * Add an iCal-event if there is a serie - and the checklist is visited the first time - or assigned is changed
          */
         if (phpgw::get_var('request_ical_event', 'bool') && $check_list_id && $serie) {
             $bocommon = CreateObject('property.bocommon');
             $current_prefs_user = $bocommon->create_preferences('property', $GLOBALS['phpgw_info']['user']['account_id']);
             $from_address = "{$GLOBALS['phpgw_info']['user']['fullname']}<{$current_prefs_user['email']}>";
             $from_name = $GLOBALS['phpgw_info']['user']['fullname'];
             $to_name = $GLOBALS['phpgw']->accounts->id2name($assigned_to);
             $prefs_target = $bocommon->create_preferences('property', $assigned_to);
             $to_address = $prefs_target['email'];
             if (!($start_date = $check_list->get_planned_date())) {
                 $start_date = $check_list->get_deadline();
             }
             $startTime = $start_date + 8 * 3600;
             $endTime = $startTime + (double) $serie['service_time'] * 3600 + (double) $serie['controle_time'] * 3600;
             if ($check_list->get_component_id() > 0) {
                 $component_arr = execMethod('property.soentity.read_single_eav', array('location_id' => $check_list->get_location_id(), 'id' => $check_list->get_component_id()));
                 $location_name = execMethod('property.bolocation.get_location_name', $component_arr['location_code']);
                 $short_desc = $location_name . '::' . execMethod('property.soentity.get_short_description', array('location_id' => $check_list->get_location_id(), 'id' => $check_list->get_component_id()));
                 $location = $location_name;
             }
             $repeat_type_array = array("0" => lang('day'), "1" => lang('week'), "2" => lang('month'), "3" => lang('year'));
             $subject = "{$repeat_type_array[$serie['repeat_type']]}/{$serie['repeat_interval']}";
             $subject .= "::{$serie['title']}::{$short_desc}";
             $link_backend = $GLOBALS['phpgw']->link('/index.php', array('menuaction' => 'controller.uicheck_list.add_check_list', 'control_id' => $check_list->get_control_id(), 'location_id' => $check_list->get_location_id(), 'component_id' => $check_list->get_component_id(), 'serie_id' => $check_list->get_serie_id(), 'type' => 'component', 'assigned_to' => $check_list->get_assigned_to(), 'deadline_current' => true), false, true, true);
             $link_mobilefrontend = $GLOBALS['phpgw']->link('/mobilefrontend/index.php', array('menuaction' => 'controller.uicheck_list.add_check_list', 'control_id' => $check_list->get_control_id(), 'location_id' => $check_list->get_location_id(), 'component_id' => $check_list->get_component_id(), 'serie_id' => $check_list->get_serie_id(), 'type' => 'component', 'assigned_to' => $check_list->get_assigned_to(), 'deadline_current' => true), false, true, true);
             $html_description = "<a href ='{$link_mobilefrontend}'>Serie#" . $check_list->get_serie_id() . '::Mobilefrontend</a><br/><br/>';
             $html_description .= "<a href ='{$link_backend}'>Serie#" . $check_list->get_serie_id() . '::Backend</a>';
             $_serie_id = $check_list->get_serie_id();
             $text_description = str_replace('&amp;', '&', "Serie#{$_serie_id}::Mobilefrontend:\\n{$link_mobilefrontend}\\n\\nSerie#{$_serie_id}::Backend:\\n{$link_backend}");
             if ($from_address && $to_address) {
                 $this->sendIcalEvent($from_name, $from_address, $to_name, $to_address, $startTime, $endTime, $subject, $html_description, $text_description, $location);
             } else {
                 phpgwapi_cache::message_set("Mangler epostadresse til avsender eller addresat - eller begge", 'error');
             }
         }
         if ($check_list_id > 0) {
             $this->redirect(array('menuaction' => 'controller.uicheck_list.edit_check_list', 'check_list_id' => $check_list_id));
         } else {
             $this->edit_check_list($check_list);
         }
     } else {
         if ($check_list->get_id() > 0) {
             $this->edit_check_list($check_list);
         } else {
             $this->redirect(array('menuaction' => 'controller.uicheck_list.add_check_list', 'control_id' => $control_id, 'location_id' => $location_id, 'component_id' => $component_id, 'serie_id' => $serie_id, 'deadline_ts' => $deadline_date_ts, 'type' => $type, 'assigned_to' => $assigned_to, 'status' => $status));
         }
     }
 }
 /**
  * Prepare an attribute value so it can be saved in the database
  *
  * @param array $values_attribute an attribute structure
  *
  * @return array the structure with the value prepared
  *
  * @internal the name of this method is misleading
  */
 public function convert_attribute_save($values_attribute = null)
 {
     if (!is_array($values_attribute)) {
         return '';
     }
     foreach ($values_attribute as &$attrib) {
         if (!$attrib['value']) {
             continue;
         }
         switch ($attrib['datatype']) {
             case 'CH':
                 $attrib['value'] = ',' . implode(',', $attrib['value']) . ',';
                 break;
             case 'R':
                 $attrib['value'] = $attrib['value'][0];
                 break;
             case 'N':
                 $attrib['value'] = str_replace(',', '.', $attrib['value']);
                 break;
             case 'D':
                 $ts = phpgwapi_datetime::date_to_timestamp($attrib['value']) - phpgwapi_datetime::user_timezone();
                 $attrib['value'] = date($this->_dateformat, $ts);
                 break;
             case 'DT':
                 if ($attrib['value']['date']) {
                     $date_array = phpgwapi_datetime::date_array($attrib['value']['date']);
                     $ts = mktime((int) $attrib['value']['hour'], (int) $attrib['value']['min'], 0, $date_array['month'], $date_array['day'], $date_array['year']) - phpgwapi_datetime::user_timezone();
                     $attrib['value'] = date($this->_datetimeformat, $ts);
                 } else {
                     $attrib['value'] = '';
                 }
                 break;
         }
     }
     return $values_attribute;
 }
 function read($data)
 {
     $start = isset($data['start']) && $data['start'] ? (int) $data['start'] : 0;
     $filter = isset($data['filter']) ? $data['filter'] : '';
     $query = isset($data['query']) ? $data['query'] : '';
     $sort = isset($data['sort']) && $data['sort'] ? $data['sort'] : 'DESC';
     $order = isset($data['order']) ? $data['order'] : '';
     $cat_id = isset($data['cat_id']) ? $data['cat_id'] : 0;
     $property_cat_id = isset($data['property_cat_id']) ? $data['property_cat_id'] : 0;
     $status_id = isset($data['status_id']) && $data['status_id'] ? $data['status_id'] : 'open';
     $district_id = isset($data['district_id']) && $data['district_id'] ? $data['district_id'] : 0;
     $project_id = isset($data['project_id']) ? $data['project_id'] : '';
     $allrows = isset($data['allrows']) ? $data['allrows'] : '';
     $list_descr = isset($data['list_descr']) ? $data['list_descr'] : '';
     $dry_run = isset($data['dry_run']) ? $data['dry_run'] : '';
     $p_num = isset($data['p_num']) ? $data['p_num'] : '';
     $start_date = isset($data['start_date']) && $data['start_date'] ? phpgwapi_datetime::date_to_timestamp($data['start_date']) : 0;
     $end_date = isset($data['end_date']) && $data['end_date'] ? phpgwapi_datetime::date_to_timestamp($data['end_date']) : 0;
     $building_part = isset($data['building_part']) && $data['building_part'] ? (int) $data['building_part'] : 0;
     $degree_id = $data['degree_id'];
     $attrib_filter = $data['attrib_filter'] ? $data['attrib_filter'] : array();
     $condition_survey_id = $data['condition_survey_id'] ? (int) $data['condition_survey_id'] : 0;
     $responsible_unit = (int) $data['responsible_unit'];
     $recommended_year = (int) $data['recommended_year'];
     $location_id = $GLOBALS['phpgw']->locations->get_id('property', '.project.request');
     $attribute_table = 'phpgw_cust_attribute';
     $attribute_filter = " location_id = {$location_id}";
     $entity_table = 'fm_request';
     $GLOBALS['phpgw']->config->read();
     $uicols = array();
     $cols .= "{$entity_table}.location_code";
     $cols_return[] = 'location_code';
     $cols_group[] = "{$entity_table}.location_code";
     $cols_group[] = 'fm_location1.loc1_name';
     $cols .= ",{$entity_table}.id as request_id";
     $cols_return[] = 'request_id';
     $cols .= ",fm_request_status.descr as status";
     $cols_return[] = 'status';
     $cols_group[] = 'fm_request_status.descr';
     $uicols['input_type'][] = 'text';
     $uicols['name'][] = 'status';
     $uicols['descr'][] = lang('status');
     $uicols['statustext'][] = lang('status');
     $uicols['exchange'][] = '';
     $uicols['align'][] = '';
     $uicols['datatype'][] = '';
     $uicols['formatter'][] = '';
     $uicols['classname'][] = '';
     $uicols['sortable'][] = false;
     $cols .= ",{$entity_table}.building_part";
     $cols_return[] = 'building_part';
     $cols_group[] = 'building_part';
     $uicols['input_type'][] = 'text';
     $uicols['name'][] = 'building_part';
     $uicols['descr'][] = lang('building part');
     $uicols['statustext'][] = lang('building part');
     $uicols['exchange'][] = '';
     $uicols['align'][] = '';
     $uicols['datatype'][] = '';
     $uicols['formatter'][] = '';
     $uicols['classname'][] = '';
     $uicols['sortable'][] = true;
     $cols .= ",{$entity_table}.start_date,{$entity_table}.entry_date,{$entity_table}.closed_date,{$entity_table}.in_progress_date,{$entity_table}.delivered_date";
     $cols_return[] = "start_date";
     $cols_return[] = "entry_date";
     $cols_return[] = "closed_date";
     $cols_return[] = "in_progress_date";
     $cols_return[] = "delivered_date";
     //			$cols_group[] 				= "{$entity_table}.start_date";
     $cols_group[] = "{$entity_table}.entry_date";
     $cols_group[] = "{$entity_table}.closed_date";
     $cols_group[] = "{$entity_table}.in_progress_date";
     $cols_group[] = "{$entity_table}.delivered_date";
     /*
     			$uicols['input_type'][]		= 'text';
     			$uicols['name'][]			= 'start_date';
     			$uicols['descr'][]			= lang('start date');
     			$uicols['statustext'][]		= lang('Request start date');
     			$uicols['exchange'][]		= '';
     			$uicols['align'][]			= '';
     			$uicols['datatype'][]		= '';
     			$uicols['formatter'][]		= '';
     			$uicols['classname'][]		= '';
     			$uicols['sortable'][]		= true;
     */
     $cols .= ",{$entity_table}.title as title";
     $cols_return[] = 'title';
     $cols_group[] = "title";
     $uicols['input_type'][] = 'text';
     $uicols['name'][] = 'title';
     $uicols['descr'][] = lang('request title');
     $uicols['statustext'][] = lang('Request title');
     $uicols['exchange'][] = '';
     $uicols['align'][] = '';
     $uicols['datatype'][] = '';
     $uicols['formatter'][] = '';
     $uicols['classname'][] = '';
     $uicols['sortable'][] = true;
     if ($list_descr) {
         $cols .= ",{$entity_table}.descr as descr";
         $cols_return[] = 'descr';
         $cols_group[] = "{$entity_table}.descr";
         $uicols['input_type'][] = 'text';
         $uicols['name'][] = 'descr';
         $uicols['descr'][] = lang('descr');
         $uicols['statustext'][] = lang('Request descr');
         $uicols['exchange'][] = '';
         $uicols['align'][] = '';
         $uicols['datatype'][] = '';
         $uicols['formatter'][] = '';
         $uicols['classname'][] = '';
         $uicols['sortable'][] = false;
     }
     $cols .= ",max(fm_request_condition.degree) as condition_degree";
     $cols_return[] = 'condition_degree';
     $uicols['input_type'][] = 'text';
     $uicols['name'][] = 'condition_degree';
     $uicols['descr'][] = lang('condition degree');
     $uicols['statustext'][] = lang('condition degree');
     $uicols['exchange'][] = '';
     $uicols['align'][] = '';
     $uicols['datatype'][] = '';
     $uicols['formatter'][] = '';
     $uicols['classname'][] = '';
     $uicols['sortable'][] = true;
     $cols .= ",({$entity_table}.amount_investment * multiplier) as amount_investment";
     $cols_return[] = 'amount_investment';
     $cols_group[] = 'amount_investment';
     $uicols['input_type'][] = 'text';
     $uicols['name'][] = 'amount_investment';
     $uicols['descr'][] = lang('investment');
     $uicols['statustext'][] = lang('cost estimate');
     $uicols['exchange'][] = '';
     $uicols['align'][] = '';
     $uicols['datatype'][] = '';
     $uicols['formatter'][] = 'FormatterRight';
     $uicols['classname'][] = 'rightClasss';
     $uicols['sortable'][] = true;
     $cols .= ",({$entity_table}.amount_operation * multiplier) as amount_operation";
     $cols_return[] = 'amount_operation';
     $cols_group[] = 'amount_operation';
     $uicols['input_type'][] = 'text';
     $uicols['name'][] = 'amount_operation';
     $uicols['descr'][] = lang('operation');
     $uicols['statustext'][] = lang('cost estimate');
     $uicols['exchange'][] = '';
     $uicols['align'][] = '';
     $uicols['datatype'][] = '';
     $uicols['formatter'][] = 'FormatterRight';
     $uicols['classname'][] = 'rightClasss';
     $uicols['sortable'][] = true;
     $cols .= ",({$entity_table}.amount_potential_grants * multiplier) as amount_potential_grants";
     $cols_return[] = 'amount_potential_grants';
     $cols_group[] = 'amount_potential_grants';
     $uicols['input_type'][] = 'text';
     $uicols['name'][] = 'amount_potential_grants';
     $uicols['descr'][] = lang('potential grants');
     $uicols['statustext'][] = lang('potential grants');
     $uicols['exchange'][] = '';
     $uicols['align'][] = '';
     $uicols['datatype'][] = '';
     $uicols['formatter'][] = 'FormatterRight';
     $uicols['classname'][] = 'rightClasss';
     $uicols['sortable'][] = true;
     //			$cols.= ",sum(amount) as consume";
     //			$cols_return[] 				= 'consume';
     $uicols['input_type'][] = 'text';
     $uicols['name'][] = 'consume';
     $uicols['descr'][] = lang('consume');
     $uicols['statustext'][] = lang('consume');
     $uicols['exchange'][] = '';
     $uicols['align'][] = '';
     $uicols['datatype'][] = '';
     $uicols['formatter'][] = 'FormatterRight';
     $uicols['classname'][] = '';
     $uicols['sortable'][] = true;
     $cols .= ",{$entity_table}.score";
     $cols_return[] = 'score';
     $cols_group[] = 'score';
     $uicols['input_type'][] = 'text';
     $uicols['name'][] = 'score';
     $uicols['descr'][] = lang('score');
     $uicols['statustext'][] = lang('score');
     $uicols['exchange'][] = '';
     $uicols['align'][] = '';
     $uicols['datatype'][] = '';
     $uicols['formatter'][] = 'FormatterRight';
     $uicols['classname'][] = '';
     $uicols['sortable'][] = true;
     $cols .= ",recommended_year";
     $cols_return[] = 'recommended_year';
     $cols_group[] = 'recommended_year';
     $uicols['input_type'][] = 'text';
     $uicols['name'][] = 'recommended_year';
     $uicols['descr'][] = lang('recommended year');
     $uicols['statustext'][] = lang('recommended year');
     $uicols['exchange'][] = '';
     $uicols['align'][] = '';
     $uicols['datatype'][] = '';
     $uicols['formatter'][] = '';
     $uicols['classname'][] = '';
     $uicols['sortable'][] = true;
     $cols .= ",start_date AS planned_year";
     $cols_return[] = 'planned_year';
     $cols_group[] = 'start_date';
     $uicols['input_type'][] = 'text';
     $uicols['name'][] = 'planned_year';
     $uicols['descr'][] = lang('planned year');
     $uicols['statustext'][] = lang('planned year');
     $uicols['exchange'][] = '';
     $uicols['align'][] = '';
     $uicols['datatype'][] = '';
     $uicols['formatter'][] = '';
     $uicols['classname'][] = '';
     $uicols['sortable'][] = true;
     $this->_db->query("SELECT * FROM {$attribute_table} WHERE list=1 AND {$attribute_filter}");
     $_attrib = array();
     while ($this->_db->next_record()) {
         $_column_name = $this->_db->f('column_name');
         $cols .= ",{$entity_table}.{$_column_name}";
         $cols_return[] = $_column_name;
         $cols_group[] = $_column_name;
         $uicols['input_type'][] = 'text';
         $uicols['name'][] = $_column_name;
         $uicols['descr'][] = $this->_db->f('input_text', true);
         $uicols['statustext'][] = $this->_db->f('statustext', true);
         $uicols['exchange'][] = '';
         $uicols['align'][] = '';
         $uicols['datatype'][] = $this->_db->f('datatype');
         $uicols['formatter'][] = '';
         $uicols['classname'][] = '';
         $uicols['sortable'][] = false;
         $_attrib[$_column_name] = $this->_db->f('id');
     }
     $cols .= ",{$entity_table}.coordinator";
     $cols_return[] = 'coordinator';
     $cols_group[] = 'coordinator';
     $uicols['input_type'][] = 'text';
     $uicols['name'][] = 'coordinator';
     $uicols['descr'][] = isset($GLOBALS['phpgw']->config->config_data['lang_request_coordinator']) && $GLOBALS['phpgw']->config->config_data['lang_request_coordinator'] ? $GLOBALS['phpgw']->config->config_data['lang_request_coordinator'] : lang('Coordinator');
     $uicols['statustext'][] = lang('Project coordinator');
     $uicols['exchange'][] = '';
     $uicols['align'][] = '';
     $uicols['datatype'][] = '';
     $uicols['formatter'][] = '';
     $uicols['classname'][] = '';
     $uicols['sortable'][] = false;
     $paranthesis = '(';
     $joinmethod = "{$this->_left_join} fm_request_status ON {$entity_table}.status = fm_request_status.id)";
     $paranthesis .= '(';
     $joinmethod .= "{$this->_left_join} fm_request_planning ON {$entity_table}.id = fm_request_planning.request_id)";
     $paranthesis .= '(';
     $joinmethod .= "{$this->_left_join} fm_request_consume ON {$entity_table}.id = fm_request_consume.request_id)";
     $paranthesis .= '(';
     $joinmethod .= "{$this->_left_join} fm_request_condition ON {$entity_table}.id = fm_request_condition.request_id)";
     $_location_level = isset($GLOBALS['phpgw']->config->config_data['request_location_level']) && $GLOBALS['phpgw']->config->config_data['request_location_level'] ? $GLOBALS['phpgw']->config->config_data['request_location_level'] : 0;
     $sql = $this->bocommon->generate_sql(array('entity_table' => $entity_table, 'cols' => $cols, 'cols_return' => $cols_return, 'uicols' => array(), 'joinmethod' => $joinmethod, 'paranthesis' => $paranthesis, 'query' => $query, 'force_location' => true, 'location_level' => $_location_level));
     for ($i = 2; $i < $_location_level + 1; $i++) {
         $cols_group[] = "fm_location{$i}.loc{$i}_name";
     }
     $cols_group[] = "{$entity_table}.multiplier";
     $cols_group[] = "{$entity_table}.id";
     $cols_group[] = 'fm_request_status.descr';
     $cols_group[] = "{$entity_table}.address";
     $groupmethod = 'GROUP BY ' . implode(',', $cols_group);
     if ($order) {
         switch ($order) {
             case 'planned_year':
                 $ordermethod = " ORDER BY planned_year {$sort}";
                 break;
             default:
                 $ordermethod = " order by {$order} {$sort}";
         }
     } else {
         $ordermethod = ' order by fm_request.id DESC';
     }
     $where = 'WHERE';
     $filtermethod = '';
     if (isset($GLOBALS['phpgw']->config->config_data['acl_at_location']) && $GLOBALS['phpgw']->config->config_data['acl_at_location']) {
         $access_location = $this->bocommon->get_location_list(PHPGW_ACL_READ);
         $filtermethod = " WHERE fm_request.loc1 in ('" . implode("','", $access_location) . "')";
         $where = 'AND';
     }
     if ($property_cat_id > 0) {
         $filtermethod .= " {$where} fm_location1.category='{$property_cat_id}' ";
         $where = 'AND';
     }
     if ($cat_id > 0) {
         $filtermethod .= " {$where} fm_request.category='{$cat_id}'";
         $where = 'AND';
     }
     if ($recommended_year > 0) {
         $filtermethod .= " {$where} fm_request.recommended_year = {$recommended_year}";
         $where = 'AND';
     }
     if ($condition_survey_id > 0) {
         $filtermethod .= " {$where} fm_request.condition_survey_id = '{$condition_survey_id}'";
         $where = 'AND';
     }
     if ($status_id && $status_id != 'all') {
         if ($status_id == 'open') {
             $_status_filter = array();
             $this->_db->query("SELECT * FROM fm_request_status WHERE delivered IS NULL AND closed IS NULL");
             while ($this->_db->next_record()) {
                 $_status_filter[] = $this->_db->f('id');
             }
             $filtermethod .= " {$where} fm_request.status IN ('" . implode("','", $_status_filter) . "')";
         } else {
             $filtermethod .= " {$where} fm_request.status='{$status_id}' ";
         }
         $where = 'AND';
     }
     if ($degree_id) {
         $degree_id = (int) $degree_id - 1;
         $filtermethod .= " {$where} fm_request_condition.degree = {$degree_id}";
         $where = 'AND';
     }
     if ($building_part) {
         $filtermethod .= " {$where} fm_request.building_part {$this->_like} '{$building_part}%'";
         $where = 'AND';
     }
     if ($start_date) {
         $end_date = $end_date + 3600 * 16 + phpgwapi_datetime::user_timezone();
         $start_date = $start_date - 3600 * 8 + phpgwapi_datetime::user_timezone();
         $filtermethod .= " {$where} fm_request.start_date >= {$start_date} AND fm_request.start_date <= {$end_date} ";
         $where = 'AND';
     }
     if ($filter) {
         $filtermethod .= " {$where} fm_request.coordinator='{$filter}' ";
         $where = 'AND';
     }
     if ($attrib_filter) {
         $filtermethod .= " {$where} " . implode(' AND ', $attrib_filter);
         $where = 'AND';
     }
     if ($project_id && !$status_id) {
         //				$filtermethod .= " $where project_id is NULL ";
         $filtermethod .= " {$where} fm_request_status.closed is NULL ";
         $where = 'AND';
     }
     if ($district_id) {
         $filtermethod .= " {$where} fm_part_of_town.district_id = {$district_id}";
         $where = 'AND';
     }
     if ($responsible_unit) {
         $filtermethod .= " {$where} fm_request.responsible_unit='{$responsible_unit}'";
         $where = 'AND';
     }
     if ($query) {
         if (stristr($query, '.') && $p_num) {
             $query = explode(".", $query);
             $querymethod = " {$where} (fm_request.p_entity_id='" . (int) $query[1] . "' AND fm_request.p_cat_id='" . (int) $query[2] . "' AND fm_request.p_num='" . (int) $query[3] . "')";
         } else {
             $query = $this->_db->db_addslashes($query);
             $querymethod = " {$where} (fm_request.title {$this->_like} '%{$query}%' OR fm_request.address {$this->_like} '%{$query}%' OR fm_request.location_code {$this->_like} '%{$query}%' OR fm_request.id =" . (int) $query;
             for ($i = 1; $i <= $_location_level; $i++) {
                 $querymethod .= " OR fm_location{$i}.loc{$i}_name {$this->_like} '%{$query}%'";
             }
             $querymethod .= ')';
         }
     }
     $sql .= " {$filtermethod} {$querymethod}";
     $sql_arr = explode('FROM', $sql);
     $sql .= " {$groupmethod}";
     //_debug_array($sql);
     $this->uicols['input_type'] = array_merge($this->bocommon->uicols['input_type'], $uicols['input_type']);
     $this->uicols['name'] = array_merge($this->bocommon->uicols['name'], $uicols['name']);
     $this->uicols['descr'] = array_merge($this->bocommon->uicols['descr'], $uicols['descr']);
     $this->uicols['statustext'] = array_merge($this->bocommon->uicols['statustext'], $uicols['statustext']);
     $this->uicols['exchange'] = array_merge($this->bocommon->uicols['exchange'], $uicols['exchange']);
     $this->uicols['align'] = array_merge($this->bocommon->uicols['align'], $uicols['align']);
     $this->uicols['datatype'] = array_merge($this->bocommon->uicols['datatype'], $uicols['datatype']);
     $this->uicols['formatter'] = array_merge($this->bocommon->uicols['formatter'], $uicols['formatter']);
     $this->uicols['classname'] = array_merge($this->bocommon->uicols['classname'], $uicols['classname']);
     $this->uicols['sortable'] = array_merge($this->bocommon->uicols['sortable'], $uicols['sortable']);
     array_unshift($this->uicols['input_type'], 'text');
     array_unshift($this->uicols['name'], 'request_id');
     array_unshift($this->uicols['descr'], 'ID');
     array_unshift($this->uicols['statustext'], 'Request ID');
     array_unshift($this->uicols['exchange'], '');
     array_unshift($this->uicols['align'], '');
     array_unshift($this->uicols['datatype'], '');
     array_unshift($this->uicols['formatter'], 'linktToRequest');
     array_unshift($this->uicols['classname'], '');
     array_unshift($this->uicols['sortable'], true);
     $cols_return = $this->bocommon->cols_return;
     $this->cols_extra = $this->bocommon->cols_extra;
     $this->_db->fetchmode = 'ASSOC';
     //			$sql2 = "SELECT count(*) as cnt, sum(amount_investment) as sum_investment, sum(amount_operation) as sum_operation, sum(amount_potential_grants) as sum_potential_grants FROM ({$sql}) as t";
     $sql2 = "SELECT count(*) as cnt, (sum(amount_investment * multiplier)) as sum_investment, (sum(amount_operation * multiplier)) as sum_operation, (sum(amount_potential_grants * multiplier)) as sum_potential_grants FROM {$sql_arr[1]}";
     $this->_db->query($sql2, __LINE__, __FILE__);
     $this->_db->next_record();
     $this->_total_records = $this->_db->f('cnt');
     $this->sum_investment = $this->_db->f('sum_investment');
     $this->sum_operation = $this->_db->f('sum_operation');
     $this->sum_potential_grants = $this->_db->f('sum_potential_grants');
     $sql3 = "SELECT sum(fm_request_consume.amount) as sum_consume  FROM {$sql_arr[1]}";
     $this->_db->query($sql3, __LINE__, __FILE__);
     $this->_db->next_record();
     $this->sum_consume = $this->_db->f('sum_consume');
     //			_debug_array($sql_arr);
     //cramirez.r@ccfirst.com 23/10/08 avoid retrieve data in first time, only render definition for headers (var myColumnDefs)
     if ($dry_run) {
         return array();
     } else {
         if (!$allrows) {
             $this->_db->limit_query($sql . $ordermethod, $start, __LINE__, __FILE__);
         } else {
             $this->_db->query($sql . $ordermethod, __LINE__, __FILE__);
         }
     }
     $_datatype = array();
     foreach ($this->uicols['name'] as $key => $_name) {
         $_datatype[$_name] = $this->uicols['datatype'][$key];
     }
     $dataset = array();
     $j = 0;
     while ($this->_db->next_record()) {
         foreach ($cols_return as $key => $field) {
             $dataset[$j][$field] = array('value' => $this->_db->f($field), 'datatype' => $_datatype[$field], 'attrib_id' => $_attrib[$field]);
         }
         $j++;
     }
     foreach ($dataset as &$entry) {
         $sql = "SELECT sum(amount) as consume FROM fm_request_consume WHERE request_id={$entry['request_id']['value']}";
         $this->_db->query($sql, __LINE__, __FILE__);
         $this->_db->next_record();
         $entry['consume'] = array('value' => $this->_db->f('consume'), 'datatype' => false, 'attrib_id' => false);
     }
     $values = $this->custom->translate_value($dataset, $location_id);
     return $values;
 }
 function update_ticket($ticket, $id = 0)
 {
     $id = (int) $id;
     $receipt = array();
     // DB Content is fresher than http posted value.
     $this->db->query("select * from phpgw_helpdesk_tickets where id='{$id}'", __LINE__, __FILE__);
     $this->db->next_record();
     $location_code = $this->db->f('location_code');
     $oldlocation_code = $this->db->f('location_code');
     $oldfinnish_date = $this->db->f('finnish_date');
     $oldfinnish_date2 = $this->db->f('finnish_date2');
     $oldassigned = $this->db->f('assignedto');
     $oldgroup_id = $this->db->f('group_id');
     $oldpriority = $this->db->f('priority');
     $oldcat_id = $this->db->f('cat_id');
     $old_status = $this->db->f('status');
     $old_budget = $this->db->f('budget');
     $old_billable_hours = $this->db->f('billable_hours');
     //	$old_billable_rate	= $this->db->f('billable_rate');
     $old_subject = $this->db->f('subject');
     $old_contact_id = $this->db->f('contact_id');
     $old_actual_cost = $this->db->f('actual_cost');
     $old_order_cat_id = $this->db->f('order_cat_id');
     $old_building_part = $this->db->f('building_part', true);
     $old_order_dim1 = (int) $this->db->f('order_dim1');
     if ($oldcat_id == 0) {
         $oldcat_id = '';
     }
     if ($old_order_cat_id == 0) {
         $old_order_cat_id = '';
     }
     if ($oldassigned == 0) {
         $oldassigned = '';
     }
     if ($oldgroup_id == 0) {
         $oldgroup_id = '';
     }
     // Figure out and last note
     $history_values = $this->historylog->return_array(array(), array('C'), 'history_timestamp', 'DESC', $id);
     $old_note = $history_values[0]['new_value'];
     if (!$old_note) {
         $old_note = $this->db->f('details');
     }
     $this->db->transaction_begin();
     /*
      ** phpgw_phpgw_helpdesk_append.append_type - Defs
      ** R - Reopen ticket
      ** X - Ticket closed
      ** O - Ticket opened
      ** C - Comment appended
      ** A - Ticket assignment
      ** G - Ticket group assignment
      ** P - Priority change
      ** T - Category change
      ** S - Subject change
      ** B - Budget change
      ** H - Billing hours
      ** F - finnish date
      ** C% - Status change
      ** L - Location changed
      ** M - Mail sent to vendor
      */
     $this->db->query("UPDATE phpgw_helpdesk_tickets SET publish_note = NULL WHERE id = {$id}", __LINE__, __FILE__);
     $this->db->query("UPDATE phpgw_history_log SET publish = NULL WHERE history_record_id = {$id}", __LINE__, __FILE__);
     if (isset($ticket['publish_note'])) {
         foreach ($ticket['publish_note'] as $publish_info) {
             $note = explode('_', $publish_info);
             if (!$note[1]) {
                 $this->db->query("UPDATE phpgw_helpdesk_tickets SET publish_note = 1 WHERE id = {$note[0]}", __LINE__, __FILE__);
             } else {
                 $this->db->query("UPDATE phpgw_history_log SET publish = 1 WHERE history_id = {$note[1]}", __LINE__, __FILE__);
             }
         }
     }
     $finnish_date = isset($ticket['finnish_date']) ? phpgwapi_datetime::date_to_timestamp($ticket['finnish_date']) : '';
     if ($oldfinnish_date && isset($ticket['finnish_date']) && $ticket['finnish_date']) {
         $this->db->query("update phpgw_helpdesk_tickets set finnish_date2='" . $finnish_date . "' where id='{$id}'", __LINE__, __FILE__);
     } else {
         if (!$oldfinnish_date && isset($ticket['finnish_date']) && $ticket['finnish_date']) {
             $this->db->query("update phpgw_helpdesk_tickets set finnish_date='" . $finnish_date . "' where id='{$id}'", __LINE__, __FILE__);
         }
     }
     if ($oldfinnish_date2 > 0) {
         $oldfinnish_date = $oldfinnish_date2;
     }
     if (isset($ticket['finnish_date']) && $ticket['finnish_date']) {
         if ($oldfinnish_date != $finnish_date) {
             $this->fields_updated = true;
             $this->historylog->add('F', $id, $finnish_date, $oldfinnish_date);
         }
     }
     if (isset($ticket['status']) && $old_status != $ticket['status']) {
         $check_old_custom = (int) trim($old_status, 'C');
         $this->db->query("SELECT * from phpgw_helpdesk_status WHERE id = {$check_old_custom}", __LINE__, __FILE__);
         $this->db->next_record();
         $this->fields_updated = true;
         if ($old_status == 'X' || $this->db->f('closed')) {
             $new_status = $ticket['status'];
             $this->historylog->add('R', $id, $ticket['status'], $old_status);
             $this->db->query("UPDATE phpgw_helpdesk_tickets SET status='{$new_status}' WHERE id= {$id}", __LINE__, __FILE__);
         } else {
             $this->historylog->add($ticket['status'], $id, $ticket['status'], $old_status);
             $this->db->query("UPDATE phpgw_helpdesk_tickets SET status='{$ticket['status']}' WHERE id={$id}", __LINE__, __FILE__);
         }
         $this->check_pending_action($ticket, $id);
     }
     if ($oldassigned != $ticket['assignedto'] && $ticket['assignedto'] != 'ignore') {
         $this->fields_updated = true;
         $value_set = array('assignedto' => $ticket['assignedto']);
         $value_set = $this->db->validate_update($value_set);
         $this->db->query("update phpgw_helpdesk_tickets set {$value_set} where id='{$id}'", __LINE__, __FILE__);
         $this->historylog->add('A', $id, $ticket['assignedto'], $oldassigned);
     }
     if ($oldgroup_id != $ticket['group_id'] && $ticket['group_id'] != 'ignore') {
         $this->fields_updated = true;
         $value_set = array('group_id' => $ticket['group_id']);
         $value_set = $this->db->validate_update($value_set);
         $this->db->query("update phpgw_helpdesk_tickets set {$value_set} where id='{$id}'", __LINE__, __FILE__);
         $this->historylog->add('G', $id, $ticket['group_id'], $oldgroup_id);
     }
     if ($oldpriority != $ticket['priority']) {
         $this->fields_updated = true;
         $this->db->query("update phpgw_helpdesk_tickets set priority='" . $ticket['priority'] . "' where id='{$id}'", __LINE__, __FILE__);
         $this->historylog->add('P', $id, $ticket['priority'], $oldpriority);
     }
     if ($old_contact_id != $ticket['contact_id']) {
         $contact_id = (int) $ticket['contact_id'];
         $this->fields_updated = true;
         $this->db->query("update phpgw_helpdesk_tickets set contact_id={$contact_id} WHERE id={$id}", __LINE__, __FILE__);
     }
     if ($oldcat_id != $ticket['cat_id'] && $ticket['cat_id'] != 'ignore') {
         $this->fields_updated = true;
         $this->db->query("update phpgw_helpdesk_tickets set cat_id='" . $ticket['cat_id'] . "' where id='{$id}'", __LINE__, __FILE__);
         $this->historylog->add('T', $id, $ticket['cat_id'], $oldcat_id);
     }
     if ($old_budget != $ticket['budget']) {
         $this->fields_updated = true;
         $this->db->query("UPDATE phpgw_helpdesk_tickets set budget='" . (int) $ticket['budget'] . "' where id='{$id}'", __LINE__, __FILE__);
         $this->historylog->add('B', $id, $ticket['budget'], $old_budget);
     }
     /*
     			if ($old_billable_rate != $ticket['billable_rate'])
     			{
     				$this->fields_updated = true;
     				$this->db->query("update phpgw_helpdesk_tickets set billable_rate='" . $ticket['billable_rate']
     					. "' where id='$id'",__LINE__,__FILE__);
     				$this->historylog->add('B',$id,$ticket['billable_rate'],$old_billable_rate);
     			}
     */
     if ($old_subject != $ticket['subject']) {
         $this->db->query("UPDATE phpgw_helpdesk_tickets SET subject='" . $ticket['subject'] . "' where id='{$id}'", __LINE__, __FILE__);
         $this->historylog->add('S', $id, $ticket['subject'], $old_subject);
         $receipt['message'][] = array('msg' => lang('Subject has been updated'));
     }
     if ($ticket['billable_hours']) {
         $ticket['billable_hours'] = str_replace(',', '.', $ticket['billable_hours']);
     }
     if ((double) $old_billable_hours != (double) $ticket['billable_hours']) {
         $this->db->query("UPDATE phpgw_helpdesk_tickets SET billable_hours='{$ticket['billable_hours']}'" . " WHERE id='{$id}'", __LINE__, __FILE__);
         $this->historylog->add('H', $id, $ticket['billable_hours'], $old_billable_hours);
         $receipt['message'][] = array('msg' => lang('billable hours has been updated'));
     }
     if ((int) $old_actual_cost != (int) $ticket['actual_cost']) {
         $this->db->query("UPDATE phpgw_helpdesk_tickets SET actual_cost='" . (double) $ticket['actual_cost'] . "' WHERE id='{$id}'", __LINE__, __FILE__);
         $this->historylog->add('AC', $id, (double) $ticket['actual_cost'], $old_actual_cost);
         $receipt['message'][] = array('msg' => lang('actual_cost has been updated'));
     }
     if ((int) $old_order_cat_id != (int) $ticket['order_cat_id']) {
         $this->db->query("UPDATE phpgw_helpdesk_tickets SET order_cat_id='" . (int) $ticket['order_cat_id'] . "' WHERE id='{$id}'", __LINE__, __FILE__);
         $receipt['message'][] = array('msg' => lang('order category has been updated'));
         $this->fields_updated = true;
     }
     if ((int) $old_order_dim1 != (int) $ticket['order_dim1']) {
         $this->db->query("UPDATE phpgw_helpdesk_tickets SET order_dim1='" . (int) $ticket['order_dim1'] . "' WHERE id='{$id}'", __LINE__, __FILE__);
         $receipt['message'][] = array('msg' => lang('order_dim1 has been updated'));
         $this->fields_updated = true;
     }
     if ($old_building_part != $ticket['building_part']) {
         $this->db->query("UPDATE phpgw_helpdesk_tickets SET building_part='" . $ticket['building_part'] . "' WHERE id='{$id}'", __LINE__, __FILE__);
         $receipt['message'][] = array('msg' => lang('building part has been updated'));
         $this->fields_updated = true;
     }
     if ($old_note != $ticket['note'] && $ticket['note']) {
         $this->fields_updated = true;
         $this->historylog->add('C', $id, $ticket['note'], $old_note);
         $_history_id = $this->db->get_last_insert_id('phpgw_helpdesk_history', 'history_id');
         $this->db->query("UPDATE phpgw_helpdesk_history SET publish = 1 WHERE history_id = {$_history_id}", __LINE__, __FILE__);
         unset($_history_id);
     }
     if (isset($ticket['location']) && $ticket['location']) {
         $ticket['location_code'] = implode('-', $ticket['location']);
     }
     if (isset($ticket['location_code']) && $ticket['location_code'] && $oldlocation_code != $ticket['location_code']) {
         $interlink = CreateObject('helpdesk.interlink');
         if ($interlink->get_relation('helpdesk', '.ticket', $id, 'origin') || $interlink->get_relation('helpdesk', '.ticket', $id, 'target')) {
             $receipt['message'][] = array('msg' => lang('location could not be changed'));
         } else {
             $value_set = array();
             if (isset($ticket['street_name']) && $ticket['street_name']) {
                 $address[] = $ticket['street_name'];
                 $address[] = $ticket['street_number'];
                 $value_set['address'] = $this->db->db_addslashes(implode(" ", $address));
             }
             if (!isset($address) || !$address) {
                 $address = isset($ticket['location_name']) ? $this->db->db_addslashes($ticket['location_name']) : '';
                 if ($address) {
                     $value_set['address'] = $address;
                 }
             }
             if (isset($ticket['location_code']) && $ticket['location_code']) {
                 $value_set['location_code'] = $ticket['location_code'];
             }
             $admin_location = CreateObject('helpdesk.soadmin_location');
             $admin_location->read(false);
             // Delete old values for location - in case of moving up in the hierarchy
             $metadata = $this->db->metadata('phpgw_helpdesk_tickets');
             for ($i = 1; $i < $admin_location->total_records + 1; $i++) {
                 if (isset($metadata["loc{$i}"])) {
                     $value_set["loc{$i}"] = false;
                 }
             }
             if (isset($ticket['location']) && is_array($ticket['location'])) {
                 foreach ($ticket['location'] as $column => $value) {
                     $value_set[$column] = $value;
                 }
             }
             if (isset($ticket['extra']) && is_array($ticket['extra'])) {
                 foreach ($ticket['extra'] as $column => $value) {
                     $value_set[$column] = $value;
                 }
             }
             $value_set = $this->db->validate_update($value_set);
             $this->db->query("UPDATE phpgw_helpdesk_tickets SET {$value_set} WHERE id={$id}", __LINE__, __FILE__);
             $this->historylog->add('L', $id, $ticket['location_code'], $oldlocation_code);
             $receipt['message'][] = array('msg' => lang('Location has been updated'));
         }
         unset($interlink);
     }
     if (isset($ticket['make_order']) && $ticket['make_order']) {
         $order_id = execMethod('property.socommon.increment_id', 'helpdesk');
         if ($order_id) {
             $this->db->query("UPDATE phpgw_helpdesk_tickets SET order_id = {$order_id} WHERE id={$id}", __LINE__, __FILE__);
             $this->db->query("INSERT INTO fm_orders (id, type) VALUES ({$order_id}, 'helpdesk')", __LINE__, __FILE__);
         }
     }
     $value_set = array();
     $value_set['vendor_id'] = $ticket['vendor_id'];
     $value_set['b_account_id'] = $ticket['b_account_id'];
     $value_set['order_descr'] = $this->db->db_addslashes($ticket['order_descr']);
     $value_set['ecodimb'] = $ticket['ecodimb'];
     $value_set['budget'] = $ticket['budget'];
     $value_set = $this->db->validate_update($value_set);
     $this->db->query("UPDATE phpgw_helpdesk_tickets SET {$value_set} WHERE id={$id}", __LINE__, __FILE__);
     $this->db->transaction_commit();
     if (isset($this->fields_updated)) {
         $receipt['message'][] = array('msg' => lang('Ticket has been updated'));
         $criteria = array('appname' => 'helpdesk', 'location' => $this->acl_location, 'allrows' => true);
         $custom_functions = $GLOBALS['phpgw']->custom_functions->find($criteria);
         foreach ($custom_functions as $entry) {
             // prevent path traversal
             if (preg_match('/\\.\\./', $entry['file_name'])) {
                 continue;
             }
             $file = PHPGW_SERVER_ROOT . "/helpdesk/inc/custom/{$GLOBALS['phpgw_info']['user']['domain']}/{$entry['file_name']}";
             if ($entry['active'] && is_file($file)) {
                 require_once $file;
             }
         }
     }
     return $receipt;
 }
 function edit_item($values, $values_attribute = '')
 {
     //_debug_array($values);
     //_debug_array($values_attribute);
     $table = 'fm_s_agreement_detail';
     while (is_array($values['extra']) && (list($column, $value) = each($values['extra']))) {
         $value_set[$column] = $value;
     }
     if (isset($values_attribute) and is_array($values_attribute)) {
         foreach ($values_attribute as $entry) {
             if ($entry['datatype'] != 'AB' && $entry['datatype'] != 'VENDOR') {
                 if ($entry['datatype'] == 'C' || $entry['datatype'] == 'T' || $entry['datatype'] == 'V' || $entry['datatype'] == 'link') {
                     $value_set[$entry['name']] = $this->db->db_addslashes($entry['value']);
                 } else {
                     $value_set[$entry['name']] = $entry['value'];
                 }
             }
             if ($entry['history'] == 1) {
                 $this->db->query("SELECT " . $entry['name'] . " from {$table} WHERE agreement_id= " . $values['s_agreement_id'] . " AND id=" . $values['id'], __LINE__, __FILE__);
                 $this->db->next_record();
                 $old_value = $this->db->f($entry['name']);
                 if ($entry['value'] != $old_value) {
                     $history_set[$entry['attrib_id']] = array('value' => $entry['value'], 'date' => phpgwapi_datetime::date_to_timestamp($entry['date']));
                 }
             }
         }
     }
     if ($values['street_name']) {
         $address[] = $values['street_name'];
         $address[] = $values['street_number'];
         $address = $this->db->db_addslashes(implode(" ", $address));
     }
     if (!$address) {
         $address = $this->db->db_addslashes($values['location_name']);
     }
     $value_set['location_code'] = $values['location_code'];
     $value_set['cost'] = $values['cost'];
     $value_set['address'] = $address;
     if ($value_set) {
         $value_set = ',' . $this->db->validate_update($value_set);
     }
     $this->db->query("UPDATE {$table} set entry_date=" . time() . "{$value_set} WHERE agreement_id=" . $values['s_agreement_id'] . ' AND id=' . intval($values['id']));
     $this->db->query("UPDATE fm_s_agreement_pricing set cost = this_index *" . $this->floatval($values['cost']) . " WHERE agreement_id=" . $values['s_agreement_id'] . ' AND item_id=' . intval($values['id']));
     if (isset($history_set) and is_array($history_set)) {
         $historylog = CreateObject('property.historylog', 's_agreement');
         foreach ($history_set as $attrib_id => $history) {
             $historylog->add('SO', $values['s_agreement_id'], $history['value'], false, $attrib_id, $history['date'], $values['id']);
         }
     }
     $receipt['s_agreement_id'] = $values['s_agreement_id'];
     $receipt['id'] = $values['id'];
     $receipt['message'][] = array('msg' => lang('s_agreement %1 has been edited', $values['s_agreement_id']));
     return $receipt;
 }
 function save($request, $action = '', $values_attribute = array())
 {
     while (is_array($request['location']) && (list(, $value) = each($request['location']))) {
         if ($value) {
             $location[] = $value;
         }
     }
     $request['location_code'] = implode("-", $location);
     $request['start_date'] = phpgwapi_datetime::date_to_timestamp($request['start_date']);
     $request['end_date'] = phpgwapi_datetime::date_to_timestamp($request['end_date']);
     $request['planning_date'] = phpgwapi_datetime::date_to_timestamp($request['planning_date']);
     $request['consume_date'] = phpgwapi_datetime::date_to_timestamp($request['consume_date']);
     if (is_array($values_attribute)) {
         $values_attribute = $this->custom->convert_attribute_save($values_attribute);
     }
     if ($action == 'edit') {
         $receipt = $this->so->edit($request, $values_attribute);
     } else {
         $receipt = $this->so->add($request, $values_attribute);
     }
     return $receipt;
 }
 public function populate()
 {
     $this->set_id(phpgw::get_var('id', 'POST', 'int'));
     $this->set_name(phpgw::get_var('name'));
     $this->set_responsible_user_id(phpgw::get_var('responsible_user_id', 'POST', 'int'));
     $this->set_description(phpgw::get_var('description'));
     if (isset($_POST['parent_activity_id'])) {
         $activity_id = phpgw::get_var('parent_activity_id', 'POST', 'int');
         $this->set_parent_id($activity_id ? $activity_id : '');
     } else {
         $this->set_parent_id(phpgw::get_var('parent_id', 'POST', 'int'));
     }
     $this->set_project_id(phpgw::get_var('project_id', 'POST', 'int'));
     $user_id = $GLOBALS['phpgw_info']['user']['id'];
     $this->set_update_user($user_id);
     if ($this->get_id() == '' | $this->get_id() == 0) {
         $this->set_create_user($user_id);
     }
     if (phpgw::get_var('start_date', 'POST', 'string') != '') {
         $start_date_ts = phpgwapi_datetime::date_to_timestamp(phpgw::get_var('start_date', 'POST', 'string'));
         $this->set_start_date($start_date_ts);
     }
     if (phpgw::get_var('end_date', 'POST', 'string') != '') {
         $end_date_ts = phpgwapi_datetime::date_to_timestamp(phpgw::get_var('end_date', 'POST', 'string'));
         $this->set_end_date($end_date_ts);
     }
 }
示例#13
0
 function update_ticket(&$ticket, $id = 0, $receipt = array(), $values_attribute = array(), $simple = false)
 {
     $this->fields_updated = array();
     $id = (int) $id;
     $ticket['id'] = $id;
     // DB Content is fresher than http posted value.
     $this->db->query("SELECT * FROM fm_tts_tickets WHERE id='{$id}'", __LINE__, __FILE__);
     $this->db->next_record();
     $location_code = $this->db->f('location_code');
     $oldlocation_code = $this->db->f('location_code');
     $oldfinnish_date = $this->db->f('finnish_date');
     $oldfinnish_date2 = $this->db->f('finnish_date2');
     $oldassigned = $this->db->f('assignedto');
     $oldgroup_id = $this->db->f('group_id');
     $oldpriority = $this->db->f('priority');
     $oldcat_id = $this->db->f('cat_id');
     $old_status = $this->db->f('status');
     $ticket['old_status'] = $old_status;
     // used for custom functions
     //	$old_budget  			= $this->db->f('budget');
     $old_billable_hours = (double) $this->db->f('billable_hours');
     //	$old_billable_rate	= $this->db->f('billable_rate');
     $old_subject = $this->db->f('subject');
     $old_contact_id = $this->db->f('contact_id');
     $old_order_cat_id = $this->db->f('order_cat_id');
     $old_building_part = $this->db->f('building_part', true);
     $old_order_dim1 = (int) $this->db->f('order_dim1');
     if ($oldcat_id == 0) {
         $oldcat_id = '';
     }
     if ($old_order_cat_id == 0) {
         $old_order_cat_id = '';
     }
     if ($oldassigned == 0) {
         $oldassigned = '';
     }
     if ($oldgroup_id == 0) {
         $oldgroup_id = '';
     }
     // Figure out and last note
     $history_values = $this->historylog->return_array(array(), array('C'), 'history_timestamp', 'DESC', $id);
     $old_note = $history_values[0]['new_value'];
     if (!$old_note) {
         $old_note = $this->db->f('details');
     }
     $this->db->transaction_begin();
     /*
      ** phpgw_fm_tts_append.append_type - Defs
      ** R - Reopen ticket
      ** X - Ticket closed
      ** O - Ticket opened
      ** C - Comment appended
      ** A - Ticket assignment
      ** G - Ticket group assignment
      ** P - Priority change
      ** T - Category change
      ** S - Subject change
      ** B - Budget change
      **	AC - actual cost changed
      ** H - Billing hours
      ** F - finnish date
      ** C% - Status change
      ** L - Location changed
      ** M - Mail sent to vendor
      */
     if (!$simple) {
         $this->db->query("UPDATE fm_tts_tickets SET publish_note = NULL WHERE id = {$id}", __LINE__, __FILE__);
         $this->db->query("UPDATE fm_tts_history SET publish = NULL WHERE history_record_id = {$id}", __LINE__, __FILE__);
         if (isset($ticket['publish_note'])) {
             foreach ($ticket['publish_note'] as $publish_info) {
                 $note = explode('_', $publish_info);
                 if (!$note[1]) {
                     $this->db->query("UPDATE fm_tts_tickets SET publish_note = 1 WHERE id = {$note[0]}", __LINE__, __FILE__);
                 } else {
                     $this->db->query("UPDATE fm_tts_history SET publish = 1 WHERE history_id = {$note[1]}", __LINE__, __FILE__);
                 }
             }
         }
     }
     if ($old_note != $ticket['note'] && $ticket['note']) {
         $this->fields_updated[] = 'note';
         $this->historylog->add('C', $id, $ticket['note'], $old_note);
         $_history_id = $this->db->get_last_insert_id('fm_tts_history', 'history_id');
         $this->db->query("UPDATE fm_tts_history SET publish = 1 WHERE history_id = {$_history_id}", __LINE__, __FILE__);
         unset($_history_id);
     }
     if (isset($this->fields_updated) && $this->fields_updated && $simple) {
         $receipt['message'][] = array('msg' => lang('Ticket1 has been updated'));
         $this->db->transaction_commit();
         return $receipt;
     }
     $finnish_date = isset($ticket['finnish_date']) ? phpgwapi_datetime::date_to_timestamp($ticket['finnish_date']) : '';
     if ($oldfinnish_date && isset($ticket['finnish_date']) && $ticket['finnish_date']) {
         $this->db->query("update fm_tts_tickets set finnish_date2='" . $finnish_date . "' where id='{$id}'", __LINE__, __FILE__);
     } else {
         if (!$oldfinnish_date && isset($ticket['finnish_date']) && $ticket['finnish_date']) {
             $this->db->query("update fm_tts_tickets set finnish_date='" . $finnish_date . "' where id='{$id}'", __LINE__, __FILE__);
         }
     }
     if ($oldfinnish_date2 > 0) {
         $oldfinnish_date = $oldfinnish_date2;
     }
     if (isset($ticket['finnish_date']) && $ticket['finnish_date']) {
         if ($oldfinnish_date != $finnish_date) {
             $this->fields_updated[] = 'finnish_date';
             $this->historylog->add('F', $id, $finnish_date, $oldfinnish_date);
         }
     }
     if (isset($ticket['status']) && $old_status != $ticket['status']) {
         $check_old_custom = (int) trim($old_status, 'C');
         $this->db->query("SELECT * from fm_tts_status WHERE id = {$check_old_custom}", __LINE__, __FILE__);
         $this->db->next_record();
         $old_closed = $this->db->f('closed');
         $this->fields_updated[] = 'status';
         if ($old_status == 'X' || $old_closed) {
             $new_status = $ticket['status'];
             $this->historylog->add('R', $id, $ticket['status'], $old_status);
             $this->db->query("UPDATE fm_tts_tickets SET status='{$new_status}' WHERE id= {$id}", __LINE__, __FILE__);
         } else {
             $this->historylog->add($ticket['status'], $id, $ticket['status'], $old_status);
             $this->db->query("UPDATE fm_tts_tickets SET status='{$ticket['status']}' WHERE id={$id}", __LINE__, __FILE__);
         }
         $this->check_pending_action($ticket, $id);
         //Close cases at related
         $check_new_custom = (int) trim($ticket['status'], 'C');
         $this->db->query("SELECT closed from fm_tts_status WHERE id = {$check_new_custom}", __LINE__, __FILE__);
         $this->db->next_record();
         if (($this->db->f('closed') || $ticket['status'] == 'X') && ($old_status != 'X' && !$old_closed)) {
             $location_id = $GLOBALS['phpgw']->locations->get_id('property', '.ticket');
             // at controller
             if (isset($GLOBALS['phpgw_info']['user']['apps']['controller'])) {
                 $controller = CreateObject('controller.uicase');
                 $controller->updateStatusForCases($location_id, $id, 1);
             }
             // at request
             execMethod('property.sorequest.update_status_from_related', array('location_id' => $location_id, 'id' => $id, 'status' => 'closed'));
         }
     }
     if ($ticket['assignedto'] && ($oldassigned != $ticket['assignedto'] && $ticket['assignedto'] != 'ignore')) {
         $this->fields_updated[] = 'assignedto';
         $value_set = array('assignedto' => $ticket['assignedto']);
         $value_set = $this->db->validate_update($value_set);
         $this->db->query("update fm_tts_tickets set {$value_set} where id='{$id}'", __LINE__, __FILE__);
         $this->historylog->add('A', $id, $ticket['assignedto'], $oldassigned);
     }
     if ($oldgroup_id != $ticket['group_id'] && $ticket['group_id'] != 'ignore') {
         $this->fields_updated[] = 'group_id';
         $value_set = array('group_id' => $ticket['group_id']);
         $value_set = $this->db->validate_update($value_set);
         $this->db->query("update fm_tts_tickets set {$value_set} where id='{$id}'", __LINE__, __FILE__);
         $this->historylog->add('G', $id, $ticket['group_id'], $oldgroup_id);
     }
     if ($oldpriority != $ticket['priority']) {
         $this->fields_updated[] = 'priority';
         $this->db->query("update fm_tts_tickets set priority='" . $ticket['priority'] . "' where id='{$id}'", __LINE__, __FILE__);
         $this->historylog->add('P', $id, $ticket['priority'], $oldpriority);
     }
     if ($old_contact_id != $ticket['contact_id']) {
         $contact_id = (int) $ticket['contact_id'];
         $this->fields_updated[] = 'contact_id';
         $this->db->query("update fm_tts_tickets set contact_id={$contact_id} WHERE id={$id}", __LINE__, __FILE__);
     }
     if ($ticket['cat_id'] && ($oldcat_id != $ticket['cat_id'] && $ticket['cat_id'] != 'ignore')) {
         $this->fields_updated[] = 'cat_id';
         $this->db->query("update fm_tts_tickets set cat_id='" . $ticket['cat_id'] . "' where id='{$id}'", __LINE__, __FILE__);
         $this->historylog->add('T', $id, $ticket['cat_id'], $oldcat_id);
     }
     /*
     			if ($old_billable_rate != $ticket['billable_rate'])
     			{
     				$this->fields_updated[] = 'billable_rate';
     				$this->db->query("update fm_tts_tickets set billable_rate='" . $ticket['billable_rate']
     					. "' where id='$id'",__LINE__,__FILE__);
     				$this->historylog->add('B',$id,$ticket['billable_rate'],$old_billable_rate);
     			}
     */
     if ($old_subject != $ticket['subject']) {
         $this->db->query("UPDATE fm_tts_tickets SET subject='" . $ticket['subject'] . "' where id='{$id}'", __LINE__, __FILE__);
         $this->historylog->add('S', $id, $ticket['subject'], $old_subject);
         $receipt['message'][] = array('msg' => lang('Subject has been updated'));
     }
     if ($ticket['billable_hours']) {
         $ticket['billable_hours'] = (double) str_replace(',', '.', $ticket['billable_hours']);
         $ticket['billable_hours'] += (double) $old_billable_hours;
         //			}
         //			if ((float)$old_billable_hours != $ticket['billable_hours'])
         //			{
         $this->db->query("UPDATE fm_tts_tickets SET billable_hours='{$ticket['billable_hours']}'" . " WHERE id='{$id}'", __LINE__, __FILE__);
         $this->historylog->add('H', $id, $ticket['billable_hours'], $old_billable_hours);
         $receipt['message'][] = array('msg' => lang('billable hours has been updated'));
     }
     if (isset($ticket['location']) && $ticket['location']) {
         $ticket['location_code'] = implode('-', $ticket['location']);
     }
     if (isset($ticket['location_code']) && $ticket['location_code'] && $oldlocation_code != $ticket['location_code']) {
         $interlink = CreateObject('property.interlink');
         if ($interlink->get_relation('property', '.ticket', $id, 'origin') || $interlink->get_relation('property', '.ticket', $id, 'target')) {
             $receipt['message'][] = array('msg' => lang('location could not be changed'));
         } else {
             $value_set = array();
             $_address = array();
             if (isset($ticket['street_name']) && $ticket['street_name']) {
                 $_address[] = "{$ticket['street_name']} {$ticket['street_number']}";
             }
             if (isset($ticket['location_name']) && $ticket['location_name']) {
                 $_address[] = $ticket['location_name'];
             }
             if (isset($ticket['additional_info']) && $ticket['additional_info']) {
                 foreach ($ticket['additional_info'] as $key => $value) {
                     if ($value) {
                         $_address[] = "{$key}|{$value}";
                     }
                 }
             }
             if (isset($ticket['extra']['p_num']) && $ticket['extra']['p_num'] && $ticket['extra']['p_entity_id'] && $ticket['extra']['p_cat_id']) {
                 $entity = CreateObject('property.soadmin_entity');
                 $entity_category = $entity->read_single_category($ticket['extra']['p_entity_id'], $ticket['extra']['p_cat_id']);
             }
             if (isset($entity_category) && $entity_category) {
                 $_address[] = "{$entity_category['name']}::{$ticket['extra']['p_num']}";
             }
             $address = $this->db->db_addslashes(implode('::', $_address));
             unset($_address);
             $value_set['address'] = $address;
             if (isset($ticket['location_code']) && $ticket['location_code']) {
                 $value_set['location_code'] = $ticket['location_code'];
             }
             $admin_location = CreateObject('property.soadmin_location');
             $admin_location->read(false);
             // Delete old values for location - in case of moving up in the hierarchy
             $metadata = $this->db->metadata('fm_tts_tickets');
             for ($i = 1; $i < $admin_location->total_records + 1; $i++) {
                 if (isset($metadata["loc{$i}"])) {
                     $value_set["loc{$i}"] = false;
                 }
             }
             if (isset($ticket['location']) && is_array($ticket['location'])) {
                 foreach ($ticket['location'] as $column => $value) {
                     $value_set[$column] = $value;
                 }
             }
             $value_set = $this->db->validate_update($value_set);
             $this->db->query("UPDATE fm_tts_tickets SET {$value_set} WHERE id={$id}", __LINE__, __FILE__);
             $this->historylog->add('L', $id, $ticket['location_code'], $oldlocation_code);
             $receipt['message'][] = array('msg' => lang('Location has been updated'));
         }
         unset($interlink);
     }
     if (isset($ticket['make_order']) && $ticket['make_order']) {
         $order_id = execMethod('property.socommon.increment_id', 'order');
         if ($order_id) {
             $this->db->query("UPDATE fm_tts_tickets SET order_id = {$order_id} WHERE id={$id}", __LINE__, __FILE__);
         }
     }
     $value_set = array();
     $data_attribute = $this->custom->prepare_for_db('fm_tts_tickets', $values_attribute);
     if (isset($data_attribute['value_set'])) {
         foreach ($data_attribute['value_set'] as $input_name => $value) {
             $value_set[$input_name] = $value;
         }
     }
     $value_set['modified_date'] = time();
     // check order-rights
     $order_add = $GLOBALS['phpgw']->acl->check('.ticket.order', PHPGW_ACL_ADD, 'property');
     $order_edit = $GLOBALS['phpgw']->acl->check('.ticket.order', PHPGW_ACL_EDIT, 'property');
     if ($order_add || $order_edit) {
         if ((int) $ticket['budget']) {
             $this->db->query("SELECT sum(amount) AS budget FROM fm_tts_budget WHERE ticket_id = {$id}", __LINE__, __FILE__);
             $this->db->next_record();
             $old_budget = $this->db->f('budget');
             $new_budget = str_replace(',', '.', $old_budget + $ticket['budget']);
             $this->db->query("UPDATE fm_tts_tickets SET budget='{$new_budget}' WHERE id='{$id}'", __LINE__, __FILE__);
             $value_set_cost = array('ticket_id' => $id, 'amount' => str_replace(',', '.', $ticket['budget']), 'period' => $ticket['budget_period'] . '01', 'created_on' => time(), 'created_by' => $this->account);
             $cols_cost = implode(',', array_keys($value_set_cost));
             $values_cost = $this->db->validate_insert(array_values($value_set_cost));
             $this->db->query("INSERT INTO fm_tts_budget ({$cols_cost}) VALUES ({$values_cost})");
             $this->historylog->add('B', $id, (double) $new_budget, $old_budget);
             $receipt['message'][] = array('msg' => lang('budget changed'));
         }
         if ((int) $ticket['actual_cost']) {
             $this->db->query("SELECT sum(amount) AS actual_cost FROM fm_tts_payments WHERE ticket_id = {$id}", __LINE__, __FILE__);
             $this->db->next_record();
             $old_actual_cost = $this->db->f('actual_cost');
             $new_actual_cost = str_replace(',', '.', $old_actual_cost + $ticket['actual_cost']);
             $this->db->query("UPDATE fm_tts_tickets SET actual_cost='{$new_actual_cost}' WHERE id='{$id}'", __LINE__, __FILE__);
             $value_set_cost = array('ticket_id' => $id, 'amount' => str_replace(',', '.', $ticket['actual_cost']), 'period' => $ticket['actual_cost_period'], 'created_on' => time(), 'created_by' => $this->account);
             $cols_cost = implode(',', array_keys($value_set_cost));
             $values_cost = $this->db->validate_insert(array_values($value_set_cost));
             $this->db->query("INSERT INTO fm_tts_payments ({$cols_cost}) VALUES ({$values_cost})");
             $this->historylog->add('AC', $id, (double) $new_actual_cost, $old_actual_cost);
             $receipt['message'][] = array('msg' => lang('actual cost has been updated'));
         }
         if ((int) $old_order_cat_id != (int) $ticket['order_cat_id']) {
             $this->db->query("UPDATE fm_tts_tickets SET order_cat_id='" . (int) $ticket['order_cat_id'] . "' WHERE id='{$id}'", __LINE__, __FILE__);
             $receipt['message'][] = array('msg' => lang('order category has been updated'));
             $this->fields_updated[] = 'order_cat_id';
         }
         if ((int) $old_order_dim1 != (int) $ticket['order_dim1']) {
             $this->db->query("UPDATE fm_tts_tickets SET order_dim1='" . (int) $ticket['order_dim1'] . "' WHERE id='{$id}'", __LINE__, __FILE__);
             $receipt['message'][] = array('msg' => lang('order_dim1 has been updated'));
             $this->fields_updated[] = 'order_dim1';
         }
         if ($old_building_part != $ticket['building_part']) {
             $this->db->query("UPDATE fm_tts_tickets SET building_part='" . $ticket['building_part'] . "' WHERE id='{$id}'", __LINE__, __FILE__);
             $receipt['message'][] = array('msg' => lang('building part has been updated'));
             $this->fields_updated[] = 'building_part';
         }
         /*
         				if ($old_budget != $ticket['budget'])
         				{
         					$this->fields_updated[] = 'budget';
         					$this->db->query("UPDATE fm_tts_tickets set budget='" . (int)$ticket['budget']
         						. "' where id='$id'",__LINE__,__FILE__);
         					$this->historylog->add('B',$id,$ticket['budget'],$old_budget);
         				}
         */
         $value_set['vendor_id'] = $ticket['vendor_id'];
         $value_set['b_account_id'] = $ticket['b_account_id'];
         $value_set['order_descr'] = $this->db->db_addslashes($ticket['order_descr']);
         $value_set['ecodimb'] = $ticket['ecodimb'];
         $value_set['branch_id'] = $ticket['branch_id'];
     }
     $value_set = $this->db->validate_update($value_set);
     $this->db->query("UPDATE fm_tts_tickets SET {$value_set} WHERE id={$id}", __LINE__, __FILE__);
     $value_set = array();
     if (isset($ticket['extra']) && is_array($ticket['extra'])) {
         foreach ($ticket['extra'] as $column => $value) {
             $value_set[$column] = $value;
         }
         $value_set = $this->db->validate_update($value_set);
         $this->db->query("UPDATE fm_tts_tickets SET {$value_set} WHERE id={$id}", __LINE__, __FILE__);
     }
     $this->db->transaction_commit();
     if (isset($this->fields_updated) && $this->fields_updated) {
         $receipt['message'][] = array('msg' => lang('Ticket has been updated'));
     }
     return $receipt;
 }
 function date_to_timestamp($date = array())
 {
     return phpgwapi_datetime::date_to_timestamp($date);
 }
 public function read($dry_run = '')
 {
     $start_date = phpgwapi_datetime::date_to_timestamp($this->start_date);
     $end_date = phpgwapi_datetime::date_to_timestamp($this->end_date);
     $valid_locations = $this->get_gallery_location();
     $values = $this->so->read(array('start' => $this->start, 'query' => $this->query, 'sort' => $this->sort, 'order' => $this->order, 'allrows' => $this->allrows, 'location_id' => $this->location_id, 'user_id' => $this->user_id, 'mime_type' => $this->mime_type, 'start_date' => $start_date, 'end_date' => $end_date, 'cat_id' => $this->cat_id, 'valid_locations' => $valid_locations, 'dry_run' => $dry_run));
     $img_types = array('image/jpeg', 'image/png', 'image/gif');
     static $locations = array();
     static $urls = array();
     $dateformat = $GLOBALS['phpgw_info']['user']['preferences']['common']['dateformat'];
     $i = 0;
     foreach ($values as &$entry) {
         if (!$entry['mime_type']) {
             $entry['mime_type'] = $this->mime_magic->filename2mime($entry['name']);
         }
         $entry['img_id'] = '';
         if (in_array($entry['mime_type'], $img_types)) {
             $entry['img_id'] = "img-{$i}";
             $i++;
         }
         $entry['date'] = $GLOBALS['phpgw']->common->show_date(strtotime($entry['created']), $dateformat);
         $directory = explode('/', $entry['directory']);
         $location = $this->get_location($directory);
         $entry['location'] = $location['location'];
         $entry['location_item_id'] = $location['location_item_id'];
         $entry['url'] = $this->interlink->get_relation_link($entry['location'], $entry['location_item_id']);
         $entry['location_name'] = $this->interlink->get_location_name($entry['location']);
         $entry['document_url'] = $GLOBALS['phpgw']->link('/index.php', array('menuaction' => 'property.uigallery.view_file', 'file' => urlencode("{$entry['directory']}/{$entry['name']}")));
         $entry['user'] = $GLOBALS['phpgw']->accounts->get($entry['createdby_id'])->__toString();
     }
     //_debug_array($values);
     $this->total_records = $this->so->total_records;
     return $values;
 }
 public function edit($data)
 {
     $active_from = phpgwapi_datetime::date_to_timestamp($data['active_from']);
     $active_to = phpgwapi_datetime::date_to_timestamp($data['active_to']);
     $delete = isset($data['delete']) && is_array($data['delete']) ? $data['delete'] : array();
     $default_user = isset($data['default_user']) && is_array($data['default_user']) ? $data['default_user'] : array();
     $alter_date = isset($data['alter_date']) && is_array($data['alter_date']) ? $data['alter_date'] : array();
     $add = isset($data['add']) && is_array($data['add']) ? $data['add'] : array();
     $this->db->transaction_begin();
     $c_default_user = 0;
     foreach ($default_user as $id) {
         if (!in_array($id, $delete)) {
             $this->db->query("UPDATE fm_ecodimb_role_user SET default_user = 1 WHERE id = '{$id}'", __LINE__, __FILE__);
             $c_default_user++;
         }
     }
     unset($id);
     $c_alter_date = 0;
     foreach ($alter_date as $id) {
         if (!in_array($id, $delete)) {
             $value_set = array();
             if ($active_from) {
                 $value_set['active_from'] = $active_from;
             }
             if ($active_to) {
                 $value_set['active_to'] = $active_to;
             }
             if ($value_set) {
                 $value_set = $this->db->validate_update($value_set);
                 $this->db->query("UPDATE fm_ecodimb_role_user SET {$value_set} WHERE id = '{$id}'", __LINE__, __FILE__);
                 unset($value_set);
             }
             $c_alter_date++;
         }
     }
     unset($id);
     foreach ($add as $info) {
         $user_arr = explode('_', $info);
         $value_set = array('ecodimb' => $user_arr[0], 'role_id' => $user_arr[1], 'user_id' => $user_arr[2], 'default_user' => false, 'active_from' => $active_from ? $active_from : time(), 'active_to' => $active_to ? $active_to : 0, 'created_on' => time(), 'created_by' => $this->account_id);
         $sql = 'INSERT INTO fm_ecodimb_role_user (' . implode(',', array_keys($value_set)) . ') VALUES (' . $this->db->validate_insert(array_values($value_set)) . ')';
         $this->db->query($sql, __LINE__, __FILE__);
     }
     $ok = false;
     if ($this->db->transaction_commit()) {
         $ok = true;
         foreach ($delete as $id) {
             $this->db->query('UPDATE fm_ecodimb_role_user SET expired_on =' . time() . " , expired_by = {$this->account_id} WHERE id = '{$id}'", __LINE__, __FILE__);
         }
         if ($delete) {
             phpgwapi_cache::message_set(lang('%1 roles deleted', count($delete)), 'message');
         }
         if ($c_alter_date) {
             phpgwapi_cache::message_set(lang('%1 dates altered', $c_alter_date), 'message');
         }
         if ($add) {
             phpgwapi_cache::message_set(lang('%1 roles added', count($add)), 'message');
         }
         if ($c_default_user) {
             phpgwapi_cache::message_set(lang('%1 roles set at default', $c_default_user), 'message');
         }
     }
     return $ok;
 }
 function add_manual_invoice($values, $skip_update_voucher_id = false)
 {
     $orders_affected = array();
     $_dateformat = $this->db->date_format();
     if (!$this->supertransaction) {
         $this->db->transaction_begin();
     }
     $num = $this->add($values, $skip_update_voucher_id);
     $this->voucher_id = $values[0]['bilagsnr'];
     $voucher = $this->get_voucher($values[0]['bilagsnr']);
     foreach ($voucher as &$line) {
         $line['overftid'] = date($_dateformat, phpgwapi_datetime::date_to_timestamp($values[0]['paid_date']));
         $line['ordrebelop'] = $line['godkjentbelop'];
         $line['filnavn'] = 'dummy';
         $line['oppsynsigndato'] = date($_dateformat);
         $line['saksigndato'] = date($_dateformat);
         $line['budsjettsigndato'] = date($_dateformat);
         $line['utbetalingsigndato'] = date($_dateformat);
         $line['utbetalingid'] = $GLOBALS['phpgw']->accounts->get($this->account_id)->lid;
         $line['manual_record'] = 1;
         $this->add_OverfBilag($line);
     }
     $this->delete_voucher_from_fm_ecobilag($values[0]['bilagsnr']);
     reset($voucher);
     if ($this->debug) {
         return true;
     }
     foreach ($voucher as &$line) {
         if ($line['order_id']) {
             $amount = $line['godkjentbelop'] * 100;
             //Oppdater beløp på bestilling
             if ($line['dimd'] % 2 == 0) {
                 $actual_cost_field = 'act_mtrl_cost';
             } else {
                 $actual_cost_field = 'act_vendor_cost';
             }
             $operator = '+';
             if (!$this->debug) {
                 //notify_coordinator_on_consumption is performed here..
                 $this->correct_actual_cost($line['order_id'], $amount, $actual_cost_field, $operator);
             }
         }
     }
     $this->update_actual_cost_from_archive($orders_affected);
     if (!$this->supertransaction) {
         return $this->db->transaction_commit();
     } else {
         return $num;
     }
 }
 function edit_value($values)
 {
     if (isset($values['input_type']) && $values['input_type'] == 'date') {
         $values['value'] = phpgwapi_datetime::date_to_timestamp($values['value']);
     }
     if (!$values['value']) {
         $this->delete_value($values['section_id'], $values['attrib_id'], $values['id']);
     } else {
         if ($this->db->get_transaction()) {
             $this->global_lock = true;
         } else {
             $this->db->transaction_begin();
         }
         $value_set['value'] = $this->db->db_addslashes($values['value']);
         $value_set = $this->db->validate_update($value_set);
         $this->db->query("UPDATE phpgw_config2_value SET {$value_set} WHERE section_id =" . (int) $values['section_id'] . ' AND attrib_id=' . (int) $values['attrib_id'] . ' AND id=' . (int) $values['id'], __LINE__, __FILE__);
         if (!$this->global_lock) {
             $this->db->transaction_commit();
         }
     }
     $receipt['message'][] = array('msg' => lang('config value has been edited'));
     $receipt['id'] = $values['id'];
     return $receipt;
 }
 function save($project, $action = '', $values_attribute = array())
 {
     //_debug_array($project);
     while (is_array($project['location']) && (list(, $value) = each($project['location']))) {
         if ($value) {
             $location[] = $value;
         }
     }
     $project['location_code'] = implode("-", $location);
     $project['start_date'] = phpgwapi_datetime::date_to_timestamp($project['start_date']);
     $project['end_date'] = phpgwapi_datetime::date_to_timestamp($project['end_date']);
     if (is_array($values_attribute)) {
         $values_attribute = $this->custom->convert_attribute_save($values_attribute);
     }
     // Custom rules - pre commit
     $criteria = array('appname' => 'property', 'location' => '.project', 'allrows' => true);
     $custom_functions = $GLOBALS['phpgw']->custom_functions->find($criteria);
     foreach ($custom_functions as $entry) {
         // prevent path traversal
         if (preg_match('/\\.\\./', $entry['file_name'])) {
             continue;
         }
         $file = PHPGW_SERVER_ROOT . "/property/inc/custom/{$GLOBALS['phpgw_info']['user']['domain']}/{$entry['file_name']}";
         if ($entry['active'] && is_file($file) && !$entry['client_side'] && $entry['pre_commit']) {
             require_once $file;
         }
     }
     unset($entry);
     reset($custom_functions);
     if ($action == 'edit') {
         try {
             $receipt = $this->so->edit($project, $values_attribute);
         } catch (Exception $e) {
             if ($e) {
                 phpgwapi_cache::message_set($e->getMessage(), 'error');
                 $receipt['id'] = $project['id'];
             }
         }
         if (isset($project['send_order']) && $project['send_order']) {
             $uiwo_hour = CreateObject('property.uiwo_hour');
             foreach ($project['send_order'] as $_order_id) {
                 try {
                     $uiwo_hour->send_order($_order_id);
                 } catch (Exception $e) {
                     if ($e) {
                         phpgwapi_cache::message_set($e->getMessage(), 'error');
                     }
                 }
             }
         }
     } else {
         $receipt = $this->so->add($project, $values_attribute);
     }
     foreach ($custom_functions as $entry) {
         // prevent path traversal
         if (preg_match('/\\.\\./', $entry['file_name'])) {
             continue;
         }
         $file = PHPGW_SERVER_ROOT . "/property/inc/custom/{$GLOBALS['phpgw_info']['user']['domain']}/{$entry['file_name']}";
         if ($entry['active'] && is_file($file) && !$entry['client_side'] && !$entry['pre_commit']) {
             require_once $file;
         }
     }
     return $receipt;
 }
 public function edit($data)
 {
     $table = 'fm_condition_survey';
     $id = (int) $data['id'];
     $value_set = $this->_get_value_set($data);
     $value_set['title'] = $this->_db->db_addslashes($data['title']);
     $value_set['descr'] = $this->_db->db_addslashes($data['descr']);
     $value_set['status_id'] = (int) $data['status_id'];
     $value_set['category'] = (int) $data['cat_id'];
     $value_set['vendor_id'] = (int) $data['vendor_id'];
     $value_set['coordinator_id'] = (int) $data['coordinator_id'];
     $value_set['report_date'] = phpgwapi_datetime::date_to_timestamp($data['report_date']);
     $value_set['user_id'] = $this->account;
     $value_set['modified_date'] = time();
     $value_set['multiplier'] = (double) $data['multiplier'];
     $this->_db->query("SELECT coordinator_id FROM fm_condition_survey WHERE id = {$id}", __LINE__, __FILE__);
     $this->_db->next_record();
     $old_coordinator_id = (int) $this->_db->f('coordinator_id');
     $this->_db->transaction_begin();
     try {
         $this->_db->Exception_On_Error = true;
         if ($old_coordinator_id != $value_set['coordinator_id']) {
             $this->_db->query("UPDATE fm_request SET coordinator = {$value_set['coordinator_id']} WHERE condition_survey_id = {$id}", __LINE__, __FILE__);
         }
         $this->_edit($id, $value_set, 'fm_condition_survey');
         $this->_db->query("UPDATE fm_request SET multiplier = '{$data['multiplier']}' WHERE condition_survey_id = {$id}", __LINE__, __FILE__);
         $this->_db->Exception_On_Error = false;
     } catch (Exception $e) {
         if ($e) {
             $this->_db->transaction_abort();
             throw $e;
         }
     }
     $this->_db->transaction_commit();
     return $id;
 }
 public function populate()
 {
     $this->set_id(phpgw::get_var('id'));
     $this->set_activity_id(phpgw::get_var('activity_id'));
     $this->set_no_of_items(phpgw::get_var('no_of_items'));
     $this->set_location_id(phpgw::get_var('location_id'));
     $this->set_create_user(phpgw::get_var('create_user'));
     if ($this->get_id() == '' | $this->get_id() == 0) {
         $user_id = $GLOBALS['phpgw_info']['user']['id'];
         $this->set_create_user($user_id);
     }
     if (phpgw::get_var('start_date', 'string') != '') {
         $start_date_ts = phpgwapi_datetime::date_to_timestamp(phpgw::get_var('start_date', 'string'));
         $this->set_start_date($start_date_ts);
     }
     if (phpgw::get_var('end_date', 'string') != '') {
         $end_date_ts = phpgwapi_datetime::date_to_timestamp(phpgw::get_var('end_date', 'string'));
         $this->set_end_date($end_date_ts);
     }
 }
 public function add_manual_invoice($values)
 {
     $receipt = array();
     $config = CreateObject('admin.soconfig', $GLOBALS['phpgw']->locations->get_id('property', '.invoice'));
     $buffer = array();
     $soXport = CreateObject('property.soXport');
     $soXport->supertransaction = $this->supertransaction;
     $soXport->debug = $this->debug;
     if ($values['loc1'] = $values['location']['loc1']) {
         $values['dima'] = implode('', $values['location']);
         $values['location_code'] = explode('-', $values['location']);
     }
     $values['spbudact_code'] = $values['b_account_id'];
     $values['fakturanr'] = $values['invoice_id'];
     $values['spvend_code'] = $values['vendor_id'];
     $values['belop'] = $values['amount'];
     $values['godkjentbelop'] = $values['amount'];
     $_dateformat = $GLOBALS['phpgw']->db->date_format();
     $invoice_date = $values['invoice_date'] ? phpgwapi_datetime::date_to_timestamp($values['invoice_date']) : time();
     $payment_date = $values['payment_date'] ? phpgwapi_datetime::date_to_timestamp($values['payment_date']) : time();
     $paid_date = $values['paid_date'] ? phpgwapi_datetime::date_to_timestamp($values['paid_date']) : time();
     $values['fakturadato'] = date($_dateformat, $invoice_date);
     $values['forfallsdato'] = date($_dateformat, $payment_date);
     $values['periode'] = date('Ym', $paid_date);
     $values['kildeid'] = 1;
     $values['pmwrkord_code'] = $values['order_id'];
     if (isset($config->config_data['common']['manual_voucher_id']) && $config->config_data['common']['manual_voucher_id']) {
         if ($soXport->check_voucher_id($values['voucher_out_id'])) {
             $receipt['error'][] = array('msg' => lang('voucher id already taken'));
         }
         $skip_update_voucher_id = true;
         $values['bilagsnr'] = $values['voucher_out_id'];
         $values['bilagsnr_ut'] = '';
     } else {
         $skip_update_voucher_id = false;
         $values['bilagsnr'] = execMethod('property.socommon.increment_id', 'Bilagsnummer');
         $values['bilagsnr_ut'] = $values['voucher_out_id'];
     }
     if ($soXport->check_invoice_id($values['vendor_id'], $values['invoice_id'])) {
         $receipt['error'][] = array('msg' => lang('invoice id already taken for this vendor'));
     }
     if (isset($receipt['error'])) {
         return $receipt;
     }
     $values['kostra_id'] = $soXport->get_kostra_id($values['loc1']);
     $values['mvakode'] = (int) $values['tax_code'];
     $values['project_id'] = $values['project_group'];
     $values['oppsynsmannid'] = $values['janitor'];
     $values['saksbehandlerid'] = $values['supervisor'];
     $values['budsjettansvarligid'] = $values['budget_responsible'];
     if ($values['order_id'] && ($order_type = $soXport->check_order($values['order_id']))) {
         if ($order_type == 'workorder') {
             $buffer[0] = $values;
         }
         if ($order_type == 's_agreement') {
             $sos_agreement = CreateObject('property.sos_agreement');
             $s_agreement = $sos_agreement->read_single($values['order_id']);
             //		$values = $this->set_responsible($values,$s_agreement['user_id'],$s_agreement['b_account_id']);
             $s_agreement_detail = $sos_agreement->read(array('allrows' => true, 's_agreement_id' => $values['order_id'], 'detail' => true));
             $sum_agreement = 0;
             for ($i = 0; $i < count($s_agreement_detail); $i++) {
                 $s_agreement_detail[$i]['cost'] = abs($s_agreement_detail[$i]['cost']) > 0 ? $s_agreement_detail[$i]['cost'] : 1;
                 $sum_agreement = $sum_agreement + $s_agreement_detail[$i]['cost'];
             }
             for ($i = 0; $i < count($s_agreement_detail); $i++) {
                 $_location = explode('-', $s_agreement_detail[$i]['location_code']);
                 $buffer[$i] = $values;
                 $buffer[$i]['location_code'] = $s_agreement_detail[$i]['location_code'];
                 $buffer[$i]['loc1'] = $_location[0];
                 $buffer[$i]['dima'] = str_replace('-', '', $s_agreement_detail[$i]['location_code']);
                 $buffer[$i]['belop'] = round($values['belop'] / $sum_agreement * $s_agreement_detail[$i]['cost'], 2);
                 $buffer[$i]['godkjentbelop'] = $buffer[$i]['belop'];
             }
         }
         if ($soXport->add_manual_invoice($buffer, $skip_update_voucher_id)) {
             $_msg = $this->debug ? 'DEBUG: ' : '';
             $receipt['message'][] = array('msg' => $_msg . lang('Invoice %1 is added', $soXport->voucher_id));
             $receipt['voucher_id'] = $soXport->voucher_id;
         } else {
             $receipt['error'][] = array('msg' => lang('Invoice is NOT added!'));
         }
     }
     return $receipt;
 }
 function update_control_serie()
 {
     if ($start_date = phpgw::get_var('control_start_date', 'string')) {
         phpgw::import_class('phpgwapi.datetime');
         $start_date = phpgwapi_datetime::date_to_timestamp($start_date);
     }
     $so_control = CreateObject('controller.socontrol');
     $values = array('ids' => phpgw::get_var('ids', 'int'), 'action' => phpgw::get_var('action', 'string'), 'assigned_to' => phpgw::get_var('control_responsible', 'int'), 'start_date' => $start_date, 'repeat_interval' => phpgw::get_var('repeat_interval', 'int'), 'controle_time' => phpgw::get_var('controle_time', 'float'), 'service_time' => phpgw::get_var('service_time', 'float'));
     $ret = $so_control->update_control_serie($values);
     if ($ret) {
         $result = array('status_kode' => 'ok', 'status' => 'Ok', 'msg' => lang('updated'));
     } else {
         $result = array('status_kode' => 'error', 'status' => lang('error'), 'msg' => 'Noe gikk galt');
     }
     return $result;
 }
    function prepare_for_db($table, $values_attribute, $id = 0)
    {
        $id = (int) $id;
        $data = array();
        if (isset($values_attribute) && is_array($values_attribute)) {
            foreach ($values_attribute as $entry) {
                if ($entry['disabled']) {
                    continue;
                }
                switch ($entry['datatype']) {
                    case 'C':
                    case 'T':
                    case 'V':
                    case 'link':
                    case 'email':
                    case 'link':
                        $data['value_set'][$entry['name']] = isset($entry['value']) && $entry['value'] ? $this->_db2->db_addslashes(phpgw::clean_value($entry['value'], 'string')) : '';
                        $entry['value'] = $this->_db2->db_addslashes($entry['value']);
                        // in case of history entries
                        break;
                    case 'LB':
                    case 'R':
                    case 'AB':
                    case 'ABO':
                    case 'AB':
                    case 'ABO':
                    case 'VENDOR':
                    case 'event':
                    case 'I':
                    case 'custom3':
                    case 'user':
                        $data['value_set'][$entry['name']] = isset($entry['value']) && $entry['value'] ? phpgw::clean_value($entry['value'], 'int') : '';
                        break;
                    case 'bolean':
                        $data['value_set'][$entry['name']] = isset($entry['value']) && $entry['value'] ? phpgw::clean_value($entry['value'], 'bool') : '';
                        break;
                    case 'N':
                        $data['value_set'][$entry['name']] = isset($entry['value']) && $entry['value'] ? phpgw::clean_value($entry['value'], 'float') : '';
                        break;
                    case 'CH':
                        $_value = ',' . implode(',', phpgw::clean_value($entry['value'])) . ',';
                        $data['value_set'][$entry['name']] = isset($entry['value']) && $entry['value'] ? $_value : '';
                        break;
                    case 'D':
                    case 'DT':
                        $data['value_set'][$entry['name']] = isset($entry['value']) && $entry['value'] ? $entry['value'] : '';
                        break;
                    case 'pwd':
                        if ($entry['value'] && $entry['value2']) {
                            if ($entry['value'] || $entry['value2']) {
                                if ($entry['value'] == $entry['value2']) {
                                    $data['value_set'][$entry['name']] = md5($entry['value']);
                                } else {
                                    throw new Exception(lang('Passwords do not match!'));
                                }
                            }
                        } else {
                            $data['value_set'][$entry['name']] = isset($entry['value']) ? $entry['value'] : '';
                        }
                        break;
                    default:
                        $data['value_set'][$entry['name']] = isset($entry['value']) && $entry['value'] ? $this->_db2->db_addslashes(phpgw::clean_value($entry['value'], 'string')) : '';
                }
                if ($entry['history'] == 1) {
                    if ($id) {
                        $this->_db2->query("SELECT {$entry['name']} FROM {$table} WHERE id = {$id}", __LINE__, __FILE__);
                        $this->_db2->next_record();
                        $old_value = $this->_db2->f($entry['name']);
                        if ($entry['value'] != $old_value) {
                            $data['history_set'][$entry['attrib_id']] = array('
									value' => $entry['value'], 'date' => phpgwapi_datetime::date_to_timestamp($entry['date']));
                        }
                    } else {
                        $data['history_set'][$entry['attrib_id']] = $entry['value'];
                    }
                }
            }
        }
        return $data;
    }
 public function bulk_update_status($start_date, $end_date, $status_filter, $status_new, $execute, $type, $user_id = 0, $ids, $paid = false, $closed_orders = false, $ecodimb = 0, $transfer_budget_year = 0, $new_budget = array(), $b_account_id = 0)
 {
     if ($transfer_budget_year && $execute && $new_budget) {
         //		echo "<H1> Overføre budsjett for valgte prosjekt/bestillinger til år {$transfer_budget_year} </H1>";
         $soworkorder = CreateObject('property.soworkorder');
         foreach ($ids as $_id) {
             if ((int) $new_budget[$_id]['latest_year'] >= (int) $transfer_budget_year) {
                 continue;
             }
             switch ($type) {
                 case 'project':
                     try {
                         $this->transfer_budget($_id, $new_budget[$_id], $transfer_budget_year);
                     } catch (Exception $e) {
                         if ($e) {
                             phpgwapi_cache::message_set($e->getMessage(), 'error');
                         }
                     }
                     break;
                 case 'workorder':
                     try {
                         $soworkorder->transfer_budget($_id, $new_budget[$_id], $transfer_budget_year);
                     } catch (Exception $e) {
                         if ($e) {
                             phpgwapi_cache::message_set($e->getMessage(), 'error');
                         }
                     }
                     break;
                 default:
                     throw new Exception('property_soproject::bulk_update_status() - not a valid type');
             }
         }
         //				die();
     }
     $start_date = $start_date ? phpgwapi_datetime::date_to_timestamp($start_date) : time();
     $start_date -= 3600 * 24;
     $end_date = $end_date ? phpgwapi_datetime::date_to_timestamp($end_date) : time();
     $filter = '';
     if ($user_id) {
         $user_id = (int) $user_id;
         $filter .= "AND fm_{$type}.user_id = {$user_id}";
     }
     if ($ecodimb) {
         $ecodimb = (int) $ecodimb;
         $filter .= "AND fm_{$type}.ecodimb = {$ecodimb}";
     }
     if ($status_filter) {
         if ($status_filter == 'open') {
             $filter .= " AND fm_{$type}_status.closed IS NULL";
         } else {
             $filter .= " AND fm_{$type}.status='{$status_filter}' ";
         }
     }
     switch ($type) {
         case 'project':
             $sql_budget = "SELECT DISTINCT year, month, active, sum(budget) as amount FROM fm_project_budget WHERE ";
             $sql_budget .= 'project_id = %d GROUP BY year, month, active ORDER BY year';
             if ($closed_orders) {
                 $filter .= " AND fm_open_workorder_view.project_id IS NULL";
             }
             $table = 'fm_project';
             $status_table = 'fm_project_status';
             $title_field = 'fm_project.name as title';
             $this->_update_status_project($execute, $status_new, $ids);
             $sql = "SELECT DISTINCT {$table}.id,{$status_table}.closed, {$status_table}.descr as status ,{$title_field},{$table}.start_date,{$table}.project_type_id, count(project_id) as num_open FROM {$table}" . " {$this->join} {$status_table} ON  {$table}.status = {$status_table}.id " . " {$this->left_join} fm_open_workorder_view ON {$table}.id = fm_open_workorder_view.project_id " . " WHERE ({$table}.start_date > {$start_date} AND {$table}.start_date < {$end_date} OR {$table}.start_date IS NULL)  {$filter}" . " GROUP BY {$table}.id, {$status_table}.closed, {$status_table}.descr ,{$table}.name, {$table}.start_date,project_type_id" . " ORDER BY {$table}.id DESC";
             break;
         case 'workorder':
             $sql_budget = "SELECT DISTINCT year, month, active, sum(combined_cost) as amount FROM fm_workorder_budget WHERE ";
             $sql_budget .= 'order_id = %d GROUP BY year, month, active ORDER BY year';
             if ($b_account_id) {
                 $filter .= " AND fm_workorder.account_id = '{$b_account_id}'";
             }
             $table = 'fm_workorder';
             $status_table = 'fm_workorder_status';
             $title_field = 'fm_workorder.title';
             $actual_cost = ',actual_cost';
             $join_method = "{$this->join} {$status_table} ON  {$table}.status = {$status_table}.id";
             $join_method .= " {$this->join} fm_project ON  {$table}.project_id = fm_project.id";
             if ($paid) {
                 $join_method .= " {$this->join} fm_orders_actual_cost_view ON fm_workorder.id = fm_orders_actual_cost_view.order_id";
                 $actual_cost = ',fm_orders_actual_cost_view.actual_cost';
                 $group_method = '';
             } else {
                 $start_period = date('Y') - 1 . '00';
                 $end_period = date('Y') - 1 . 13;
                 $join_method .= " {$this->left_join} fm_ecobilagoverf ON ( fm_workorder.id = fm_ecobilagoverf.pmwrkord_code AND fm_ecobilagoverf.periode > {$start_period} AND fm_ecobilagoverf.periode < {$end_period})";
                 $actual_cost = ',sum(fm_ecobilagoverf.godkjentbelop) AS actual_cost';
                 $group_method = "GROUP BY fm_workorder.id, fm_workorder.project_id, fm_workorder.account_id, fm_workorder_status.closed,fm_workorder_status.descr,fm_project.project_type_id,fm_workorder.title,fm_workorder.start_date,fm_workorder.continuous";
             }
             $this->_update_status_workorder($execute, $status_new, $ids);
             $sql = "SELECT {$table}.id, {$table}.project_id,{$status_table}.closed, {$table}.account_id, {$status_table}.descr as status ,{$title_field},{$table}.start_date {$actual_cost}," . " project_type_id, continuous" . " FROM {$table} {$join_method}" . " WHERE ({$table}.start_date > {$start_date} AND {$table}.start_date < {$end_date} {$filter}) OR {$table}.start_date is NULL" . " {$group_method} ORDER BY {$table}.id DESC";
             break;
         default:
             return array();
     }
     $project_types = array(1 => lang('operation'), 2 => lang('investment'), 3 => lang('buffer'), 4 => lang('maintenance'));
     $this->db->query($sql, __LINE__, __FILE__);
     $values = array();
     $dateformat = $GLOBALS['phpgw_info']['user']['preferences']['common']['dateformat'];
     while ($this->db->next_record()) {
         $values[] = array('id' => $this->db->f('id'), 'project_id' => $this->db->f('project_id'), 'closed' => $this->db->f('closed'), 'title' => $this->db->f('title', true), 'status' => $this->db->f('status', true), 'actual_cost' => (double) $this->db->f('actual_cost'), 'start_date' => $GLOBALS['phpgw']->common->show_date($this->db->f('start_date'), $dateformat), 'num_open' => (int) $this->db->f('num_open'), 'project_type_id' => $this->db->f('project_type_id'), 'continuous' => $this->db->f('continuous') ? X : '', 'project_type' => $project_types[$this->db->f('project_type_id')], 'b_account_id' => $this->db->f('account_id'));
     }
     foreach ($values as &$entry) {
         $sql = sprintf($sql_budget, $entry['id']);
         $this->db->query($sql, __LINE__, __FILE__);
         $budget = array();
         $_budget = array();
         $_year = 0;
         $_active_amount = array();
         while ($this->db->next_record()) {
             $_year = $this->db->f('year');
             $_amount = $this->db->f('amount');
             $_active = $this->db->f('active') ? X : 0;
             if ($_active) {
                 $_active_amount[$_year] += $_amount;
             }
             $_budget[$_year] += $_amount;
         }
         foreach ($_budget as $__year => $__budget) {
             $budget[] = $__year . ' [' . number_format((int) $_active_amount[$__year], 0, ',', '.') . '/' . number_format((int) $__budget, 0, ',', '.') . ']';
         }
         $entry['budget'] = implode(' ;', $budget);
         $entry['latest_year'] = $_year;
         $entry['active_amount'] = array_sum($_active_amount);
     }
     return $values;
 }
 /**
  * Edit a contract
  */
 public function edit()
 {
     $GLOBALS['phpgw_info']['flags']['app_header'] .= '::' . lang('edit');
     $contract_id = (int) phpgw::get_var('id');
     $location_id = (int) phpgw::get_var('location_id');
     $update_price_items = false;
     phpgw::import_class('phpgwapi.jquery');
     phpgwapi_jquery::load_widget('core');
     self::add_javascript('rental', 'rental', 'contract.edit.js');
     $message = null;
     $error = null;
     $add_default_price_items = false;
     if (isset($_POST['save_contract'])) {
         if (isset($contract_id) && $contract_id > 0) {
             $contract = rental_socontract::get_instance()->get_single($contract_id);
             // Gets responsibility area from db (ex: eksternleie, internleie)
             $responsibility_area = rental_socontract::get_instance()->get_responsibility_title($contract->get_location_id());
             // Redirect with error message if responsibility area is eksternleie and contract type not set
             if (!is_numeric(phpgw::get_var('contract_type')) && strcmp($responsibility_area, "contract_type_eksternleie") == 0) {
                 $error = lang('billing_removed_external_contract');
                 $GLOBALS['phpgw']->redirect_link('/index.php', array('menuaction' => 'rental.uicontract.edit', 'id' => $contract->get_id(), 'message' => $message, 'error' => $error));
             }
             if (!$contract->has_permission(PHPGW_ACL_EDIT)) {
                 unset($contract);
                 $this->render('permission_denied.php', array('error' => lang('permission_denied_edit_contract')));
             }
         } else {
             // Gets responsibility area from db (ex: eksternleie, internleie)
             $responsibility_area = rental_socontract::get_instance()->get_responsibility_title($location_id);
             // Redirect with error message if responsibility area is eksternleie and contract type not set
             if (!is_numeric(phpgw::get_var('contract_type')) && strcmp($responsibility_area, "contract_type_eksternleie") == 0) {
                 $error = lang('billing_removed_external_contract');
                 $GLOBALS['phpgw']->redirect_link('/index.php', array('menuaction' => 'rental.uicontract.edit', 'location_id' => $location_id, 'message' => $message, 'error' => $error));
             }
             if (isset($location_id) && ($this->isExecutiveOfficer() || $this->isAdministrator())) {
                 $contract = new rental_contract();
                 $fields = rental_socontract::get_instance()->get_fields_of_responsibility();
                 $contract->set_location_id($location_id);
                 $contract->set_contract_type_title($fields[$location_id]);
                 $add_default_price_items = true;
             }
         }
         $date_start = phpgwapi_datetime::date_to_timestamp(phpgw::get_var('date_start'));
         $date_end = phpgwapi_datetime::date_to_timestamp(phpgw::get_var('date_end'));
         if (isset($contract)) {
             $contract->set_contract_date(new rental_contract_date($date_start, $date_end));
             $contract->set_security_type(phpgw::get_var('security_type'));
             $contract->set_security_amount(phpgw::get_var('security_amount'));
             $contract->set_executive_officer_id(phpgw::get_var('executive_officer'));
             $contract->set_comment(phpgw::get_var('comment'));
             if (isset($location_id) && $location_id > 0) {
                 $contract->set_location_id($location_id);
                 // only present when new contract
             }
             $contract->set_term_id(phpgw::get_var('billing_term'));
             $contract->set_billing_start_date(phpgwapi_datetime::date_to_timestamp(phpgw::get_var('billing_start_date')));
             $contract->set_billing_end_date(phpgwapi_datetime::date_to_timestamp(phpgw::get_var('billing_end_date')));
             $contract->set_service_id(phpgw::get_var('service_id'));
             $contract->set_responsibility_id(phpgw::get_var('responsibility_id'));
             $contract->set_reference(phpgw::get_var('reference'));
             $contract->set_invoice_header(phpgw::get_var('invoice_header'));
             $contract->set_account_in(phpgw::get_var('account_in'));
             /*
             					if($contract->get_contract_type_id() != phpgw::get_var('contract_type'))
             					{
             						// New contract type id set, retrieve correct account out
             						$type_id = phpgw::get_var('contract_type');
             						if(isset($type_id) && $type_is != ''){
             							$account = rental_socontract::get_instance()->get_contract_type_account($type_id);
             							$contract->set_account_out($account);
             						}
             						else
             						{
             							$contract->set_account_out(phpgw::get_var('account_out'));
             						}
             					}
             					else
             					{*/
             $contract->set_account_out(phpgw::get_var('account_out'));
             //}
             $contract->set_project_id(phpgw::get_var('project_id'));
             $contract->set_due_date(phpgwapi_datetime::date_to_timestamp(phpgw::get_var('due_date')));
             $contract->set_contract_type_id(phpgw::get_var('contract_type'));
             $old_rented_area = $contract->get_rented_area();
             $new_rented_area = phpgw::get_var('rented_area');
             $new_rented_area = str_replace(',', '.', $new_rented_area);
             $validated_numeric = false;
             if (!isset($new_rented_area) || $new_rented_area == '') {
                 $new_rented_area = 0;
             }
             if ($old_rented_area != $new_rented_area) {
                 $update_price_items = true;
             }
             $contract->set_rented_area($new_rented_area);
             $contract->set_adjustment_interval(phpgw::get_var('adjustment_interval'));
             $contract->set_adjustment_share(phpgw::get_var('adjustment_share'));
             $contract->set_adjustable(phpgw::get_var('adjustable') == 'on' ? true : false);
             $contract->set_publish_comment(phpgw::get_var('publish_comment') == 'on' ? true : false);
             $validated_numeric = $contract->validate_numeric();
             if ($validated_numeric) {
                 $so_contract = rental_socontract::get_instance();
                 $db_contract = $so_contract->get_db();
                 $db_contract->transaction_begin();
                 if ($so_contract->store($contract)) {
                     if ($update_price_items) {
                         $success = $so_contract->update_price_items($contract->get_id(), $new_rented_area);
                         if ($success) {
                             $db_contract->transaction_commit();
                             $message = lang('messages_saved_form');
                             $contract_id = $contract->get_id();
                         } else {
                             $db_contract->transaction_abort();
                             $error = lang('messages_form_error');
                         }
                     } else {
                         if ($add_default_price_items) {
                             $so_price_item = rental_soprice_item::get_instance();
                             //get default price items for location_id
                             $default_price_items = $so_contract->get_default_price_items($contract->get_location_id());
                             //add price_items to contract
                             foreach ($default_price_items as $price_item_id) {
                                 $so_price_item->add_price_item($contract->get_id(), $price_item_id);
                             }
                             $db_contract->transaction_commit();
                             $message = lang('messages_saved_form');
                             $contract_id = $contract->get_id();
                         } else {
                             $db_contract->transaction_commit();
                             $message = lang('messages_saved_form');
                             $contract_id = $contract->get_id();
                         }
                     }
                 } else {
                     $db_contract->transaction_abort();
                     $error = lang('messages_form_error');
                 }
             } else {
                 $error = $contract->get_validation_errors();
                 return $this->viewedit(true, $contract_id, $contract, $location_id, $notification, $message, $error);
             }
         }
         $GLOBALS['phpgw']->redirect_link('/index.php', array('menuaction' => 'rental.uicontract.edit', 'id' => $contract->get_id(), 'message' => $message, 'error' => $error));
     } else {
         if (isset($_POST['add_notification'])) {
             $contract = rental_socontract::get_instance()->get_single($contract_id);
             if ($contract->has_permission(PHPGW_ACL_EDIT)) {
                 $account_id = phpgw::get_var('notification_target');
                 $location_id = phpgw::get_var('notification_location');
                 $date = phpgw::get_var('date_notification');
                 if ($date) {
                     $date = phpgwapi_datetime::date_to_timestamp($date);
                 }
                 $notification = new rental_notification(-1, $account_id, $location_id, $contract_id, $date, phpgw::get_var('notification_message'), phpgw::get_var('notification_recurrence'));
                 if (rental_sonotification::get_instance()->store($notification)) {
                     $message = lang('messages_saved_form');
                     $notification = null;
                     // We don't want to display the date/message when it was sucessfully stored.
                 } else {
                     $error = lang('messages_form_error');
                 }
             } else {
                 $error = lang('permission_denied_edit_contract');
             }
         }
     }
     return $this->viewedit(true, $contract_id, null, $location_id, $notification, $message, $error);
 }