/**
  * 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;
 }
 function render_add_subscribers()
 {
     $context = build_context_array(array_var($_GET, 'context', ''));
     $uids = array_var($_GET, 'users', '');
     $genid = array_var($_GET, 'genid', '');
     $otype = array_var($_GET, 'otype', '');
     $subscriberIds = explode(",", $uids);
     tpl_assign('object_type_id', $otype);
     tpl_assign('context', $context);
     tpl_assign('subscriberIds', $subscriberIds);
     tpl_assign('genid', $genid);
     $this->setLayout("html");
     $this->setTemplate("add_subscribers");
 }
 function allowed_users_to_assign()
 {
     $context_plain = array_var($_GET, 'context');
     $context = null;
     if (!is_null($context_plain)) {
         $context = build_context_array($context_plain);
     }
     $comp_array = allowed_users_to_assign_all($context);
     $object = array("companies" => $comp_array);
     if (!can_manage_tasks(logged_user()) && can_task_assignee(logged_user())) {
         $object['only_me'] = "1";
     }
     ajx_extra_data($object);
     ajx_current("empty");
 }
 function allowed_users_to_assign()
 {
     $members = array();
     $member_ids = explode(',', array_var($_GET, 'member_ids'));
     if (count($member_ids) > 0) {
         $tmp_members = Members::findAll(array('conditions' => 'id IN (' . implode(',', $member_ids) . ')'));
         foreach ($tmp_members as $m) {
             if ($m->getDimension()->getIsManageable()) {
                 $members[] = $m;
             }
         }
     }
     if (count($members) == 0) {
         $context_plain = array_var($_GET, 'context');
         $context = null;
         if (!is_null($context_plain)) {
             $context = build_context_array($context_plain);
         }
     } else {
         $context = $members;
     }
     $comp_array = allowed_users_to_assign($context);
     $object = array("companies" => $comp_array);
     Hook::fire('modify_allowed_users_to_assign', array('params' => array_var($_REQUEST, 'extra_params')), $object);
     if (!can_manage_tasks(logged_user()) && can_task_assignee(logged_user())) {
         $object['only_me'] = "1";
     }
     ajx_extra_data($object);
     ajx_current("empty");
 }
 private function initContext()
 {
     $context_plain = array_var($_GET, 'context');
     $context = build_context_array($context_plain);
     $this->setContext($context);
 }
 function total_task_times($report_data = null, $task = null)
 {
     if (!$report_data) {
         $report_data = array_var($_POST, 'report');
         // save selections into session
         $_SESSION['total_task_times_report_data'] = $report_data;
     }
     if (array_var($_GET, 'export') == 'csv') {
         $context = build_context_array(array_var($_REQUEST, 'context'));
         $report_data = json_decode(str_replace("'", '"', $_REQUEST['parameters']), true);
         tpl_assign('context', $context);
     } 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;
     }
     $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;
         }
     }
     $timeslots = Timeslots::getTaskTimeslots($context, null, $user, $st, $et, array_var($report_data, 'task_id', 0), $group_by, null, null, null, $timeslotType);
     $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('template_name', 'total_task_times');
     tpl_assign('title', lang('task time report'));
     tpl_assign('allow_export', false);
     if (array_var($_GET, 'export') == 'csv') {
         $this->setTemplate('total_task_times_csv');
         ajx_current("empty");
     } else {
         $this->setTemplate('report_wrapper');
     }
 }
	function allowed_users_view_events() {
		$comp_array = array();
		$actual_user_id = isset($_GET['user']) ? $_GET['user'] : logged_user()->getId();
		$evid = array_var($_GET, 'evid');
		
		$i = 0;
		$companies_tmp = Contacts::findAll(array("conditions" => "is_company = 1"));
		$companies = array("0" => array('id' => $i++, 'name' => lang('without company'), 'logo_url' => '#'));
		foreach ($companies_tmp as $comptmp) {
			$companies[$comptmp->getId()] = array(
				'id' => $i++,
				'name' => $comptmp->getObjectName(),
				'logo_url' => $comptmp->getPictureUrl()
			);
		}
		
		$context_plain = array_var($_GET, 'context');
		if (is_null($context_plain) || $context_plain == "") $context = active_context();
		else $context = build_context_array($context_plain);
		
		$users = allowed_users_in_context(ProjectEvents::instance()->getObjectTypeId(), $context, ACCESS_LEVEL_READ);
		
		foreach ($companies as $id => $comp) {
			if (is_array($users) && count($users) > 0) {
				$comp_data = array(
					'id' => $comp['id'],
					'object_id' => $id,
					'name' => $comp['name'],
					'logo_url' => $comp['logo_url'],
					'users' => array() 
				);
				foreach ($users as $user) {
					if ($user->getCompanyId() == $id) {
						$comp_data['users'][] = array(
							'id' => $user->getId(),
							'name' => $user->getObjectName(),
							'avatar_url' => $user->getPictureUrl(),
							'invited' => $evid == 0 ? ($user->getId() == $actual_user_id) : (EventInvitations::findOne(array('conditions' => "`event_id` = $evid and `contact_id` = ".$user->getId())) != null),
							'mail' => $user->getEmailAddress()
						);
					}
				}
				if (count($comp_data['users']) > 0) {
					$comp_array[] = $comp_data;
				}
			}
		}
		
		$object = array(
			"totalCount" => count($comp_array),
			"start" => 0,
			"companies" => $comp_array
		);

		ajx_extra_data($object);
		ajx_current("empty");
	}
	function render_add_milestone() {
		$genid = array_var($_GET, 'genid', '');				
		tpl_assign('genid', $genid);
		$context = build_context_array(array_var($_GET, 'context', ''));
		tpl_assign('context', $context);
		$task_data = array('milestone_id' => array_var($_GET, 'selected'));
		tpl_assign('task_data', $task_data);
		$this->setLayout("html");
		$this->setTemplate("add_select_milestone");	
	}
Exemple #9
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
 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');
     }
 }