Exemple #1
0
/**
 * Returns a DateTimeValue from a date representation from pick_date_widget2
 *
 * @param string $value
 * @param DateTimeValue $default
 * @return DateTimeValue
 */
function getDateValue($value = '', $default = EMPTY_DATETIME)
{
    if ($value instanceof DateTimeValue) {
        return $value;
    }
    if ($value != '' && $value != date_format_tip(user_config_option('date_format'))) {
        $date_format = user_config_option('date_format');
        return DateTimeValueLib::dateFromFormatAndString($date_format, $value);
    }
    return $default;
}
 /**
  * Execute a report and return results
  *
  * @param $id
  * @param $params
  *
  * @return array
  */
 static function executeReport($id, $params, $order_by_col = '', $order_by_asc = true, $offset = 0, $limit = 50, $to_print = false)
 {
     if (is_null(active_context())) {
         CompanyWebsite::instance()->setContext(build_context_array(array_var($_REQUEST, 'context')));
     }
     $results = array();
     $report = self::getReport($id);
     $show_archived = false;
     if ($report instanceof Report) {
         $conditionsFields = ReportConditions::getAllReportConditionsForFields($id);
         $conditionsCp = ReportConditions::getAllReportConditionsForCustomProperties($id);
         $ot = ObjectTypes::findById($report->getReportObjectTypeId());
         $table = $ot->getTableName();
         if ($ot->getType() == 'dimension_object' || $ot->getType() == 'dimension_group') {
             $hook_parameters = array('report' => $report, 'params' => $params, 'order_by_col' => $order_by_col, 'order_by_asc' => $order_by_asc, 'offset' => $offset, 'limit' => $limit, 'to_print' => $to_print);
             $report_result = null;
             Hook::fire('replace_execute_report_function', $hook_parameters, $report_result);
             if ($report_result) {
                 return $report_result;
             }
         }
         eval('$managerInstance = ' . $ot->getHandlerClass() . "::instance();");
         eval('$item_class = ' . $ot->getHandlerClass() . '::instance()->getItemClass(); $object = new $item_class();');
         $order_by = '';
         if (is_object($params)) {
             $params = get_object_vars($params);
         }
         $report_columns = ReportColumns::getAllReportColumns($id);
         $allConditions = "";
         $contact_extra_columns = self::get_extra_contact_columns();
         if (count($conditionsFields) > 0) {
             foreach ($conditionsFields as $condField) {
                 if ($condField->getFieldName() == "archived_on") {
                     $show_archived = true;
                 }
                 $skip_condition = false;
                 $model = $ot->getHandlerClass();
                 $model_instance = new $model();
                 $col_type = $model_instance->getColumnType($condField->getFieldName());
                 $allConditions .= ' AND ';
                 $dateFormat = 'm/d/Y';
                 if (isset($params[$condField->getId()])) {
                     $value = $params[$condField->getId()];
                     if ($col_type == DATA_TYPE_DATE || $col_type == DATA_TYPE_DATETIME) {
                         $dateFormat = user_config_option('date_format');
                     }
                 } else {
                     $value = $condField->getValue();
                 }
                 if ($ot->getHandlerClass() == 'Contacts' && in_array($condField->getFieldName(), $contact_extra_columns)) {
                     $allConditions .= self::get_extra_contact_column_condition($condField->getFieldName(), $condField->getCondition(), $value);
                 } else {
                     if ($value == '' && $condField->getIsParametrizable()) {
                         $skip_condition = true;
                     }
                     if (!$skip_condition) {
                         $field_name = $condField->getFieldName();
                         if (in_array($condField->getFieldName(), Objects::getColumns())) {
                             $field_name = 'o`.`' . $condField->getFieldName();
                         }
                         if ($condField->getCondition() == 'like' || $condField->getCondition() == 'not like') {
                             $value = '%' . $value . '%';
                         }
                         if ($col_type == DATA_TYPE_DATE || $col_type == DATA_TYPE_DATETIME) {
                             if ($value == date_format_tip($dateFormat)) {
                                 $value = EMPTY_DATE;
                             } else {
                                 $dtValue = DateTimeValueLib::dateFromFormatAndString($dateFormat, $value);
                                 $value = $dtValue->format('Y-m-d');
                             }
                         }
                         if ($condField->getCondition() != '%') {
                             if ($col_type == DATA_TYPE_INTEGER || $col_type == DATA_TYPE_FLOAT) {
                                 $allConditions .= '`' . $field_name . '` ' . $condField->getCondition() . ' ' . DB::escape($value);
                             } else {
                                 if ($condField->getCondition() == '=' || $condField->getCondition() == '<=' || $condField->getCondition() == '>=') {
                                     if ($col_type == DATA_TYPE_DATETIME || $col_type == DATA_TYPE_DATE) {
                                         $equal = 'datediff(' . DB::escape($value) . ', `' . $field_name . '`)=0';
                                     } else {
                                         $equal = '`' . $field_name . '` ' . $condField->getCondition() . ' ' . DB::escape($value);
                                     }
                                     switch ($condField->getCondition()) {
                                         case '=':
                                             $allConditions .= $equal;
                                             break;
                                         case '<=':
                                         case '>=':
                                             $allConditions .= '(`' . $field_name . '` ' . $condField->getCondition() . ' ' . DB::escape($value) . ' OR ' . $equal . ') ';
                                             break;
                                     }
                                 } else {
                                     $allConditions .= '`' . $field_name . '` ' . $condField->getCondition() . ' ' . DB::escape($value);
                                 }
                             }
                         } else {
                             $allConditions .= '`' . $field_name . '` like ' . DB::escape("%{$value}");
                         }
                     } else {
                         $allConditions .= ' true';
                     }
                 }
             }
         }
         if (count($conditionsCp) > 0) {
             $dateFormat = user_config_option('date_format');
             $date_format_tip = date_format_tip($dateFormat);
             foreach ($conditionsCp as $condCp) {
                 $cp = CustomProperties::getCustomProperty($condCp->getCustomPropertyId());
                 $skip_condition = false;
                 if (isset($params[$condCp->getId() . "_" . $cp->getName()])) {
                     $value = $params[$condCp->getId() . "_" . $cp->getName()];
                 } else {
                     $value = $condCp->getValue();
                 }
                 if ($value == '' && $condCp->getIsParametrizable()) {
                     $skip_condition = true;
                 }
                 if (!$skip_condition) {
                     $current_condition = ' AND ';
                     $current_condition .= 'o.id IN ( SELECT object_id as id FROM ' . TABLE_PREFIX . 'custom_property_values cpv WHERE ';
                     $current_condition .= ' cpv.custom_property_id = ' . $condCp->getCustomPropertyId();
                     $fieldType = $object->getColumnType($condCp->getFieldName());
                     if ($condCp->getCondition() == 'like' || $condCp->getCondition() == 'not like') {
                         $value = '%' . $value . '%';
                     }
                     if ($cp->getType() == 'date') {
                         if ($value == $date_format_tip) {
                             continue;
                         }
                         $dtValue = DateTimeValueLib::dateFromFormatAndString($dateFormat, $value);
                         $value = $dtValue->format('Y-m-d H:i:s');
                     }
                     if ($condCp->getCondition() != '%') {
                         if ($cp->getType() == 'numeric') {
                             $current_condition .= ' AND cpv.value ' . $condCp->getCondition() . ' ' . DB::escape($value);
                         } else {
                             if ($cp->getType() == 'boolean') {
                                 $current_condition .= ' AND cpv.value ' . $condCp->getCondition() . ' ' . ($value ? '1' : '0');
                                 if (!$value) {
                                     $current_condition .= ') OR o.id NOT IN (SELECT object_id as id FROM ' . TABLE_PREFIX . 'custom_property_values cpv2 WHERE cpv2.object_id=o.id AND cpv2.value=1 AND cpv2.custom_property_id = ' . $condCp->getCustomPropertyId();
                                 }
                             } else {
                                 $current_condition .= ' AND cpv.value ' . $condCp->getCondition() . ' ' . DB::escape($value);
                             }
                         }
                     } else {
                         $current_condition .= ' AND cpv.value like ' . DB::escape("%{$value}");
                     }
                     $current_condition .= ')';
                     $allConditions .= $current_condition;
                 }
             }
         }
         $select_columns = array('*');
         $join_params = null;
         if ($order_by_col == '') {
             $order_by_col = $report->getOrderBy();
         }
         if ($ot->getHandlerClass() == 'Contacts' && in_array($order_by_col, $contact_extra_columns)) {
             $join_params = self::get_extra_contact_column_order_by($order_by_col, $order_by_col, $select_columns);
         }
         $original_order_by_col = $order_by_col;
         if (in_array($order_by_col, self::$external_columns)) {
             $order_by_col = 'name_order';
             $join_params = array('table' => Objects::instance()->getTableName(), 'jt_field' => 'id', 'e_field' => $original_order_by_col, 'join_type' => 'left');
             $select_columns = array();
             $tmp_cols = $managerInstance->getColumns();
             foreach ($tmp_cols as $col) {
                 $select_columns[] = "e.{$col}";
             }
             $tmp_cols = Objects::instance()->getColumns();
             foreach ($tmp_cols as $col) {
                 $select_columns[] = "o.{$col}";
             }
             $select_columns[] = 'jt.name as name_order';
         }
         if ($order_by_asc == null) {
             $order_by_asc = $report->getIsOrderByAsc();
         }
         if ($ot->getName() == 'task' && !SystemPermissions::userHasSystemPermission(logged_user(), 'can_see_assigned_to_other_tasks')) {
             $allConditions .= " AND assigned_to_contact_id = " . logged_user()->getId();
         }
         if ($managerInstance) {
             if ($order_by_col == "order") {
                 $order_by_col = "`{$order_by_col}`";
             }
             $listing_parameters = array("select_columns" => $select_columns, "order" => "{$order_by_col}", "order_dir" => $order_by_asc ? "ASC" : "DESC", "extra_conditions" => $allConditions, "count_results" => true, "join_params" => $join_params);
             if ($limit > 0) {
                 $listing_parameters["start"] = $offset;
                 $listing_parameters["limit"] = $limit;
             }
             if ($show_archived) {
                 $listing_parameters["archived"] = true;
             }
             $result = $managerInstance->listing($listing_parameters);
         } else {
             // TODO Performance Killer
             $result = ContentDataObjects::getContentObjects(active_context(), $ot, $order_by_col, $order_by_asc ? "ASC" : "DESC", $allConditions);
         }
         $objects = $result->objects;
         $totalResults = $result->total;
         $results['pagination'] = Reports::getReportPagination($id, $params, $original_order_by_col, $order_by_asc, $offset, $limit, $totalResults);
         $dimensions_cache = array();
         foreach ($report_columns as $column) {
             if ($column->getCustomPropertyId() == 0) {
                 $field = $column->getFieldName();
                 if (str_starts_with($field, 'dim_')) {
                     $dim_id = str_replace("dim_", "", $field);
                     $dimension = Dimensions::getDimensionById($dim_id);
                     $dimensions_cache[$dim_id] = $dimension;
                     $column_name = $dimension->getName();
                     $results['columns'][$field] = $column_name;
                     $results['db_columns'][$column_name] = $field;
                 } else {
                     if ($managerInstance->columnExists($field) || Objects::instance()->columnExists($field)) {
                         $column_name = Localization::instance()->lang('field ' . $ot->getHandlerClass() . ' ' . $field);
                         if (is_null($column_name)) {
                             $column_name = lang('field Objects ' . $field);
                         }
                         $results['columns'][$field] = $column_name;
                         $results['db_columns'][$column_name] = $field;
                     } else {
                         if ($ot->getHandlerClass() == 'Contacts') {
                             if (in_array($field, $contact_extra_columns)) {
                                 $results['columns'][$field] = lang($field);
                                 $results['db_columns'][lang($field)] = $field;
                             }
                         } else {
                             if ($ot->getHandlerClass() == 'Timeslots') {
                                 if (in_array($field, array('time', 'billing'))) {
                                     $results['columns'][$field] = lang('field Objects ' . $field);
                                     $results['db_columns'][lang('field Objects ' . $field)] = $field;
                                 }
                             } else {
                                 if ($ot->getHandlerClass() == 'MailContents') {
                                     if (in_array($field, array('to', 'cc', 'bcc', 'body_plain', 'body_html'))) {
                                         $results['columns'][$field] = lang('field Objects ' . $field);
                                         $results['db_columns'][lang('field Objects ' . $field)] = $field;
                                     }
                                 }
                             }
                         }
                     }
                 }
             } else {
                 $results['columns'][$column->getCustomPropertyId()] = $column->getCustomPropertyId();
             }
         }
         $report_rows = array();
         foreach ($objects as &$object) {
             /* @var $object Object */
             $obj_name = $object->getObjectName();
             $icon_class = $object->getIconClass();
             $row_values = array('object_type_id' => $object->getObjectTypeId());
             if (!$to_print) {
                 $row_values['link'] = '<a class="link-ico ' . $icon_class . '" title="' . clean($obj_name) . '" target="new" href="' . $object->getViewUrl() . '">&nbsp;</a>';
             }
             foreach ($report_columns as $column) {
                 if ($column->getCustomPropertyId() == 0) {
                     $field = $column->getFieldName();
                     if (str_starts_with($field, 'dim_')) {
                         $dim_id = str_replace("dim_", "", $field);
                         if (!array_var($dimensions_cache, $dim_id) instanceof Dimension) {
                             $dimension = Dimensions::getDimensionById($dim_id);
                             $dimensions_cache[$dim_id] = $dimension;
                         } else {
                             $dimension = array_var($dimensions_cache, $dim_id);
                         }
                         $om_object_id = $object instanceof Timeslot ? $object->getRelObjectId() : $object->getId();
                         $members = ObjectMembers::getMembersByObjectAndDimension($om_object_id, $dim_id, " AND om.is_optimization=0");
                         $value = "";
                         foreach ($members as $member) {
                             /* @var $member Member */
                             $val = $member->getPath();
                             $val .= ($val == "" ? "" : "/") . $member->getName();
                             if ($value != "") {
                                 $val = " - {$val}";
                             }
                             $value .= $val;
                         }
                         $row_values[$field] = $value;
                     } else {
                         if ($object instanceof Timeslot) {
                             if ($field == 'id') {
                                 $value = $object->getObjectId();
                             } else {
                                 $value = $object->getColumnValue($field);
                                 // if it is a task column
                                 if (in_array($field, ProjectTasks::instance()->getColumns())) {
                                     $task = ProjectTasks::findById($object->getRelObjectId());
                                     // if task exists
                                     if ($task instanceof ProjectTask) {
                                         $value = $task->getColumnValue($field);
                                         // if it is an external task column
                                         if (in_array($field, ProjectTasks::instance()->getExternalColumns())) {
                                             $value = self::instance()->getExternalColumnValue($field, $value, ProjectTasks::instance());
                                         } else {
                                             // if is a date then use format
                                             if (ProjectTasks::instance()->getColumnType($field) == DATA_TYPE_DATETIME && $value instanceof DateTimeValue) {
                                                 $value = format_value_to_print($field, $value->toMySQL(), DATA_TYPE_DATETIME, $report->getReportObjectTypeId());
                                             }
                                         }
                                     }
                                     $results['columns'][$field] = lang('field ProjectTasks ' . $field);
                                     $results['db_columns'][lang('field ProjectTasks ' . $field)] = $field;
                                 }
                             }
                         } else {
                             $value = $object->getColumnValue($field);
                         }
                         if ($value instanceof DateTimeValue) {
                             $dateFormat = user_config_option('date_format');
                             Hook::fire("custom_property_date_format", null, $dateFormat);
                             $tz = logged_user()->getTimezone();
                             if ($object instanceof ProjectTask) {
                                 if ($field == 'due_date' && !$object->getUseDueTime() || $field == 'start_date' && !$object->getUseStartTime()) {
                                     $dateFormat = user_config_option('date_format');
                                     $tz = 0;
                                 }
                             }
                             $value = format_date($value, $dateFormat, $tz * 3600);
                         }
                         if (in_array($field, $managerInstance->getExternalColumns())) {
                             if ($object instanceof Timeslot && $field == 'time') {
                                 $lastStop = $object->getEndTime() != null ? $object->getEndTime() : ($object->isPaused() ? $object->getPausedOn() : DateTimeValueLib::now());
                                 $seconds = $lastStop->getTimestamp() - $object->getStartTime()->getTimestamp();
                                 $hours = number_format($seconds / 3600, 2, ',', '.');
                                 $value = $hours;
                                 //$value = DateTimeValue::FormatTimeDiff($object->getStartTime(), $lastStop, "hm", 60, $object->getSubtract());
                             } else {
                                 if ($object instanceof Timeslot && $field == 'billing') {
                                     $value = config_option('currency_code', '$') . ' ' . $object->getFixedBilling();
                                 } else {
                                     $value = self::instance()->getExternalColumnValue($field, $value, $managerInstance);
                                 }
                             }
                         } else {
                             if ($field != 'link') {
                                 //$value = html_to_text(html_entity_decode($value));
                                 if ($object->getColumnType($field) == DATA_TYPE_STRING) {
                                     // change html block end tags and brs to \n, then remove all other html tags, then replace \n with <br>, to remove all styles and keep the enters
                                     $value = str_replace(array("</div>", "</p>", "<br>", "<br />", "<br/>"), "\n", $value);
                                     $value = nl2br(strip_tags($value));
                                 }
                             }
                         }
                         if (self::isReportColumnEmail($value)) {
                             if (logged_user()->hasMailAccounts()) {
                                 $value = '<a class="internalLink" href="' . get_url('mail', 'add_mail', array('to' => clean($value))) . '">' . clean($value) . '</a></div>';
                             } else {
                                 $value = '<a class="internalLink" target="_self" href="mailto:' . clean($value) . '">' . clean($value) . '</a></div>';
                             }
                         }
                         $row_values[$field] = $value;
                         if ($ot->getHandlerClass() == 'Contacts') {
                             if ($managerInstance instanceof Contacts) {
                                 $contact = Contacts::findOne(array("conditions" => "object_id = " . $object->getId()));
                                 if ($field == "email_address") {
                                     $row_values[$field] = $contact->getEmailAddress();
                                 }
                                 if ($field == "is_user") {
                                     $row_values[$field] = $contact->getUserType() > 0 && !$contact->getIsCompany();
                                 }
                                 if ($field == "im_values") {
                                     $str = "";
                                     foreach ($contact->getAllImValues() as $type => $value) {
                                         $str .= ($str == "" ? "" : " | ") . "{$type}: {$value}";
                                     }
                                     $row_values[$field] = $str;
                                 }
                                 if (in_array($field, array("mobile_phone", "work_phone", "home_phone"))) {
                                     if ($field == "mobile_phone") {
                                         $row_values[$field] = $contact->getPhoneNumber('mobile', null, false);
                                     } else {
                                         if ($field == "work_phone") {
                                             $row_values[$field] = $contact->getPhoneNumber('work', null, false);
                                         } else {
                                             if ($field == "home_phone") {
                                                 $row_values[$field] = $contact->getPhoneNumber('home', null, false);
                                             }
                                         }
                                     }
                                 }
                                 if (in_array($field, array("personal_webpage", "work_webpage", "other_webpage"))) {
                                     if ($field == "personal_webpage") {
                                         $row_values[$field] = $contact->getWebpageUrl('personal');
                                     } else {
                                         if ($field == "work_webpage") {
                                             $row_values[$field] = $contact->getWebpageUrl('work');
                                         } else {
                                             if ($field == "other_webpage") {
                                                 $row_values[$field] = $contact->getWebpageUrl('other');
                                             }
                                         }
                                     }
                                 }
                                 if (in_array($field, array("home_address", "work_address", "other_address"))) {
                                     if ($field == "home_address") {
                                         $row_values[$field] = $contact->getStringAddress('home');
                                     } else {
                                         if ($field == "work_address") {
                                             $row_values[$field] = $contact->getStringAddress('work');
                                         } else {
                                             if ($field == "other_address") {
                                                 $row_values[$field] = $contact->getStringAddress('other');
                                             }
                                         }
                                     }
                                 }
                             }
                         } else {
                             if ($ot->getHandlerClass() == 'MailContents') {
                                 if (in_array($field, array('to', 'cc', 'bcc', 'body_plain', 'body_html'))) {
                                     $mail_data = MailDatas::findById($object->getId());
                                     $row_values[$field] = $mail_data->getColumnValue($field);
                                     if ($field == "body_html") {
                                         if (class_exists("DOMDocument")) {
                                             $d = new DOMDocument();
                                             $mock = new DOMDocument();
                                             $d->loadHTML(remove_css_and_scripts($row_values[$field]));
                                             $body = $d->getElementsByTagName('body')->item(0);
                                             foreach ($body->childNodes as $child) {
                                                 $mock->appendChild($mock->importNode($child, true));
                                             }
                                             // if css is inside an html comment => remove it
                                             $row_values[$field] = preg_replace('/<!--(.*)-->/Uis', '', remove_css($row_values[$field]));
                                         } else {
                                             $row_values[$field] = preg_replace('/<!--(.*)-->/Uis', '', remove_css_and_scripts($row_values[$field]));
                                         }
                                     }
                                 }
                             }
                         }
                         if (!$to_print && $field == "name") {
                             $row_values[$field] = '<a target="new-' . $object->getId() . '" href="' . $object->getViewUrl() . '">' . $value . '</a>';
                         }
                     }
                 } else {
                     $colCp = $column->getCustomPropertyId();
                     $cp = CustomProperties::getCustomProperty($colCp);
                     if ($cp instanceof CustomProperty) {
                         /* @var $cp CustomProperty */
                         $row_values[$cp->getName()] = get_custom_property_value_for_listing($cp, $object);
                         $results['columns'][$colCp] = $cp->getName();
                         $results['db_columns'][$cp->getName()] = $colCp;
                     }
                 }
             }
             Hook::fire("report_row", $object, $row_values);
             $report_rows[] = $row_values;
         }
         if (!$to_print) {
             if (is_array($results['columns'])) {
                 array_unshift($results['columns'], '');
             } else {
                 $results['columns'] = array('');
             }
             Hook::fire("report_header", $ot, $results['columns']);
         }
         $results['rows'] = $report_rows;
     }
     return $results;
 }
Exemple #3
0
?>
,
	'email_polling': <?php 
echo json_encode(user_config_option('email_polling'));
?>
 ,
	'email_check_acc_errors': <?php 
echo json_encode(user_config_option('mail_account_err_check_interval'));
?>
 ,
	'date_format': <?php 
echo json_encode(user_config_option('date_format'));
?>
,
	'date_format_tip': <?php 
echo json_encode(date_format_tip(user_config_option('date_format')));
?>
,
	'start_monday': <?php 
echo user_config_option('start_monday') ? '1' : '0';
?>
,
	'draft_autosave_timeout': <?php 
echo json_encode(user_config_option('draft_autosave_timeout'));
?>
,
	'drag_drop_prompt': <?php 
echo json_encode(user_config_option('drag_drop_prompt'));
?>
,
	'mail_drag_drop_prompt': <?php 
Exemple #4
0
function pick_date_widget2($name, $value = null, $genid = null, $tabindex = null, $display_date_info = true, $id = null)
{
    require_javascript('og/DateField.js');
    $date_format = user_config_option('date_format');
    if ($genid == null) {
        $genid = gen_id();
    }
    $dateValue = '';
    if ($value instanceof DateTimeValue) {
        $dateValue = $value->format($date_format);
    }
    if (!$id) {
        $id = $genid . $name . "Cmp";
    }
    $daterow = '';
    // 	if ($display_date_info)
    // 		$daterow = "<td style='padding-top:4px;font-size:80%'><span class='desc'>&nbsp;(" . date_format_tip($date_format) . ")</span></td>";
    $html = "<table><tr><td><span id='" . $genid . $name . "'></span></td>{$daterow}</tr></table>\n\t<script>\n\t\tvar dtp" . gen_id() . " = new og.DateField({\n\t\t\trenderTo:'" . $genid . $name . "',\n\t\t\tname: '" . $name . "',\n\t\t\temptyText: '" . date_format_tip($date_format) . "',\n\t\t\tid: '" . $id . "'," . (isset($tabindex) ? "tabIndex: '{$tabindex}'," : "") . "value: '" . $dateValue . "'});\n\t</script>\n\t";
    return $html;
}
 /**
  * Edit task
  *
  * @access public
  * @param void
  * @return null
  */
 function edit_task()
 {
     $isTemplateTask = false;
     if (array_var($_REQUEST, 'template_task') == true) {
         $isTemplateTask = true;
     }
     if (logged_user()->isGuest()) {
         flash_error(lang('no access permissions'));
         ajx_current("empty");
         return;
     }
     $this->setTemplate('add_task');
     if (array_var($_REQUEST, "template_task")) {
         $task = TemplateTasks::findById(array_var($_REQUEST, "template_task_id", get_id()));
         $this->setTemplate(get_template_path('add_template_task', 'template_task'));
         if (array_var($_REQUEST, 'template_id')) {
             $template_id = array_var($_REQUEST, 'template_id');
         } else {
             $template_id = $task->getTemplateId();
         }
         tpl_assign('additional_tt_params', array_var($_REQUEST, 'additional_tt_params'));
         tpl_assign('template_id', $template_id);
         if (!$task instanceof TemplateTask) {
             flash_error(lang('task list dnx'));
             ajx_current("empty");
             return;
         }
         // if
     } else {
         $task = ProjectTasks::findById(get_id());
         if (!$task instanceof ProjectTask) {
             flash_error(lang('task list dnx'));
             ajx_current("empty");
             return;
         }
         // if
         if (!$task->canEdit(logged_user())) {
             flash_error(lang('no access permissions'));
             ajx_current("empty");
             return;
         }
         // if
     }
     if (array_var($_GET, 'replace')) {
         ajx_replace(true);
     }
     $task_data = array_var($_POST, 'task');
     $time_estimate = array_var($_POST, 'hours', 0) * 60 + array_var($_POST, 'minutes', 0);
     if ($time_estimate > 0) {
         $estimatedTime = $time_estimate;
     } else {
         $estimatedTime = $task->getTimeEstimate();
     }
     if (!is_array($task_data)) {
         // set layout for modal form
         if (array_var($_REQUEST, 'modal')) {
             $this->setLayout("json");
             tpl_assign('modal', true);
         }
         $this->getRepeatOptions($task, $occ, $rsel1, $rsel2, $rsel3, $rnum, $rend, $rjump);
         $dd = $task->getDueDate() instanceof DateTimeValue ? $task->getDueDate() : null;
         if ($dd instanceof DateTimeValue && $task->getUseDueTime()) {
             $dd->advance(logged_user()->getTimezone() * 3600);
         }
         $sd = $task->getStartDate() instanceof DateTimeValue ? $task->getStartDate() : null;
         if ($sd instanceof DateTimeValue && $task->getUseStartTime()) {
             $sd->advance(logged_user()->getTimezone() * 3600);
         }
         $post_dd = null;
         if (array_var($_POST, 'task_due_date')) {
             $post_dd = getDateValue(array_var($_POST, 'task_due_date'));
             if ($post_dd instanceof DateTimeValue) {
                 $duetime = getTimeValue(array_var($_POST, 'task_due_time'));
                 if (is_array($duetime)) {
                     $post_dd->setHour(array_var($duetime, 'hours'));
                     $post_dd->setMinute(array_var($duetime, 'mins'));
                     $post_dd->advance(logged_user()->getTimezone() * 3600);
                 }
             }
         }
         $post_st = null;
         if (array_var($_POST, 'task_start_date')) {
             $post_st = getDateValue(array_var($_POST, 'task_start_date'));
             if ($post_st instanceof DateTimeValue) {
                 $starttime = getTimeValue(array_var($_POST, 'task_start_time'));
                 if (is_array($starttime)) {
                     $post_st->setHour(array_var($starttime, 'hours'));
                     $post_st->setMinute(array_var($starttime, 'mins'));
                     $post_st->advance(logged_user()->getTimezone() * 3600);
                 }
             }
         }
         if (config_option("wysiwyg_tasks")) {
             $text_post = preg_replace("/[\n|\r|\n\r]/", '', array_var($_POST, 'text', $task->getText()));
         } else {
             $text_post = array_var($_POST, 'text', $task->getText());
         }
         $task_data = array('name' => array_var($_POST, 'name', $task->getObjectName()), 'text' => $text_post, 'milestone_id' => array_var($_POST, 'milestone_id', $task->getMilestoneId()), 'due_date' => getDateValue($post_dd, $dd), 'start_date' => getDateValue($post_st, $sd), 'parent_id' => $task->getParentId(), 'assigned_to_contact_id' => array_var($_POST, 'assigned_to_contact_id', $task->getAssignedToContactId()), 'selected_members_ids' => json_decode(array_var($_POST, 'members', null)), 'priority' => array_var($_POST, 'priority', $task->getPriority()), 'time_estimate' => $estimatedTime, 'percent_completed' => $task->getPercentCompleted(), 'forever' => $task->getRepeatForever(), 'rend' => $rend, 'rnum' => $rnum, 'rjump' => $rjump, 'rsel1' => $rsel1, 'rsel2' => $rsel2, 'rsel3' => $rsel3, 'occ' => $occ, 'repeat_by' => $task->getRepeatBy(), 'object_subtype' => array_var($_POST, "object_subtype", $task->getObjectSubtype() != 0 ? $task->getObjectSubtype() : config_option('default task co type')), 'type_content' => $task->getTypeContent(), 'multi_assignment' => $task->getColumnValue('multi_assignment', 0), 'send_notification_subscribers' => user_config_option("can notify subscribers"));
         // array
         //control dates of parent and subtasks
         $task_data['type_control'] = "";
         $parent_data = $task->getParent();
         if ($parent_data) {
             $task_data['type_control'] = "child";
             $task_data['control_title'] = $parent_data->getObjectName();
             $task_data['control_due_date'] = $parent_data->getDueDate() instanceof DateTimeValue ? $parent_data->getDueDate()->getTimestamp() + logged_user()->getTimezone() * 3600 : null;
             $task_data['control_start_date'] = $parent_data->getStartDate() instanceof DateTimeValue ? $parent_data->getStartDate()->getTimestamp() + logged_user()->getTimezone() * 3600 : null;
         }
         $subtask_data = $task->getAllSubTasks();
         if ($subtask_data) {
             $task_data['type_control'] = "father";
             $task_data['control_title'] = $task->getObjectName();
             $task_data['control_due_date'] = getDateValue($post_dd, $dd) instanceof DateTimeValue ? getDateValue($post_dd, $dd)->getTimestamp() : null;
             $task_data['control_start_date'] = getDateValue($post_st, $sd) instanceof DateTimeValue ? getDateValue($post_st, $sd)->getTimestamp() : null;
         }
     }
     // if
     //I find all those related to the task to find out if the original
     $task_related = ProjectTasks::findByRelated($task->getObjectId());
     if (!$task_related) {
         //is not the original as the original look plus other related
         if ($task->getOriginalTaskId() != "0") {
             $task_related = ProjectTasks::findByTaskAndRelated($task->getObjectId(), $task->getOriginalTaskId());
         }
     }
     if ($task_related) {
         $pending_id = 0;
         foreach ($task_related as $t_rel) {
             if ($task->getStartDate() <= $t_rel->getStartDate() && $task->getDueDate() <= $t_rel->getDueDate() && !$t_rel->isCompleted()) {
                 $pending_id = $t_rel->getId();
                 break;
             }
         }
         tpl_assign('pending_task_id', $pending_id);
         tpl_assign('task_related', true);
     } else {
         tpl_assign('pending_task_id', 0);
         tpl_assign('task_related', false);
     }
     tpl_assign('task', $task);
     tpl_assign('task_data', $task_data);
     if (is_array(array_var($_POST, 'task'))) {
         foreach ($task_data as $k => &$v) {
             $v = remove_scripts($v);
         }
         $send_edit = false;
         if ($task->getAssignedToContactId() == array_var($task_data, 'assigned_to_contact_id')) {
             $send_edit = true;
         }
         $old_owner = $task->getAssignedTo();
         if (array_var($task_data, 'parent_id') == $task->getId()) {
             flash_error(lang("task own parent error"));
             ajx_current("empty");
             return;
         }
         try {
             try {
                 $task_data['due_date'] = getDateValue(array_var($_POST, 'task_due_date'));
                 $task_data['start_date'] = getDateValue(array_var($_POST, 'task_start_date'));
             } catch (Exception $e) {
                 throw new Exception(lang('date format error', date_format_tip(user_config_option('date_format'))));
             }
             if ($task_data['due_date'] instanceof DateTimeValue) {
                 $duetime = getTimeValue(array_var($_POST, 'task_due_time'));
                 if (is_array($duetime)) {
                     $task_data['due_date']->setHour(array_var($duetime, 'hours'));
                     $task_data['due_date']->setMinute(array_var($duetime, 'mins'));
                     $task_data['due_date']->advance(logged_user()->getTimezone() * -3600);
                 }
                 $task_data['use_due_time'] = is_array($duetime);
             }
             if ($task_data['start_date'] instanceof DateTimeValue) {
                 $starttime = getTimeValue(array_var($_POST, 'task_start_time'));
                 if (is_array($starttime)) {
                     $task_data['start_date']->setHour(array_var($starttime, 'hours'));
                     $task_data['start_date']->setMinute(array_var($starttime, 'mins'));
                     $task_data['start_date']->advance(logged_user()->getTimezone() * -3600);
                 }
                 $task_data['use_start_time'] = is_array($starttime);
             }
             //control date subtask whit parent
             if (array_var($_POST, 'control_dates') == "child") {
                 $parent = $task->getParent();
                 if ($parent->getStartDate() instanceof DateTimeValue && $task_data['start_date'] instanceof DateTimeValue) {
                     if ($task_data['start_date']->getTimestamp() < $parent->getStartDate()->getTimestamp()) {
                         $parent->setStartDate($task_data['start_date']);
                         $parent->setUseStartTime($task_data['use_start_time']);
                     }
                 } else {
                     $parent->setStartDate($task_data['start_date']);
                     $parent->setUseStartTime(array_var($task_data, 'use_start_time', 0));
                 }
                 if ($parent->getDueDate() instanceof DateTimeValue && $task_data['due_date'] instanceof DateTimeValue) {
                     if ($task_data['due_date']->getTimestamp() > $parent->getDueDate()->getTimestamp()) {
                         $parent->setDueDate($task_data['due_date']);
                         $parent->setUseDueTime($task_data['use_due_time']);
                     }
                 } else {
                     $parent->setDueDate($task_data['due_date']);
                     $parent->setUseDueTime(array_var($task_data, 'use_due_time', 0));
                 }
                 // calculate and set estimated time
                 $totalMinutes = array_var($task_data, 'time_estimate_hours') * 60 + array_var($task_data, 'time_estimate_minutes');
                 $parent->setTimeEstimate($totalMinutes);
                 $parent->save();
             }
             $err_msg = $this->setRepeatOptions($task_data);
             if ($err_msg) {
                 throw new Exception($err_msg);
             }
             if (!isset($task_data['parent_id'])) {
                 $task_data['parent_id'] = 0;
             }
             $member_ids = json_decode(array_var($_POST, 'members'));
             // keep old dates to check for subtasks
             $old_start_date = $task->getStartDate();
             $old_due_date = $task->getDueDate();
             if (config_option("wysiwyg_tasks")) {
                 $task_data['type_content'] = "html";
                 $task_data['text'] = str_replace(array("\r", "\n", "\r\n"), array('', '', ''), array_var($task_data, 'text'));
             } else {
                 $task_data['type_content'] = "text";
             }
             $task->setFromAttributes($task_data);
             $totalMinutes = array_var($task_data, 'time_estimate_hours') * 60 + array_var($task_data, 'time_estimate_minutes');
             $task->setTimeEstimate($totalMinutes);
             if ($task->getParentId() > 0 && $task->hasChild($task->getParentId())) {
                 flash_error(lang('task child of child error'));
                 ajx_current("empty");
                 return;
             }
             if (isset($task_data['percent_completed']) && $task_data['percent_completed'] >= 0 && $task_data['percent_completed'] <= 100) {
                 $task->setPercentCompleted($task_data['percent_completed']);
             }
             DB::beginWork();
             $task->save();
             if (!isset($task_data['percent_completed'])) {
                 $task->calculatePercentComplete();
             }
             // dependencies
             if (config_option('use tasks dependencies')) {
                 $previous_tasks = array_var($task_data, 'previous');
                 if (is_array($previous_tasks)) {
                     foreach ($previous_tasks as $ptask) {
                         if ($ptask == $task->getId()) {
                             continue;
                         }
                         $dep = ProjectTaskDependencies::findById(array('previous_task_id' => $ptask, 'task_id' => $task->getId()));
                         if (!$dep instanceof ProjectTaskDependency) {
                             $dep = new ProjectTaskDependency();
                             $dep->setPreviousTaskId($ptask);
                             $dep->setTaskId($task->getId());
                             $dep->save();
                         }
                     }
                     $saved_ptasks = ProjectTaskDependencies::findAll(array('conditions' => 'task_id = ' . $task->getId()));
                     foreach ($saved_ptasks as $pdep) {
                         if (!in_array($pdep->getPreviousTaskId(), $previous_tasks)) {
                             $pdep->delete();
                         }
                     }
                 } else {
                     ProjectTaskDependencies::delete('task_id = ' . $task->getId());
                 }
             }
             // Add assigned user to the subscibers list
             if ($task->getAssignedToContactId() > 0 && Contacts::instance()->findById($task->getAssignedToContactId())) {
                 if (!isset($_POST['subscribers'])) {
                     $_POST['subscribers'] = array();
                 }
                 $_POST['subscribers']['user_' . $task->getAssignedToContactId()] = '1';
             }
             $object_controller = new ObjectController();
             if ($isTemplateTask) {
                 $object_controller->add_to_members($task, $member_ids, null, false);
             } else {
                 $object_controller->add_to_members($task, $member_ids);
             }
             $is_template = $task instanceof TemplateTask;
             $object_controller->add_subscribers($task, null, !$is_template);
             $object_controller->link_to_new_object($task);
             $object_controller->add_custom_properties($task);
             if (!$task->isCompleted()) {
                 //to make sure the task it is not completed yet, and that it has subscribed people
                 $old_reminders = ObjectReminders::getByObject($task);
                 $object_controller->add_reminders($task);
                 //adding the new reminders, if any
                 $object_controller->update_reminders($task, $old_reminders);
                 //updating the old ones
                 if (logged_user() instanceof Contact && (!is_array($old_reminders) || count($old_reminders) == 0) && (user_config_option("add_task_autoreminder") && logged_user()->getId() != $task->getAssignedToContactId() || user_config_option("add_self_task_autoreminder") && logged_user()->getId() == $task->getAssignedToContactId())) {
                     //if there is no asignee, but it still has subscribers
                     $reminder = new ObjectReminder();
                     $def = explode(",", user_config_option("reminders_tasks"));
                     $minutes = $def[2] * $def[1];
                     $reminder->setMinutesBefore($minutes);
                     $reminder->setType($def[0]);
                     $reminder->setContext("due_date");
                     $reminder->setObject($task);
                     $reminder->setUserId(0);
                     $date = $task->getDueDate();
                     if ($date instanceof DateTimeValue) {
                         $rdate = new DateTimeValue($date->getTimestamp() - $minutes * 60);
                         $reminder->setDate($rdate);
                     }
                     $reminder->save();
                 }
             }
             if (!is_array($member_ids) || count($member_ids) == 0) {
                 $member_ids = array(0);
             }
             $members = Members::findAll(array('conditions' => "id IN (" . implode(',', $member_ids) . ")"));
             $task->apply_members_to_subtasks($members, true);
             // apply values to subtasks
             $assigned_to = $task->getAssignedToContactId();
             $subtasks = $task->getAllSubTasks();
             $milestone_id = $task->getMilestoneId();
             $apply_ms = array_var($task_data, 'apply_milestone_subtasks');
             $apply_at = array_var($task_data, 'apply_assignee_subtasks', '');
             foreach ($subtasks as $sub) {
                 $modified = false;
                 //if ($apply_at || !($sub->getAssignedToContactId() > 0)) {
                 if ($apply_at) {
                     $sub->setAssignedToContactId($assigned_to);
                     $modified = true;
                 }
                 if ($apply_ms) {
                     $sub->setMilestoneId($milestone_id);
                     $modified = true;
                 }
                 if ($modified) {
                     $sub->save();
                 }
                 //control date parent whit subtask
                 if ($_POST['control_dates'] == "father") {
                     if ($sub->getStartDate() instanceof DateTimeValue) {
                         if ($task->getStartDate() instanceof DateTimeValue) {
                             if ($task->getStartDate()->getTimestamp() > $sub->getStartDate()->getTimestamp()) {
                                 $sub->setStartDate($task->getStartDate());
                             }
                         }
                     } else {
                         if ($task->getStartDate() instanceof DateTimeValue) {
                             $sub->setStartDate($task->getStartDate());
                         }
                     }
                     $sub->setUseStartTime($task->getUseStartTime());
                     if ($sub->getDueDate() instanceof DateTimeValue) {
                         if ($task->getDueDate() instanceof DateTimeValue) {
                             if ($task->getDueDate()->getTimestamp() < $sub->getDueDate()->getTimestamp()) {
                                 $sub->setDueDate($task->getDueDate());
                             }
                         }
                     } else {
                         if ($task->getDueDate() instanceof DateTimeValue) {
                             $sub->setDueDate($task->getDueDate());
                         }
                     }
                     $sub->setUseDueTime($task->getUseDueTime());
                     $sub->save();
                 }
             }
             $task->resetIsRead();
             $log_info = '';
             if ($send_edit == true) {
                 $log_info = $task->getAssignedToContactId();
             } else {
                 if ($send_edit == false) {
                     $task->setAssignedBy(logged_user());
                     $task->save();
                 }
             }
             if (config_option('repeating_task') == 1) {
                 $opt_rep_day['saturday'] = false;
                 $opt_rep_day['sunday'] = false;
                 if (array_var($task_data, 'repeat_saturdays', false)) {
                     $opt_rep_day['saturday'] = true;
                 }
                 if (array_var($task_data, 'repeat_sundays', false)) {
                     $opt_rep_day['sunday'] = true;
                 }
                 $this->repetitive_task($task, $opt_rep_day);
             }
             if (isset($_POST['type_related'])) {
                 if ($_POST['type_related'] == "all" || $_POST['type_related'] == "news") {
                     $task_data['members'] = json_decode(array_var($_POST, 'members'));
                     unset($task_data['due_date']);
                     unset($task_data['use_due_time']);
                     unset($task_data['start_date']);
                     unset($task_data['use_start_time']);
                     $this->repetitive_tasks_related($task, "edit", $_POST['type_related'], $task_data);
                 }
             }
             if (config_option('multi_assignment') && Plugins::instance()->isActivePlugin('crpm')) {
                 if (array_var($task_data, 'multi_assignment_aplly_change') == 'subtask') {
                     $null = null;
                     Hook::fire('edit_subtasks', $task, $null);
                 }
             }
             //for calculate member status we save de task again after the object have the members
             $task->save();
             // save subtasks added in 'subtasks' tab
             $sub_tasks_to_log = $this->saveSubtasks($task, array_var($task_data, 'subtasks'), $member_ids);
             DB::commit();
             foreach ($sub_tasks_to_log['add'] as $st_to_log) {
                 ApplicationLogs::createLog($st_to_log, ApplicationLogs::ACTION_ADD);
             }
             foreach ($sub_tasks_to_log['edit'] as $st_to_log) {
                 ApplicationLogs::createLog($st_to_log, ApplicationLogs::ACTION_EDIT);
             }
             foreach ($sub_tasks_to_log['trash'] as $st_to_log) {
                 ApplicationLogs::createLog($st_to_log, ApplicationLogs::ACTION_TRASH);
             }
             //Send Template task to view
             if ($task instanceof TemplateTask) {
                 $objectId = $task->getObjectId();
                 $id = $task->getId();
                 $objectTypeName = $task->getObjectTypeName();
                 $objectName = $task->getObjectName();
                 $manager = get_class($task->manager());
                 $milestoneId = $task instanceof TemplateTask ? $task->getMilestoneId() : '0';
                 $subTasks = $task->getSubTasks();
                 $parentId = $task->getParentId();
                 $ico = "ico-task";
                 $action = "edit";
                 $object = TemplateController::prepareObject($objectId, $id, $objectName, $objectTypeName, $manager, $action, $milestoneId, $subTasks, $parentId, $ico);
                 $template_task_data = array('object' => $object);
                 if (array_var($_REQUEST, 'additional_tt_params')) {
                     $additional_tt_params = json_decode(str_replace("'", '"', array_var($_REQUEST, 'additional_tt_params')), true);
                     foreach ($additional_tt_params as $k => $v) {
                         $template_task_data[$k] = $v;
                     }
                 }
                 if (!array_var($_REQUEST, 'modal')) {
                     evt_add("template object added", $template_task_data);
                 }
             }
             try {
                 // notify asignee
                 if (array_var($task_data, 'send_notification') && $task->getAssignedToContactId() != $task->getAssignedById()) {
                     $new_owner = $task->getAssignedTo();
                     if ($new_owner instanceof Contact) {
                         Notifier::taskAssigned($task);
                     }
                     // if
                 }
                 // if
                 if (array_var($task_data, 'send_notification')) {
                     foreach ($sub_tasks_to_log['assigned'] as $st_to_log) {
                         Notifier::taskAssigned($st_to_log);
                     }
                 }
             } catch (Exception $e) {
             }
             // try
             //notify subscribers
             $isSilent = true;
             if (array_var($task_data, 'send_notification_subscribers')) {
                 $isSilent = false;
             }
             ApplicationLogs::createLog($task, ApplicationLogs::ACTION_EDIT, false, false, true, $log_info);
             //flash_success(lang('success edit task list', $task->getObjectName()));
             if (array_var($_REQUEST, 'modal')) {
                 if (array_var($_REQUEST, 'reload')) {
                     evt_add("reload current panel");
                 } else {
                     ajx_current("empty");
                     $this->setLayout("json");
                     $this->setTemplate(get_template_path("empty"));
                     // reload task info because plugins may have updated some task info (for example: name prefix)
                     if ($is_template) {
                         $task = TemplateTasks::findById($task->getId());
                     } else {
                         $task = ProjectTasks::findById($task->getId());
                     }
                     $params = array('msg' => lang('success edit task list', $task->getObjectName()), 'task' => $task->getArrayInfo(), 'reload' => array_var($_REQUEST, 'reload'));
                     if ($task instanceof TemplateTask) {
                         //$params['msg'] = lang('success edit template', $task->getObjectName());
                         $params['object'] = $template_task_data['object'];
                     }
                     //print_modal_json_response($params, true, array_var($_REQUEST, 'use_ajx'));
                     ajx_extra_data($params);
                 }
             } else {
                 ajx_current("back");
             }
             // if has subtasks and dates were changed, ask the user if the subtasks dates should also be changed
             if ($task instanceof ProjectTask && $task->countOpenSubTasks() > 0) {
                 // check if there was any due date changes
                 $dd_advance_info = null;
                 if ($task->getDueDate() instanceof DateTimeValue && $old_due_date instanceof DateTimeValue && $old_due_date->getTimestamp() != $task->getDueDate()->getTimestamp()) {
                     $dd_to_advance_ts = $task->getDueDate()->getTimestamp() - $old_due_date->getTimestamp();
                     if ($dd_to_advance_ts != 0) {
                         $dd_advance_info = get_time_info($dd_to_advance_ts);
                     }
                 }
                 // check if there was any start date changes
                 $sd_advance_info = null;
                 if ($task->getStartDate() instanceof DateTimeValue && $old_start_date instanceof DateTimeValue && $old_start_date->getTimestamp() != $task->getStartDate()->getTimestamp()) {
                     $sd_to_advance_ts = $task->getStartDate()->getTimestamp() - $old_start_date->getTimestamp();
                     if ($sd_to_advance_ts != 0) {
                         $sd_advance_info = get_time_info($sd_to_advance_ts);
                     }
                 }
                 if ($dd_advance_info != null || $sd_advance_info != null) {
                     evt_add('ask to change subtasks dates', array('dd_diff' => $dd_advance_info, 'sd_diff' => $sd_advance_info, 'task_id' => $task->getId()));
                 }
             }
         } catch (Exception $e) {
             DB::rollback();
             if (array_var($_REQUEST, 'modal')) {
                 $this->setLayout("json");
                 $this->setTemplate(get_template_path("empty"));
                 print_modal_json_response(array('errorCode' => 1, 'errorMessage' => $e->getMessage(), 'showMessage' => 1), true, array_var($_REQUEST, 'use_ajx'));
             } else {
                 flash_error($e->getMessage());
             }
             ajx_current("empty");
         }
         // try
     }
     // if
 }
 private function save_object($request)
 {
     $response = false;
     if (!empty($request['args'])) {
         $service = $request['srv'];
         switch ($service) {
             case "task":
                 if ($request['args']['id']) {
                     $object = ProjectTasks::instance()->findByid($request['args']['id']);
                 } else {
                     $object = new ProjectTask();
                 }
                 if ($object instanceof ProjectTask) {
                     if (!empty($request['args']['title'])) {
                         $object->setObjectName($request['args']['title']);
                     }
                     if (!empty($request['args']['description'])) {
                         $object->setText($request['args']['description']);
                     }
                     if (!empty($request['args']['due_date'])) {
                         if ($request['args']['due_date'] != '' && $request['args']['due_date'] != date_format_tip('dd/mm/yyyy')) {
                             $date_format = 'dd/mm/yyyy';
                             $object->setDueDate(DateTimeValueLib::dateFromFormatAndString($date_format, $value));
                         }
                     }
                     if (!empty($request['args']['completed'])) {
                         $object->setPercentCompleted($request['args']['completed']);
                     }
                     if (!empty($request['args']['assign_to'])) {
                         $object->setAssignedToContactId($request['args']['assign_to']);
                     }
                     if (!empty($request['args']['priority'])) {
                         $object->setPriority($request['args']['priority']);
                     }
                 }
                 break;
             case 'note':
                 if ($request['args']['id']) {
                     $object = ProjectMessages::instance()->findByid($request['args']['id']);
                 } else {
                     $object = new ProjectMessage();
                 }
                 if ($object instanceof ProjectMessage) {
                     if (!empty($request['args']['title'])) {
                         $object->setObjectName($request['args']['title']);
                     }
                     if (!empty($request['args']['title'])) {
                         $object->setText($request['args']['text']);
                     }
                 }
                 break;
         }
         // END SWITCH
         if ($object) {
             try {
                 $context = array();
                 $members = array();
                 if (!empty($request['args']['members'])) {
                     $members = $request['args']['members'];
                     $context = get_context_from_array($members);
                 }
                 //Check permissions:
                 if ($request['args']['id'] && $object->canEdit(logged_user()) || !$request['args']['id'] && $object->canAdd(logged_user(), $context)) {
                     DB::beginWork();
                     $object->save();
                     $object_controller = new ObjectController();
                     if (!$request['args']['id']) {
                         $object_controller->add_to_members($object, $members);
                     }
                     DB::commit();
                     $response = true;
                 }
             } catch (Exception $e) {
                 DB::rollback();
                 return false;
             }
         }
     }
     return $this->response('json', $response);
 }
Exemple #7
0
	/**
	 * Execute a report and return results
	 *
	 * @param $id
	 * @param $params
	 *
	 * @return array
	 */
	static function executeReport($id, $params, $order_by_col = '', $order_by_asc = true, $offset=0, $limit=50, $to_print = false) {
		if (is_null(active_context())) {
			CompanyWebsite::instance()->setContext(build_context_array(array_var($_REQUEST, 'context')));
		}
		$results = array();
		$report = self::getReport($id);
		if($report instanceof Report){
			$conditionsFields = ReportConditions::getAllReportConditionsForFields($id);
			$conditionsCp = ReportConditions::getAllReportConditionsForCustomProperties($id);
			
			$ot = ObjectTypes::findById($report->getReportObjectTypeId());
			$table = $ot->getTableName();
			
			eval('$managerInstance = ' . $ot->getHandlerClass() . "::instance();");
			eval('$item_class = ' . $ot->getHandlerClass() . '::instance()->getItemClass(); $object = new $item_class();');
			
			$order_by = '';
			if (is_object($params)) {
				$params = get_object_vars($params);				
			}
			
			$report_columns = ReportColumns::getAllReportColumns($id);

			$allConditions = "";
			
			if(count($conditionsFields) > 0){
				foreach($conditionsFields as $condField){
					
					$skip_condition = false;
					$model = $ot->getHandlerClass();
					$model_instance = new $model();
					$col_type = $model_instance->getColumnType($condField->getFieldName());

					$allConditions .= ' AND ';
					$dateFormat = 'm/d/Y';
					if(isset($params[$condField->getId()])){
						$value = $params[$condField->getId()];
						if ($col_type == DATA_TYPE_DATE || $col_type == DATA_TYPE_DATETIME)
						$dateFormat = user_config_option('date_format');
					} else {
						$value = $condField->getValue();
					}
					if ($value == '' && $condField->getIsParametrizable()) $skip_condition = true;
					if (!$skip_condition) {
						if($condField->getCondition() == 'like' || $condField->getCondition() == 'not like'){
							$value = '%'.$value.'%';
						}
						if ($col_type == DATA_TYPE_DATE || $col_type == DATA_TYPE_DATETIME) {
							$dtValue = DateTimeValueLib::dateFromFormatAndString($dateFormat, $value);
							$value = $dtValue->format('Y-m-d');
						}
						if($condField->getCondition() != '%'){
							if ($col_type == DATA_TYPE_INTEGER || $col_type == DATA_TYPE_FLOAT) {
								$allConditions .= '`'.$condField->getFieldName().'` '.$condField->getCondition().' '.DB::escape($value);
							} else {
								if ($condField->getCondition()=='=' || $condField->getCondition()=='<=' || $condField->getCondition()=='>='){
									if ($col_type == DATA_TYPE_DATETIME || $col_type == DATA_TYPE_DATE) {
										$equal = 'datediff('.DB::escape($value).', `'.$condField->getFieldName().'`)=0';
									} else {
										$equal = '`'.$condField->getFieldName().'` '.$condField->getCondition().' '.DB::escape($value);
									}
									switch($condField->getCondition()){
										case '=':
											$allConditions .= $equal;
											break;
										case '<=':
										case '>=':
											$allConditions .= '(`'.$condField->getFieldName().'` '.$condField->getCondition().' '.DB::escape($value).' OR '.$equal.') ';
											break;																
									}										
								} else {
									$allConditions .= '`'.$condField->getFieldName().'` '.$condField->getCondition().' '.DB::escape($value);
								}									
							}
						} else {
							$allConditions .= '`'.$condField->getFieldName().'` like '.DB::escape("%$value");
						}
					} else $allConditions .= ' true';
					
				}
			}
			if(count($conditionsCp) > 0){
				$dateFormat = user_config_option('date_format');
				$date_format_tip = date_format_tip($dateFormat);
				
				foreach($conditionsCp as $condCp){
					$cp = CustomProperties::getCustomProperty($condCp->getCustomPropertyId());

					$skip_condition = false;
					
					if(isset($params[$condCp->getId()."_".$cp->getName()])){
						$value = $params[$condCp->getId()."_".$cp->getName()];
					}else{
						$value = $condCp->getValue();
					}
					if ($value == '' && $condCp->getIsParametrizable()) $skip_condition = true;
					if (!$skip_condition) {
						$current_condition = ' AND ';
						$current_condition .= 'o.id IN ( SELECT object_id as id FROM '.TABLE_PREFIX.'custom_property_values cpv WHERE ';
						$current_condition .= ' cpv.custom_property_id = '.$condCp->getCustomPropertyId();
						$fieldType = $object->getColumnType($condCp->getFieldName());

						if($condCp->getCondition() == 'like' || $condCp->getCondition() == 'not like'){
							$value = '%'.$value.'%';
						}
						if ($cp->getType() == 'date') {
							if ($value == $date_format_tip) continue;
							$dtValue = DateTimeValueLib::dateFromFormatAndString($dateFormat, $value);
							$value = $dtValue->format('Y-m-d H:i:s');
						}
						if($condCp->getCondition() != '%'){
							if ($cp->getType() == 'numeric') {
								$current_condition .= ' AND cpv.value '.$condCp->getCondition().' '.DB::escape($value);
							}else if ($cp->getType() == 'boolean') {
								$current_condition .= ' AND cpv.value '.$condCp->getCondition().' '.$value;
								if (!$value) {
									$current_condition .= ') OR o.id NOT IN (SELECT object_id as id FROM '.TABLE_PREFIX.'custom_property_values cpv2 WHERE cpv2.object_id=o.id AND cpv2.value=1 AND cpv2.custom_property_id = '.$condCp->getCustomPropertyId();
								}
							}else{
								$current_condition .= ' AND cpv.value '.$condCp->getCondition().' '.DB::escape($value);
							}
						}else{
							$current_condition .= ' AND cpv.value like '.DB::escape("%$value");
						}
						$current_condition .= ')';
						$allConditions .= $current_condition;
					}
				}
			}
			
			$select_columns = array('*');
			$join_params = null;
			if ($order_by_col == '') {
				$order_by_col = $report->getOrderBy();
			}
			if (in_array($order_by_col, self::$external_columns)) {
				$original_order_by_col = $order_by_col;
				$order_by_col = 'name_order';
				$join_params = array(
					'table' => Objects::instance()->getTableName(),
					'jt_field' => 'id',
					'e_field' => $original_order_by_col,
					'join_type' => 'left'
				);
				$select_columns = array();
				$tmp_cols = $managerInstance->getColumns();
				foreach ($tmp_cols as $col) $select_columns[] = "e.$col";
				$tmp_cols = Objects::instance()->getColumns();
				foreach ($tmp_cols as $col) $select_columns[] = "o.$col";
				$select_columns[] = 'jt.name as name_order';
			}
			if ($order_by_asc == null) $order_by_asc = $report->getIsOrderByAsc();

			if ($ot->getName() == 'task' && !SystemPermissions::userHasSystemPermission(logged_user(), 'can_see_assigned_to_other_tasks')) {
				$allConditions .= " AND assigned_to_contact_id = ".logged_user()->getId();
			}
			
			if ($managerInstance) {
				$result = $managerInstance->listing(array(
					"select_columns" => $select_columns,
					"order" => "$order_by_col",
					"order_dir" => ($order_by_asc ? "ASC" : "DESC"),
					"extra_conditions" => $allConditions,
					"join_params" => $join_params
				));
			}else{
				// TODO Performance Killer
				$result = ContentDataObjects::getContentObjects(active_context(), $ot, $order_by_col, ($order_by_asc ? "ASC" : "DESC"), $allConditions);
			}
			$objects = $result->objects;
			$totalResults = $result->total;

			$results['pagination'] = Reports::getReportPagination($id, $params, $order_by_col, $order_by_asc, $offset, $limit, $totalResults);
		
			$dimensions_cache = array();
			
			foreach($report_columns as $column){
				if ($column->getCustomPropertyId() == 0) {
					$field = $column->getFieldName();
					if (str_starts_with($field, 'dim_')) {
						$dim_id = str_replace("dim_", "", $field);
						$dimension = Dimensions::getDimensionById($dim_id);
						$dimensions_cache[$dim_id] = $dimension;
						$doptions = $dimension->getOptions(true);
						$column_name = $doptions && isset($doptions->useLangs) && $doptions->useLangs ? lang($dimension->getCode()) : $dimension->getName();
						
						$results['columns'][$field] = $column_name;
						$results['db_columns'][$column_name] = $field;
					} else {
						if ($managerInstance->columnExists($field) || Objects::instance()->columnExists($field)) {
							$column_name = Localization::instance()->lang('field '.$ot->getHandlerClass().' '.$field);
							if (is_null($column_name)) $column_name = lang('field Objects '.$field);
							$results['columns'][$field] = $column_name;
							$results['db_columns'][$column_name] = $field;
						}
					}
				} else {
					$results['columns'][$column->getCustomPropertyId()] = $column->getCustomPropertyId();
				}
			}
			
			$report_rows = array();
			foreach($objects as &$object){/* @var $object Object */
				$obj_name = $object->getObjectName();
				$icon_class = $object->getIconClass();
				
				$row_values = array('object_type_id' => $object->getObjectTypeId());
				
				if (!$to_print) {
					$row_values['link'] = '<a class="link-ico '.$icon_class.'" title="' . $obj_name . '" target="new" href="' . $object->getViewUrl() . '">&nbsp;</a>';
				}
				
				foreach($report_columns as $column){
					if ($column->getCustomPropertyId() == 0) {
						
						$field = $column->getFieldName();
						
						if (str_starts_with($field, 'dim_')) {
							$dim_id = str_replace("dim_", "", $field);
							if (!array_var($dimensions_cache, $dim_id) instanceof Dimension) {
								$dimension = Dimensions::getDimensionById($dim_id);
								$dimensions_cache[$dim_id] = $dimension;
							} else {
								$dimension = array_var($dimensions_cache, $dim_id);
							}
							$members = ObjectMembers::getMembersByObjectAndDimension($object->getId(), $dim_id, " AND om.is_optimization=0");
							
							$value = "";
							foreach ($members as $member) {/* @var $member Member */
								$val = $member->getPath();
								$val .= ($val == "" ? "" : "/") . $member->getName();
								
								if ($value != "") $val = " - $val";
								$value .= $val;
							}
							
							$row_values[$field] = $value;
						} else {
						
							$value = $object->getColumnValue($field);
								
							if ($value instanceof DateTimeValue) {
								$field_type = $managerInstance->columnExists($field) ? $managerInstance->getColumnType($field) : Objects::instance()->getColumnType($field);
								$value = format_value_to_print($field, $value->toMySQL(), $field_type, $report->getReportObjectTypeId());
							}
								
							if(in_array($field, $managerInstance->getExternalColumns())){
								$value = self::instance()->getExternalColumnValue($field, $value, $managerInstance);
							} else if ($field != 'link'){
								$value = html_to_text($value);
							}
							if(self::isReportColumnEmail($value)) {
								if(logged_user()->hasMailAccounts()){
									$value = '<a class="internalLink" href="'.get_url('mail', 'add_mail', array('to' => clean($value))).'">'.clean($value).'</a></div>';
								}else{
									$value = '<a class="internalLink" target="_self" href="mailto:'.clean($value).'">'.clean($value).'</a></div>';
								}
							}	
							$row_values[$field] = $value;
						}
					} else {
						
						$colCp = $column->getCustomPropertyId();
						$cp = CustomProperties::getCustomProperty($colCp);
						if ($cp instanceof CustomProperty) { /* @var $cp CustomProperty */
							
							$cp_val = CustomPropertyValues::getCustomPropertyValue($object->getId(), $colCp);
							$row_values[$cp->getName()] = $cp_val instanceof CustomPropertyValue ? $cp_val->getValue() : "";
							
							$results['columns'][$colCp] = $cp->getName();
							$results['db_columns'][$cp->getName()] = $colCp;
							
						}
					}
				}
				

				Hook::fire("report_row", $object, $row_values);
				$report_rows[] = $row_values;
			}
			
			if (!$to_print) {
				if (is_array($results['columns'])) {
					array_unshift($results['columns'], '');
				} else {
					$results['columns'] = array('');
				}
				Hook::fire("report_header", $ot, $results['columns']);
			}
			$results['rows'] = $report_rows;
		}

		return $results;
	} //  executeReport
 /**
  * Adds the custom properties of an object into the database.
  * 
  * @param $object
  * @return unknown_type
  */
 function add_custom_properties($object)
 {
     if (logged_user()->isGuest()) {
         flash_error(lang('no access permissions'));
         ajx_current("empty");
         return;
     }
     $obj_custom_properties = array_var($_POST, 'object_custom_properties');
     if (is_array($obj_custom_properties)) {
         foreach ($obj_custom_properties as $id => &$val) {
             $val = remove_scripts($val);
         }
     }
     $date_format = user_config_option('date_format');
     $date_format_tip = date_format_tip($date_format);
     $required_custom_props = array();
     $object_type_id = $object instanceof TemplateTask ? ProjectTasks::instance()->getObjectTypeId() : $object->getObjectTypeId();
     $customProps = CustomProperties::getAllCustomPropertiesByObjectType($object_type_id);
     //Sets all boolean custom properties to 0. If any boolean properties are returned, they are subsequently set to 1.
     foreach ($customProps as $cp) {
         if ($cp->getType() == 'boolean') {
             $custom_property_value = CustomPropertyValues::getCustomPropertyValue($object->getId(), $cp->getId());
             if (!$custom_property_value instanceof CustomPropertyValue) {
                 $custom_property_value = new CustomPropertyValue();
             }
             $custom_property_value->setObjectId($object->getId());
             $custom_property_value->setCustomPropertyId($cp->getId());
             $custom_property_value->setValue(0);
             $custom_property_value->save();
         }
         if ($cp->getIsRequired()) {
             $required_custom_props[] = $cp;
         }
     }
     foreach ($required_custom_props as $req_cp) {
         if (!isset($obj_custom_properties[$req_cp->getId()])) {
             throw new Exception(lang('custom property value required', $req_cp->getName()));
         }
     }
     if (is_array($obj_custom_properties)) {
         // check required custom properties
         foreach ($obj_custom_properties as $id => $value) {
             //Get the custom property
             $custom_property = null;
             foreach ($customProps as $cp) {
                 if ($cp->getId() == $id) {
                     $custom_property = $cp;
                     break;
                 }
             }
             if ($custom_property instanceof CustomProperty) {
                 // save dates in standard format "Y-m-d H:i:s", because the column type is string
                 if ($custom_property->getType() == 'date') {
                     if (is_array($value)) {
                         $newValues = array();
                         foreach ($value as $val) {
                             if (trim($val) != '' && trim($val) != $date_format_tip) {
                                 $dtv = DateTimeValueLib::dateFromFormatAndString($date_format, $val);
                                 $newValues[] = $dtv->format("Y-m-d H:i:s");
                             }
                         }
                         $value = $newValues;
                     } else {
                         if (trim($value) != '' && trim($val) != $date_format_tip) {
                             $dtv = DateTimeValueLib::dateFromFormatAndString($date_format, $value);
                             $value = $dtv->format("Y-m-d H:i:s");
                         } else {
                             $value = '';
                         }
                     }
                 }
                 foreach (array_var($_REQUEST, 'remove_custom_properties', array()) as $cpropid => $remove) {
                     if ($remove) {
                         CustomPropertyValues::deleteCustomPropertyValues($object->getId(), $cpropid);
                     }
                 }
                 Hook::fire('before_save_custom_property_value', array('custom_prop' => $custom_property), $value);
                 if (is_array($value)) {
                     if ($custom_property->getType() == 'address') {
                         if ($custom_property->getIsRequired()) {
                             if (array_var($value, 'street') == '' && array_var($value, 'city') == '' && array_var($value, 'state') == '' && array_var($value, 'country') == '' && array_var($value, 'zip_code') == '') {
                                 throw new Exception(lang('custom property value required', $custom_property->getName()));
                             }
                             $errors = array(lang('error form validation'));
                             Env::useHelper('form');
                             $ok = checkAddressInputMandatoryFields($value, $custom_property->getName(), $errors);
                             if (!$ok) {
                                 throw new Exception(implode("\n - ", $errors));
                             }
                         }
                         // Address custom property
                         $val = array_var($value, 'type') . '|' . array_var($value, 'street') . '|' . array_var($value, 'city') . '|' . array_var($value, 'state') . '|' . array_var($value, 'country') . '|' . array_var($value, 'zip_code');
                         CustomPropertyValues::deleteCustomPropertyValues($object->getId(), $id);
                         $custom_property_value = new CustomPropertyValue();
                         $custom_property_value->setObjectId($object->getId());
                         $custom_property_value->setCustomPropertyId($id);
                         $custom_property_value->setValue($val);
                         $custom_property_value->save();
                     } else {
                         //Save multiple values
                         CustomPropertyValues::deleteCustomPropertyValues($object->getId(), $id);
                         foreach ($value as &$val) {
                             if (is_array($val)) {
                                 // CP type == table
                                 $str_val = '';
                                 foreach ($val as $col_val) {
                                     $col_val = str_replace("|", "\\|", $col_val);
                                     $str_val .= ($str_val == '' ? '' : '|') . $col_val;
                                 }
                                 $val = $str_val;
                             }
                             if ($val != '') {
                                 $custom_property_value = new CustomPropertyValue();
                                 $custom_property_value->setObjectId($object->getId());
                                 $custom_property_value->setCustomPropertyId($id);
                                 $custom_property_value->setValue($val);
                                 $custom_property_value->save();
                             }
                         }
                     }
                 } else {
                     if ($custom_property->getType() == 'boolean') {
                         $value = isset($value);
                     }
                     $cpv = CustomPropertyValues::getCustomPropertyValue($object->getId(), $id);
                     if ($cpv instanceof CustomPropertyValue) {
                         $custom_property_value = $cpv;
                     } else {
                         $custom_property_value = new CustomPropertyValue();
                         $custom_property_value->setObjectId($object->getId());
                         $custom_property_value->setCustomPropertyId($id);
                     }
                     $custom_property_value->setValue($value);
                     $custom_property_value->save();
                 }
                 //Add to searchable objects
                 if ($object->isSearchable() && ($custom_property->getType() == 'text' || $custom_property->getType() == 'list' || $custom_property->getType() == 'numeric')) {
                     $name = str_replace("'", "\\'", $custom_property->getName());
                     if (is_array($value)) {
                         $value = implode(', ', $value);
                     }
                     $value = str_replace("'", "\\'", $value);
                     $sql = "INSERT INTO " . TABLE_PREFIX . "searchable_objects (rel_object_id, column_name, content)\r\n\t\t\t\t\t\tVALUES ('" . $object->getId() . "', '" . $name . "', '" . $value . "')\r\n\t\t\t\t\t\tON DUPLICATE KEY UPDATE content='" . $value . "'";
                     DB::execute($sql);
                 }
             }
         }
     }
     //Save the key - value pair custom properties (object_properties table)
     $object->clearObjectProperties();
     $names = array_var($_POST, 'custom_prop_names');
     $values = array_var($_POST, 'custom_prop_values');
     if (!is_array($names)) {
         return;
     }
     for ($i = 0; $i < count($names); $i++) {
         $name = trim($names[$i]);
         $value = trim($values[$i]);
         if ($name != '' && $value != '') {
             $property = new ObjectProperty();
             $property->setObject($object);
             $property->setPropertyName($name);
             $property->setPropertyValue($value);
             $property->save();
             if ($object->isSearchable()) {
                 $object->addPropertyToSearchableObject($property);
             }
         }
     }
 }
 function total_task_times($report_data = null, $task = null, $csv = null)
 {
     if (!$report_data) {
         $report_data = array_var($_POST, 'report');
         set_user_config_option('timeReportDate', $report_data['date_type'], logged_user()->getId());
         $dateStart = getDateValue($report_data['start_value']);
         if ($dateStart instanceof DateTimeValue) {
             set_user_config_option('timeReportDateStart', $dateStart, logged_user()->getId());
         }
         $dateEnd = getDateValue($report_data['end_value']);
         if ($dateEnd instanceof DateTimeValue) {
             set_user_config_option('timeReportDateEnd', $dateEnd, logged_user()->getId());
         }
         set_user_config_option('timeReportShowEstimatedTime', array_var($report_data, 'show_estimated_time') == 'checked', logged_user()->getId());
         set_user_config_option('timeReportPerson', $report_data['user'], logged_user()->getId());
         set_user_config_option('timeReportTimeslotType', $report_data['timeslot_type'], logged_user()->getId());
         set_user_config_option('timeReportShowBilling', isset($report_data['show_billing']) ? 1 : 0, logged_user()->getId());
         $group = $report_data['group_by_1'] . ", " . $report_data['group_by_2'] . ", " . $report_data['group_by_3'];
         $altGroup = $report_data['alt_group_by_1'] . "," . $report_data['alt_group_by_2'] . "," . $report_data['alt_group_by_3'];
         set_user_config_option('timeReportGroupBy', $group, logged_user()->getId());
         set_user_config_option('timeReportAltGroupBy', $altGroup, logged_user()->getId());
         $_SESSION['total_task_times_report_data'] = $report_data;
     }
     if (array_var($_GET, 'export') == 'csv' || isset($csv) && $csv == true) {
         $context = build_context_array(array_var($_REQUEST, 'context'));
         CompanyWebsite::instance()->setContext($context);
         if (!$report_data) {
             if (isset($_REQUEST['parameters'])) {
                 $report_data = json_decode(str_replace("'", '"', $_REQUEST['parameters']), true);
             } else {
                 $report_data = $_REQUEST;
             }
         }
         tpl_assign('context', $context);
         $this->setTemplate('total_task_times_csv');
     } else {
         $context = active_context();
     }
     $columns = array_var($report_data, 'columns');
     if (!is_array($columns)) {
         $columns = array_var($_POST, 'columns', array());
     }
     asort($columns);
     //sort the array by column order
     foreach ($columns as $column => $order) {
         if ($order > 0) {
             $newColumn = new ReportColumn();
             //$newColumn->setReportId($newReport->getId());
             if (is_numeric($column)) {
                 $newColumn->setCustomPropertyId($column);
             } else {
                 $newColumn->setFieldName($column);
             }
         }
     }
     $user = Contacts::findById(array_var($report_data, 'user'));
     $now = DateTimeValueLib::now();
     $now->advance(logged_user()->getTimezone() * 3600, true);
     switch (array_var($report_data, 'date_type')) {
         case 1:
             //Today
             $st = DateTimeValueLib::make(0, 0, 0, $now->getMonth(), $now->getDay(), $now->getYear());
             $et = DateTimeValueLib::make(23, 59, 59, $now->getMonth(), $now->getDay(), $now->getYear());
             break;
         case 2:
             //This week
             $monday = $now->getMondayOfWeek();
             $nextMonday = $now->getMondayOfWeek()->add('w', 1)->add('d', -1);
             $st = DateTimeValueLib::make(0, 0, 0, $monday->getMonth(), $monday->getDay(), $monday->getYear());
             $et = DateTimeValueLib::make(23, 59, 59, $nextMonday->getMonth(), $nextMonday->getDay(), $nextMonday->getYear());
             break;
         case 3:
             //Last week
             $monday = $now->getMondayOfWeek()->add('w', -1);
             $nextMonday = $now->getMondayOfWeek()->add('d', -1);
             $st = DateTimeValueLib::make(0, 0, 0, $monday->getMonth(), $monday->getDay(), $monday->getYear());
             $et = DateTimeValueLib::make(23, 59, 59, $nextMonday->getMonth(), $nextMonday->getDay(), $nextMonday->getYear());
             break;
         case 4:
             //This month
             $st = DateTimeValueLib::make(0, 0, 0, $now->getMonth(), 1, $now->getYear());
             $et = DateTimeValueLib::make(23, 59, 59, $now->getMonth(), 1, $now->getYear())->add('M', 1)->add('d', -1);
             break;
         case 5:
             //Last month
             $now->add('M', -1);
             $st = DateTimeValueLib::make(0, 0, 0, $now->getMonth(), 1, $now->getYear());
             $et = DateTimeValueLib::make(23, 59, 59, $now->getMonth(), 1, $now->getYear())->add('M', 1)->add('d', -1);
             break;
         case 6:
             //Date interval
             $st = getDateValue(array_var($report_data, 'start_value'));
             $st = $st->beginningOfDay();
             $et = getDateValue(array_var($report_data, 'end_value'));
             $et = $et->endOfDay();
             break;
     }
     if ($st instanceof DateTimeValue) {
         $st->add('h', -logged_user()->getTimezone());
     }
     if ($et instanceof DateTimeValue) {
         $et->add('h', -logged_user()->getTimezone());
     }
     $timeslotType = array_var($report_data, 'timeslot_type', 0);
     $group_by = array();
     for ($i = 1; $i <= 3; $i++) {
         if ($timeslotType == 0) {
             $gb = array_var($report_data, 'group_by_' . $i);
         } else {
             $gb = array_var($report_data, 'alt_group_by_' . $i);
         }
         if ($gb != '0') {
             $group_by[] = $gb;
         }
     }
     $dateFormat = user_config_option('date_format');
     $date_format_tip = date_format_tip($dateFormat);
     $extra_conditions = "";
     $conditions = array_var($_POST, 'conditions', array());
     foreach ($conditions as $cond) {
         if ($cond['deleted'] > 0) {
             continue;
         }
         if (array_var($cond, 'custom_property_id') > 0) {
             if (!in_array($cond['condition'], array('like', 'not like', '=', '<=', '>=', '<', '>', '<>', '%'))) {
                 continue;
             }
             $cp = CustomProperties::getCustomProperty($cond['custom_property_id']);
             if (!$cp instanceof CustomProperty) {
                 continue;
             }
             $current_condition = ' AND e.rel_object_id IN ( SELECT object_id as id FROM ' . TABLE_PREFIX . 'custom_property_values cpv WHERE cpv.custom_property_id = ' . $cond['custom_property_id'];
             $value = $cond['value'];
             if ($cond['condition'] == 'like' || $cond['condition'] == 'not like') {
                 $value = '%' . $cond['value'] . '%';
             }
             if ($cp->getType() == 'date') {
                 if ($value == $date_format_tip) {
                     continue;
                 }
                 $dtValue = DateTimeValueLib::dateFromFormatAndString($dateFormat, $value);
                 $value = $dtValue->format('Y-m-d H:i:s');
             }
             if ($cond['condition'] != '%') {
                 if ($cp->getType() == 'numeric') {
                     $current_condition .= ' AND cpv.value ' . $cond['condition'] . ' ' . DB::escape($value);
                 } else {
                     if ($cp->getType() == 'boolean') {
                         $current_condition .= ' AND cpv.value ' . $cond['condition'] . ' ' . ($value ? '1' : '0');
                         if (!$value) {
                             $current_condition .= ') OR o.id NOT IN (SELECT object_id as id FROM ' . TABLE_PREFIX . 'custom_property_values cpv2 WHERE cpv2.object_id=o.id AND cpv2.value=1 AND cpv2.custom_property_id = ' . $cp->getId();
                         }
                     } else {
                         $current_condition .= ' AND cpv.value ' . $cond['condition'] . ' ' . DB::escape($value);
                     }
                 }
             } else {
                 $current_condition .= ' AND cpv.value like ' . DB::escape("%{$value}");
             }
             $current_condition .= ')';
             $extra_conditions .= $current_condition;
         }
     }
     $timeslots = Timeslots::getTaskTimeslots($context, null, $user, $st, $et, array_var($report_data, 'task_id', 0), $group_by, null, null, null, $timeslotType, $extra_conditions);
     $unworkedTasks = null;
     if (array_var($report_data, 'include_unworked') == 'checked') {
         $unworkedTasks = ProjectTasks::getPendingTasks(logged_user(), $workspace);
         tpl_assign('unworkedTasks', $unworkedTasks);
     }
     $gb_criterias = array();
     foreach ($group_by as $text) {
         if (in_array($text, array('contact_id', 'rel_object_id'))) {
             $gb_criterias[] = array('type' => 'column', 'value' => $text);
         } else {
             if (in_array($text, array('milestone_id', 'priority'))) {
                 $gb_criterias[] = array('type' => 'assoc_obj', 'fk' => 'rel_object_id', 'value' => $text);
             } else {
                 if (str_starts_with($text, 'dim_')) {
                     $gb_criterias[] = array('type' => 'dimension', 'value' => str_replace_first('dim_', '', $text));
                 }
             }
         }
     }
     $grouped_timeslots = groupObjects($gb_criterias, $timeslots);
     tpl_assign('columns', $columns);
     tpl_assign('timeslotsArray', array());
     tpl_assign('grouped_timeslots', $grouped_timeslots);
     if (array_var($report_data, 'date_type') == 6) {
         $st->advance(logged_user()->getTimezone() * 3600, true);
         $et->advance(logged_user()->getTimezone() * 3600, true);
     }
     tpl_assign('start_time', $st);
     tpl_assign('end_time', $et);
     tpl_assign('user', $user);
     tpl_assign('post', $report_data);
     tpl_assign('title', lang('task time report'));
     tpl_assign('allow_export', false);
     if (array_var($_GET, 'export') == 'csv' || isset($csv) && $csv == true) {
         $filename = $this->total_task_times_csv_export($grouped_timeslots);
         ajx_extra_data(array('filename' => "{$filename}.csv"));
         ajx_current("empty");
     } else {
         tpl_assign('template_name', 'total_task_times');
         $this->setTemplate('report_wrapper');
     }
 }