function format_value_to_print_task($value, $type, $textWrapper = '', $dateformat = 'Y-m-d') { switch ($type) { case DATA_TYPE_STRING: if (preg_match(EMAIL_FORMAT, strip_tags($value))) { $formatted = $value; } else { $formatted = $textWrapper . clean($value) . $textWrapper; } break; case DATA_TYPE_INTEGER: $formatted = clean($value); break; case DATA_TYPE_BOOLEAN: $formatted = $value == 1 ? lang('yes') : lang('no'); break; case DATA_TYPE_DATE: if ($value != 0) { if (str_ends_with($value, "00:00:00")) { $dateformat .= " H:i:s"; } $dtVal = DateTimeValueLib::dateFromFormatAndString($dateformat, $value); $formatted = format_date($dtVal, null, 0); } else { $formatted = ''; } break; case DATA_TYPE_DATETIME: if ($value != 0) { $dtVal = DateTimeValueLib::dateFromFormatAndString("{$dateformat} H:i:s", $value); $formatted = format_date($dtVal, null, 0); } else { $formatted = ''; } break; default: $formatted = $value; } if ($formatted == '') { $formatted = '--'; } return $formatted; }
/** * 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) { $results = array(); $report = self::getReport($id); if ($report instanceof Report) { $conditionsFields = ReportConditions::getAllReportConditionsForFields($id); $conditionsCp = ReportConditions::getAllReportConditionsForCustomProperties($id); $table = ''; $object = null; $controller = ''; $view = ''; eval('$managerInstance = ' . $report->getObjectType() . "::instance();"); if ($report->getObjectType() == 'Companies') { $table = 'companies'; $controller = 'company'; $view = 'card'; $object = new Company(); } else { if ($report->getObjectType() == 'Contacts') { $table = 'contacts'; $controller = 'contact'; $view = 'card'; $object = new Contact(); } else { if ($report->getObjectType() == 'MailContents') { $table = 'mail_contents'; $controller = 'mail'; $view = 'view'; $object = new MailContent(); } else { if ($report->getObjectType() == 'ProjectEvents') { $table = 'project_events'; $controller = 'event'; $view = 'viewevent'; $object = new ProjectEvent(); } else { if ($report->getObjectType() == 'ProjectFiles') { $table = 'project_files'; $controller = 'files'; $view = 'file_details'; $object = new ProjectFile(); } else { if ($report->getObjectType() == 'ProjectMilestones') { $table = 'project_milestones'; $controller = 'milestone'; $view = 'view'; $object = new ProjectMilestone(); } else { if ($report->getObjectType() == 'ProjectMessages') { $table = 'project_messages'; $controller = 'message'; $view = 'view'; $object = new ProjectMessage(); } else { if ($report->getObjectType() == 'ProjectTasks') { $table = 'project_tasks'; $controller = 'task'; $view = 'view_task'; $object = new ProjectTask(); } else { if ($report->getObjectType() == 'Users') { $table = 'users'; $controller = 'user'; $view = 'card'; $object = new User(); } else { if ($report->getObjectType() == 'ProjectWebpages') { $table = 'project_webpages'; $controller = 'webpage'; $view = 'view'; $object = new ProjectWebpage(); } else { if ($report->getObjectType() == 'Projects') { $table = 'projects'; $controller = 'project'; $view = ''; $object = new Project(); } } } } } } } } } } } $order_by = ''; if (is_object($params)) { $params = get_object_vars($params); } $sql = 'SELECT id FROM ' . TABLE_PREFIX . $table . ' t WHERE '; $manager = $report->getObjectType(); $allConditions = permissions_sql_for_listings(new $manager(), ACCESS_LEVEL_READ, logged_user(), 'project_id', 't'); if (count($conditionsFields) > 0) { foreach ($conditionsFields as $condField) { if ($condField->getFieldName() == 'workspace' || $condField->getFieldName() == 'tag') { //if has a tag or workspace condition if ($condField->getFieldName() == 'workspace') { //if is a workspace condition: $fiterUsingWorkspace = true; if ($condField->getIsParametrizable() && isset($params['workspace'])) { //if is parameter condition and is set the parameter $ws_value = $params['workspace']; } else { //if is a fixed workspace value and is set $val = $condField->getValue(); if (isset($val)) { $ws_value = $val; } else { //if there is no workspace to filter with it doesnt filter at all. $fiterUsingWorkspace = false; } } $wsCondition = $condField->getCondition(); if ($fiterUsingWorkspace && $ws_value != 0) { $parentWS = Projects::findById($ws_value); if ($parentWS instanceof Project) { $subWorkspaces = $parentWS->getSubWorkspaces(); foreach ($subWorkspaces as $subWS) { $ws_value .= ',' . $subWS->getId(); } } $allConditions .= ' AND t.id ' . ($wsCondition == '=' ? 'IN' : 'NOT IN') . ' (SELECT object_id FROM ' . TABLE_PREFIX . 'workspace_objects WHERE object_manager = \'' . $manager . '\' AND workspace_id IN ( ' . $ws_value . '))'; } } if ($condField->getFieldName() == 'tag') { //if is a tag condition: $fiterUsingTag = true; if ($condField->getIsParametrizable() && isset($params['tag'])) { //if is parameter condition and is set the parameter $tags_csv = $params['tag']; $tags = explode(',', $tags_csv); } else { //if is a fixed tag value and is set $tval = $condField->getValue(); if (isset($tval)) { $tags = explode(',', $tval); } else { //if there is no tag to filter with it doesnt filter at all. $fiterUsingTag = false; } } $tagCondition = $condField->getCondition(); if ($fiterUsingTag && is_array($tags)) { foreach ($tags as $tag_value) { $tag_value = trim($tag_value); if ($tag_value == '') { continue; } $allConditions .= ' AND t.id ' . ($tagCondition == '=' ? 'IN' : 'NOT IN') . ' (SELECT rel_object_id FROM ' . TABLE_PREFIX . 'tags WHERE rel_object_manager = \'' . $manager . '\' AND tag = \'' . $tag_value . '\')'; } } } } else { $skip_condition = false; $model = $report->getObjectType(); $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() . ' ' . mysql_real_escape_string($value); } else { if ($condField->getCondition() == '=' || $condField->getCondition() == '<=' || $condField->getCondition() == '>=') { $equal = 'datediff(\'' . mysql_real_escape_string($value) . '\', `' . $condField->getFieldName() . '`)=0'; switch ($condField->getCondition()) { case '=': $allConditions .= $equal; break; case '<=': case '>=': $allConditions .= '(`' . $condField->getFieldName() . '` ' . $condField->getCondition() . ' \'' . mysql_real_escape_string($value) . '\'' . ' OR ' . $equal . ') '; break; } } else { $allConditions .= '`' . $condField->getFieldName() . '` ' . $condField->getCondition() . ' \'' . mysql_real_escape_string($value) . '\''; } } } else { $allConditions .= '`' . $condField->getFieldName() . '` like "%' . mysql_real_escape_string($value) . '"'; } } else { $allConditions .= ' true'; } } //else } //foreach } if (count($conditionsCp) > 0) { foreach ($conditionsCp as $condCp) { $cp = CustomProperties::getCustomProperty($condCp->getCustomPropertyId()); $skip_condition = false; $dateFormat = 'm/d/Y'; if (isset($params[$condCp->getId() . "_" . $cp->getName()])) { $value = $params[$condCp->getId() . "_" . $cp->getName()]; if ($cp->getType() == 'date') { $dateFormat = user_config_option('date_format'); } } else { $value = $condCp->getValue(); } if ($value == '' && $condCp->getIsParametrizable()) { $skip_condition = true; } if (!$skip_condition) { $allConditions .= ' AND '; $allConditions .= 't.id IN ( SELECT object_id as id FROM ' . TABLE_PREFIX . 'custom_property_values cpv WHERE '; $allConditions .= ' 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') { $dtValue = DateTimeValueLib::dateFromFormatAndString($dateFormat, $value); $value = $dtValue->format('Y-m-d H:i:s'); } if ($condCp->getCondition() != '%') { if ($cp->getType() == 'numeric') { $allConditions .= ' AND cpv.value ' . $condCp->getCondition() . ' ' . mysql_real_escape_string($value); } else { $allConditions .= ' AND cpv.value ' . $condCp->getCondition() . ' "' . mysql_real_escape_string($value) . '"'; } } else { $allConditions .= ' AND cpv.value like "%' . mysql_real_escape_string($value) . '"'; } $allConditions .= ')'; } } } if ($manager != 'Projects' && $manager != 'Users') { $allConditions .= ' AND t.trashed_by_id = 0 '; } $sql .= $allConditions; $rows = DB::executeAll($sql); if (is_null($rows)) { $rows = array(); } $totalResults = count($rows); $results['pagination'] = Reports::getReportPagination($id, $params, $order_by_col, $order_by_asc, $offset, $limit, $totalResults); $selectCols = 'distinct(t.id) as "id"'; $titleCols = $managerInstance->getReportObjectTitleColumns(); $titleColAlias = array(); foreach ($titleCols as $num => $title) { $selectCols .= ', t.' . $title . ' as "titleCol' . $num . '"'; $titleColAlias['titleCol' . $num] = $title; } $selectFROM = TABLE_PREFIX . $table . ' t '; $selectWHERE = "WHERE {$allConditions}"; $order = $order_by_col != '' ? $order_by_col : $report->getOrderBy(); $order_asc = $order_by_col != '' ? $order_by_asc : $report->getIsOrderByAsc(); $allColumns = ReportColumns::getAllReportColumns($id); $print_ws_idx = -1; $print_tags_idx = -1; if (is_array($allColumns) && count($allColumns) > 0) { $first = true; $openPar = ''; $index = 0; foreach ($allColumns as $column) { if ($column->getCustomPropertyId() == 0) { $field = $column->getFieldName(); if ($managerInstance->columnExists($field)) { $selectCols .= ', t.' . $field; $results['columns'][] = lang('field ' . $report->getObjectType() . ' ' . $field); $results['db_columns'][lang('field ' . $report->getObjectType() . ' ' . $field)] = $field; $first = false; } else { if ($field === 'workspace') { $print_ws_idx = $index; } else { if ($field === 'tag') { $print_tags_idx = $index; } } } } else { $colCp = $column->getCustomPropertyId(); $cp = CustomProperties::getCustomProperty($colCp); if ($cp instanceof CustomProperty) { $selectCols .= $cp->getIsMultipleValues() ? ', GROUP_CONCAT(DISTINCT cpv' . $colCp . '.value SEPARATOR ", ") as "' . $cp->getName() . '"' : ', cpv' . $colCp . '.value as "' . $cp->getName() . '"'; $results['columns'][] = $cp->getName(); $results['db_columns'][$cp->getName()] = $colCp; $openPar .= '('; $selectFROM .= ' LEFT OUTER JOIN ' . TABLE_PREFIX . 'custom_property_values cpv' . $colCp . ' ON (t.id = cpv' . $colCp . '.object_id AND cpv' . $colCp . '.custom_property_id = ' . $colCp . '))'; $first = false; if ($order == $colCp) { if ($cp->getType() == 'date') { $order_by = 'ORDER BY STR_TO_DATE(cpv' . $colCp . '.value, "%Y-%m-%d %H:%i:%s") ' . ($order_asc ? 'asc' : 'desc'); } else { $order_by = 'ORDER BY cpv' . $colCp . '.value ' . ($order_asc ? 'asc' : 'desc'); } } } } $index++; } } if ($order_by == '') { if (is_numeric($order)) { $id = $order; $openPar .= '('; $selectFROM .= ' LEFT OUTER JOIN ' . TABLE_PREFIX . 'custom_property_values cpv' . $id . ' ON (t.id = cpv' . $id . '.object_id AND cpv' . $id . '.custom_property_id = ' . $id . '))'; $order_by = 'ORDER BY ' . $order; } else { if ($object->getColumnType($order) == 'date') { $order_by = 'ORDER BY STR_TO_DATE(t.' . $order . ', "%Y-%m-%d %H:%i:%s") ' . ($order_asc ? 'asc' : 'desc'); } else { $order_by = 'ORDER BY t.' . $order . ' ' . ($order_asc ? 'asc' : 'desc'); } } } if ($to_print) { $limit_str = ''; } else { $limit_str = ' LIMIT ' . $offset . ',' . $limit; } $sql = 'SELECT ' . $selectCols . ' FROM (' . $openPar . $selectFROM . ') ' . $selectWHERE . ' GROUP BY id ' . $order_by . $limit_str; $rows = DB::executeAll($sql); if (is_null($rows)) { $rows = array(); } $rows = Reports::removeDuplicateRows($rows); $reportObjTitleCols = array(); foreach ($rows as &$row) { foreach ($row as $col => $value) { if (isset($titleColAlias[$col])) { $reportObjTitleCols[$titleColAlias[$col]] = $value; } } $title = $managerInstance->getReportObjectTitle($reportObjTitleCols); $iconame = strtolower($managerInstance->getItemClass()); $id = $row['id']; unset($row['id']); $row = array_slice($row, count($titleCols)); if (!$to_print) { $row = array('link' => '<a class="link-ico ico-' . $iconame . '" title="' . clean($title) . '" target="new" href="' . get_url($controller, $view, array('id' => $id)) . '"> </a>') + $row; } foreach ($row as $col => &$value) { if (in_array($col, $managerInstance->getExternalColumns())) { $value = self::getExternalColumnValue($col, $value); } else { if ($col != 'link') { $value = html_to_text(clean($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>'; } } } if ($print_tags_idx > -1) { $row['tag'] = implode(", ", Tags::getTagNamesByObjectIds($id, $report->getObjectType())); } if ($print_ws_idx > -1) { $row['workspace'] = ""; $workspaces = WorkspaceObjects::getWorkspacesByObject($report->getObjectType(), $id, logged_user()->getWorkspacesQuery()); foreach ($workspaces as $workspace) { $row['workspace'] .= ($row['workspace'] == "" ? "" : ", ") . $workspace->getName(); } } // TODO: reorder columns $row = str_replace('|', ',', $row); } // TODO: reorder column titles if ($print_tags_idx > -1) { $results['columns'][] = lang('tags'); } if ($print_ws_idx > -1) { $results['columns'][] = lang('workspaces'); } if (!$to_print) { if (is_array($results['columns'])) { array_unshift($results['columns'], ''); } else { $results['columns'] = array(''); } } $results['rows'] = $rows; } return $results; }
function get_member_custom_property_value_for_listing($cp, $member_id, $cp_vals = null) { if (is_null($cp_vals)) { $cp_vals = MemberCustomPropertyValues::getMemberCustomPropertyValues($member_id, $cp->getId()); } $val_to_show = ""; foreach ($cp_vals as $cp_val) { if (in_array($cp->getType(), array('contact', 'user')) && $cp_val instanceof MemberCustomPropertyValue) { $cp_contact = Contacts::findById($cp_val->getValue()); if ($cp_contact instanceof Contact) { $cp_val->setValue($cp_contact->getObjectName()); } else { $cp_val->setValue(""); } } if ($cp->getType() == 'date' && $cp_val instanceof MemberCustomPropertyValue) { $format = user_config_option('date_format'); Hook::fire("custom_property_date_format", null, $format); $tmp_date = DateTimeValueLib::dateFromFormatAndString(DATE_MYSQL, $cp_val->getValue()); if (str_starts_with($cp_val->getValue(), EMPTY_DATE)) { $formatted = ""; } else { if (str_ends_with($cp_val->getValue(), "00:00:00")) { $formatted = $tmp_date->format(user_config_option('date_format')); } else { $formatted = $tmp_date->format($format); } } $cp_val->setValue($formatted); } if ($cp->getType() == 'address' && $cp_val instanceof MemberCustomPropertyValue) { $values = str_replace("\\|", "%%_PIPE_%%", $cp_val->getValue()); $exploded = explode("|", $values); foreach ($exploded as &$v) { $v = str_replace("%%_PIPE_%%", "|", $v); $v = str_replace("'", "\\'", $v); } if (count($exploded) > 0) { $address_type = array_var($exploded, 0, ''); $street = array_var($exploded, 1, ''); $city = array_var($exploded, 2, ''); $state = array_var($exploded, 3, ''); $country = array_var($exploded, 4, ''); $zip_code = array_var($exploded, 5, ''); $country_name = CountryCodes::getCountryNameByCode($country); $tmp = array(); if ($street != '') { $tmp[] = $street; } if ($city != '') { $tmp[] = $city; } if ($state != '') { $tmp[] = $state; } if ($zip_code != '') { $tmp[] = $zip_code; } if ($country_name != '') { $tmp[] = $country_name; } $cp_val->setValue(implode(' - ', $tmp)); } } $val_to_show .= ($val_to_show == "" ? "" : ", ") . ($cp_val instanceof MemberCustomPropertyValue ? $cp_val->getValue() : ""); } $val_to_show = html_to_text($val_to_show); return $val_to_show; }
/** * 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 != '') { $date_format = user_config_option('date_format'); return DateTimeValueLib::dateFromFormatAndString($date_format, $value); } return $default; }
/** * 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'); $customProps = CustomProperties::getAllCustomPropertiesByObjectType($object->getObjectTypeId()); //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 (is_array($obj_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) { $dtv = DateTimeValueLib::dateFromFormatAndString(user_config_option('date_format'), $val); $newValues[] = $dtv->format("Y-m-d H:i:s"); } $value = $newValues; } else { $dtv = DateTimeValueLib::dateFromFormatAndString(user_config_option('date_format'), $value); $value = $dtv->format("Y-m-d H:i:s"); } } //Save multiple values if (is_array($value)) { 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 != '') { if (strpos($val, ',')) { $val = str_replace(',', '|', $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 = $custom_property->getName(); $searchable_object = SearchableObjects::findOne(array("conditions" => "`rel_object_id` = " . $object->getId() . " AND `column_name` = '{$name}'")); if (!$searchable_object) { $searchable_object = new SearchableObject(); } if (is_array($value)) { $value = implode(', ', $value); } $searchable_object->setRelObjectId($object->getId()); $searchable_object->setColumnName($name); $searchable_object->setContent($value); $searchable_object->save(); } } } } }
private function get_tasks_request_conditions() { // get query parameters, save user preferences if necessary $status = array_var($_REQUEST, 'status', null); if (is_null($status) || $status == '') { $status = user_config_option('task panel status', 2); } else { if (user_config_option('task panel status') != $status) { set_user_config_option('task panel status', $status, logged_user()->getId()); } } $previous_filter = user_config_option('task panel filter', 'no_filter'); $filter_from_date = getDateValue(array_var($_REQUEST, 'from_date')); if ($filter_from_date instanceof DateTimeValue) { $copFromDate = $filter_from_date; $filter_from_date = $filter_from_date->toMySQL(); } $tasks_from_date = ''; $filter_to_date = getDateValue(array_var($_REQUEST, 'to_date')); if ($filter_to_date instanceof DateTimeValue) { $copToDate = $filter_to_date; $filter_to_date = $filter_to_date->toMySQL(); } $tasks_to_date = ''; if (user_config_option('tasksDateStart') != $filter_from_date) { if ($filter_from_date != '0000-00-00 00:00:00' || array_var($_REQUEST, 'resetDateStart')) { set_user_config_option('tasksDateStart', $copFromDate, logged_user()->getId()); } else { $filter_from_date = user_config_option('tasksDateStart'); } } if (user_config_option('tasksDateEnd') != $filter_to_date) { if ($filter_to_date != '0000-00-00 00:00:00' || array_var($_REQUEST, 'resetDateEnd')) { set_user_config_option('tasksDateEnd', $copToDate, logged_user()->getId()); } else { $filter_to_date = user_config_option('tasksDateEnd'); } } if ($filter_from_date != '0000-00-00 00:00:00' || $filter_to_date != '0000-00-00 00:00:00') { if ($filter_from_date != '0000-00-00 00:00:00') { $dateFrom = DateTimeValueLib::dateFromFormatAndString(DATE_MYSQL, $filter_from_date); $dateFrom->advance(logged_user()->getTimezone() * -3600); $dateFrom = $dateFrom->toMySQL(); } if ($filter_to_date != '0000-00-00 00:00:00') { $dateTo = DateTimeValueLib::dateFromFormatAndString(DATE_MYSQL, $filter_to_date); $dateTo->setHour(23); $dateTo->setMinute(59); $dateTo->setSecond(59); $dateTo->advance(logged_user()->getTimezone() * -3600); $dateTo = $dateTo->toMySQL(); } if ($filter_from_date != '0000-00-00 00:00:00' && $filter_to_date != '0000-00-00 00:00:00') { $tasks_from_date = " AND (((`start_date` BETWEEN '" . $dateFrom . "' AND '" . $dateTo . "') AND `start_date` != " . DB::escape(EMPTY_DATETIME) . ") OR ((`due_date` BETWEEN '" . $dateFrom . "' AND '" . $dateTo . "') AND `due_date` != " . DB::escape(EMPTY_DATETIME) . "))"; } elseif ($filter_from_date != '0000-00-00 00:00:00') { $tasks_from_date = " AND (`start_date` > '" . $dateFrom . "' OR `due_date` > '" . $dateFrom . "') "; } else { $tasks_from_date = "AND ((`start_date` < '" . $dateTo . "' AND `start_date` != " . DB::escape(EMPTY_DATETIME) . ") OR (`due_date` < '" . $dateTo . "' AND `due_date` != " . DB::escape(EMPTY_DATETIME) . "))"; } } else { $tasks_from_date = ""; } $filter = array_var($_REQUEST, 'filter'); if (is_null($filter) || $filter == '') { $filter = $previous_filter; } else { if ($previous_filter != $filter) { set_user_config_option('task panel filter', $filter, logged_user()->getId()); } } if ($filter != 'no_filter') { $filter_value = array_var($_REQUEST, 'fval'); if (is_null($filter_value) || $filter_value == '') { $filter_value = user_config_option('task panel filter value', null, logged_user()->getId()); set_user_config_option('task panel filter value', $filter_value, logged_user()->getId()); $filter = $previous_filter; set_user_config_option('task panel filter', $filter, logged_user()->getId()); } else { if (user_config_option('task panel filter value') != $filter_value) { set_user_config_option('task panel filter value', $filter_value, logged_user()->getId()); } } } /* $isJson = array_var($_GET,'isJson',false); if ($isJson) ajx_current("empty"); */ $template_condition = "`e`.`is_template` = 0 "; //Get the task query conditions $task_filter_condition = ""; switch ($filter) { case 'assigned_to': $assigned_to = $filter_value; if ($assigned_to > 0) { $task_filter_condition = " AND (`assigned_to_contact_id` = " . $assigned_to . ") "; } else { if ($assigned_to == -1) { $task_filter_condition = " AND `assigned_to_contact_id` = 0"; } } break; case 'assigned_by': if ($filter_value != 0) { $task_filter_condition = " AND `assigned_by_id` = " . $filter_value . " "; } break; case 'created_by': if ($filter_value != 0) { $task_filter_condition = " AND `created_by_id` = " . $filter_value . " "; } break; case 'completed_by': if ($filter_value != 0) { $task_filter_condition = " AND `completed_by_id` = " . $filter_value . " "; } break; case 'milestone': $task_filter_condition = " AND `milestone_id` = " . $filter_value . " "; break; case 'priority': $task_filter_condition = " AND `priority` = " . $filter_value . " "; break; case 'subtype': if ($filter_value != 0) { $task_filter_condition = " AND `object_subtype` = " . $filter_value . " "; } break; case 'subscribed_to': if ($filter_value > 0) { $res20 = DB::execute("SELECT object_id FROM " . TABLE_PREFIX . "object_subscriptions WHERE `contact_id` = " . $filter_value); $subs_rows = $res20->fetchAll($res20); $subs = array(); if (count($subs_rows) > 0) { foreach ($subs_rows as $row) { $subs[] = $row['object_id']; } unset($res20, $subs_rows, $row); if (count($subs) > 0) { $task_filter_condition = " AND `e`.`completed_on` = " . DB::escape(EMPTY_DATETIME) . " AND `o`.`id` IN(" . implode(',', $subs) . ")"; } } else { $task_filter_condition = " AND `e`.`completed_on` = " . DB::escape(EMPTY_DATETIME) . " AND `o`.`id` = -1"; } } break; case 'no_filter': $task_filter_condition = ""; break; default: flash_error(lang('task filter criteria not recognised', $filter)); } $task_status_condition = ""; $now_date = DateTimeValueLib::now(); $now_date->advance(logged_user()->getTimezone() * 3600); $now = $now_date->format('Y-m-d 00:00:00'); $now_end = $now_date->format('Y-m-d 23:59:59'); switch ($status) { case 0: // Incomplete tasks $task_status_condition = " AND `e`.`completed_on` = " . DB::escape(EMPTY_DATETIME); break; case 1: // Complete tasks $task_status_condition = " AND `e`.`completed_on` > " . DB::escape(EMPTY_DATETIME); break; case 10: // Active tasks $task_status_condition = " AND (SELECT COUNT(ts.object_id) FROM " . TABLE_PREFIX . "timeslots ts WHERE ts.rel_object_id=o.id AND ts.end_time = '" . EMPTY_DATETIME . "') > 0"; break; case 11: // Overdue tasks $task_status_condition = " AND `e`.`completed_on` = " . DB::escape(EMPTY_DATETIME) . " AND `e`.`due_date` < '{$now}'"; break; case 12: // Today tasks $task_status_condition = " AND `e`.`completed_on` = " . DB::escape(EMPTY_DATETIME) . " AND `e`.`due_date` >= '{$now}' AND `e`.`due_date` <= '{$now_end}'"; break; case 13: // Today + Overdue tasks $task_status_condition = " AND `e`.`completed_on` = " . DB::escape(EMPTY_DATETIME) . " AND `e`.`due_date` <= '{$now_end}'"; break; case 20: // Actives task by current user $task_status_condition = " AND `e`.`completed_on` = " . DB::escape(EMPTY_DATETIME) . " AND `e`.`start_date` <= '{$now}' AND `e`.`assigned_to_contact_id` = " . logged_user()->getId(); break; case 21: // Subscribed tasks by current user $res20 = DB::execute("SELECT object_id FROM " . TABLE_PREFIX . "object_subscriptions WHERE `contact_id` = " . logged_user()->getId()); $subs_rows = $res20->fetchAll($res20); foreach ($subs_rows as $row) { $subs[] = $row['object_id']; } unset($res20, $subs_rows, $row); $task_status_condition = " AND `e`.`completed_on` = " . DB::escape(EMPTY_DATETIME) . " AND `o`.`id` IN(" . implode(',', $subs) . ")"; break; case 2: // All tasks break; default: throw new Exception('Task status "' . $status . '" not recognised'); } $task_assignment_conditions = ""; if (!SystemPermissions::userHasSystemPermission(logged_user(), 'can_see_assigned_to_other_tasks')) { $task_assignment_conditions = " AND assigned_to_contact_id = " . logged_user()->getId(); } $conditions = "AND {$template_condition} {$task_filter_condition} {$task_status_condition} {$task_assignment_conditions} {$tasks_from_date}"; $data = array(); $data['conditions'] = $conditions; $data['filterValue'] = isset($filter_value) ? $filter_value : ''; $data['filter'] = $filter; $data['status'] = $status; $data['limit'] = array_var($_REQUEST, 'limit', user_config_option('task_display_limit', 999)); return $data; }
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); }
function instantiate() { $id = get_id(); $template = COTemplates::findById($id); if (!$template instanceof COTemplate) { flash_error(lang("template dnx")); ajx_current("empty"); return; } $parameters = TemplateParameters::getParametersByTemplate($id); $parameterValues = array_var($_POST, 'parameterValues'); if (count($parameters) > 0 && !isset($parameterValues)) { ajx_current("back"); return; } $objects = $template->getObjects(); foreach ($objects as $object) { if (!$object instanceof ProjectDataObject) { continue; } // copy object $copy = $object->copy(); if ($copy->columnExists('is_template')) { $copy->setColumnValue('is_template', false); } if ($copy instanceof ProjectTask) { // don't copy parent task and milestone $copy->setMilestoneId(0); $copy->setParentId(0); } $copy->save(); $wsId = array_var($_POST, 'project_id', active_or_personal_project()->getId()); // if specified, set workspace $workspace = Projects::findById($wsId); if (!$workspace instanceof Project) { $workspace = active_or_personal_project(); } $copy->addToWorkspace($workspace); // add object tags and specified tags $tags = implode(',', $object->getTagNames()); $copy->setTagsFromCSV($tags . "," . array_var($_POST, 'tags')); // copy linked objects $copy->copyLinkedObjectsFrom($object); // copy subtasks if applicable if ($copy instanceof ProjectTask) { ProjectTasks::copySubTasks($object, $copy, false); $manager = new ProjectTask(); } else { if ($copy instanceof ProjectMilestone) { ProjectMilestones::copyTasks($object, $copy, false); $manager = new ProjectMilestone(); } } // copy custom properties $copy->copyCustomPropertiesFrom($object); // set property values as defined in template $objProp = TemplateObjectProperties::getPropertiesByTemplateObject($id, $object->getId()); foreach ($objProp as $property) { $propName = $property->getProperty(); $value = $property->getValue(); if ($manager->getColumnType($propName) == DATA_TYPE_STRING) { if (is_array($parameterValues)) { foreach ($parameterValues as $param => $val) { $value = str_replace('{' . $param . '}', $val, $value); } } } else { if ($manager->getColumnType($propName) == DATA_TYPE_DATE || $manager->getColumnType($propName) == DATA_TYPE_DATETIME) { $operator = '+'; if (strpos($value, '+') === false) { $operator = '-'; } $opPos = strpos($value, $operator); if ($opPos !== false) { $dateParam = substr($value, 1, strpos($value, '}') - 1); $dateUnit = substr($value, strlen($value) - 1); // d, w or m (for days, weeks or months) if ($dateUnit == 'm') { $dateUnit = 'M'; // make month unit uppercase to call DateTimeValue::add with correct parameter } $dateNum = (int) substr($value, strpos($value, $operator), strlen($value) - 2); $date = $parameterValues[$dateParam]; $date = DateTimeValueLib::dateFromFormatAndString(user_config_option('date_format'), $date); $value = $date->add($dateUnit, $dateNum); } } else { if ($manager->getColumnType($propName) == DATA_TYPE_INTEGER) { if (is_array($parameterValues)) { foreach ($parameterValues as $param => $val) { $value = str_replace('{' . $param . '}', $val, $value); } } } } } if ($value != '') { $copy->setColumnValue($propName, $value); $copy->save(); } } //copy assigned to company if applicable if ($copy->getAssignedToUserId() != 0) { $copy->setAssignedToCompanyId($copy->getAssignedTo()->getCompanyId()); $copy->save(); } // copy reminders $reminders = ObjectReminders::getByObject($object); foreach ($reminders as $reminder) { $copy_reminder = new ObjectReminder(); $copy_reminder->setContext($reminder->getContext()); $reminder_date = $copy->getColumnValue($reminder->getContext()); if ($reminder_date instanceof DateTimeValue) { $reminder_date = new DateTimeValue($reminder_date->getTimestamp()); $reminder_date->add('m', -$reminder->getMinutesBefore()); } $copy_reminder->setDate($reminder_date); $copy_reminder->setMinutesBefore($reminder->getMinutesBefore()); $copy_reminder->setObject($copy); $copy_reminder->setType($reminder->getType()); $copy_reminder->setUserId($reminder->getUserId()); $copy_reminder->save(); } } if (is_array($parameters) && count($parameters) > 0) { ajx_current("back"); } else { ajx_current("reload"); } }
function import_google_calendar_for_user($user) { if ($user instanceof ExternalCalendarUser) { $calendars = ExternalCalendars::findByExtCalUserId($user->getId()); $service = $this->connect_with_google_calendar($user); $contact = Contacts::findById($user->getContactId()); try { //update or insert events for calendars foreach ($calendars as $calendar) { if ($calendar->getSync() == 0) { continue; } $optParams = array(); $syncToken = $calendar->getExternalCalendarPropertyValue("syncToken"); //if syncToken is not present we have to make a full sync if ($syncToken) { //incremental sync get events created or updated from las check $optParams['syncToken'] = $syncToken; } else { //full sync get events starting from past 2 weeks $previous_week = strtotime("-2 week"); $time_min = date(DATE_RFC3339, $previous_week); $optParams['timeMin'] = $time_min; } //Try to get events for this calendar try { $events = $service->events->listEvents($calendar->getOriginalCalendarId(), $optParams); } catch (Exception $e) { Logger::log("Fail to get events from external calendar: " . $calendar->getId()); Logger::log($e->getMessage()); //remove the syncToken for this calendar so the next time we do a full sync $syncTokenProp = $calendar->getExternalCalendarProperty("syncToken"); if ($syncTokenProp) { $syncTokenProp->delete(); } //go to the next calendar continue; } //Working with events while (true) { foreach ($events->getItems() as $event) { //check if is a cancelled event if ($event->getStatus() == "cancelled") { $cancelled_event = ProjectEvents::findBySpecialId($event->getId(), $calendar->getId()); //delete ProjectEvent if ($cancelled_event instanceof ProjectEvent) { $cancelled_event->delete(); } continue; } //check if is a recurrent event if (is_array($event->getRecurrence())) { continue; } //check if is a recurrent event instance if (!is_null($event->getRecurringEventId()) && $event->getRecurringEventId() != '') { continue; } //get all the data that we need from google event $event_id = $event->getId(); $event_name = $event->getSummary(); $event_desc = $event->getDescription(); $event_start_date = ExternalCalendarController::date_google_to_sql($event->getStart()); $event_end_date = ExternalCalendarController::date_google_to_sql($event->getEnd()); $event_type = 1; if ($event->getStart()->getDate()) { $event_type = 2; //set this times because we have a bug with all day events times $event_start_date = DateTimeValueLib::dateFromFormatAndString(DATE_MYSQL, $event_start_date); $event_start_date->advance(12 * 3600); $event_start_date = $event_start_date->toMySQL(); $event_end_date = DateTimeValueLib::dateFromFormatAndString(DATE_MYSQL, $event_start_date); $event_end_date->advance(1 * 3600); $event_end_date = $event_end_date->toMySQL(); } $event_updated_date = EMPTY_DATETIME; if (!is_null($event->getUpdated()) && $event->getUpdated() != '') { $event_updated_date_str = strtotime($event->getUpdated()); $event_updated_date = date(DATE_MYSQL, $event_updated_date_str); } //Save event try { DB::beginWork(); //if event exist update it $new_event = ProjectEvents::findBySpecialId($event_id, $calendar->getId()); if (!$new_event instanceof ProjectEvent) { //Create ProjectEvent from google event $new_event = new ProjectEvent(); } $new_event->setSpecialID($event_id); $new_event->setStart($event_start_date); $new_event->setDuration($event_end_date); $new_event->setTypeId($event_type); $new_event->setObjectName($event_name); $new_event->setDescription($event_desc); $new_event->setUpdateSync($event_updated_date); $new_event->setExtCalId($calendar->getId()); $new_event->save(); //Invitation insert only if not exists $conditions = array('event_id' => $new_event->getId(), 'contact_id' => $user->getContactId()); if (EventInvitations::findById($conditions) == null) { $invitation = new EventInvitation(); $invitation->setEventId($new_event->getId()); $invitation->setContactId($user->getContactId()); $invitation->setInvitationState(1); $invitation->setUpdateSync(); $invitation->setSpecialId($event_id); $invitation->save(); } //Subscription insert only if not exists if (ObjectSubscriptions::findBySubscriptions($new_event->getId(), $contact) == null) { $subscription = new ObjectSubscription(); $subscription->setObjectId($new_event->getId()); $subscription->setContactId($user->getContactId()); $subscription->save(); } $member = array(); if ($calendar->getRelatedTo()) { $member_ids = explode(",", $calendar->getRelatedTo()); foreach ($member_ids as $member_id) { $member[] = $member_id; } } $object_controller = new ObjectController(); $object_controller->add_to_members($new_event, $member, $contact); DB::commit(); } catch (Exception $e) { DB::rollback(); Logger::log("Fail to save event for external calendar user: "******"syncToken", $nextSyncToken); } break; } } } //foreach calendars } catch (Exception $e) { Logger::log("Fail to get events for external calendar user: " . $user->getId()); Logger::log($e->getMessage()); } } }
<table> <tr style='height:30px;'> <td><span class="bold"><?php echo lang("date"); ?> : </span></td> <td align='left'><?php echo select_box('report[date_type]', array(option_tag(lang('today'), 1, array_var($report_data, "date_type") == 1 ? array('selected' => 'selected') : null), option_tag(lang('this week'), 2, array_var($report_data, "date_type") == 2 ? array('selected' => 'selected') : null), option_tag(lang('last week'), 3, array_var($report_data, "date_type") == 3 ? array('selected' => 'selected') : null), option_tag(lang('this month'), 4, array_var($report_data, "date_type") == 4 ? array('selected' => 'selected') : null), option_tag(lang('last month'), 5, array_var($report_data, "date_type") == 5 ? array('selected' => 'selected') : null), option_tag(lang('select dates...'), 6, array_var($report_data, "date_type") == 6 ? array('selected' => 'selected') : null)), array('onchange' => 'og.dateselectchange(this)')); ?> </td> </tr> <?php if (array_var($report_data, "date_type") == 6) { $style = ""; $st = DateTimeValueLib::dateFromFormatAndString(DATE_MYSQL, array_var($report_data, 'start_value')); $et = DateTimeValueLib::dateFromFormatAndString(DATE_MYSQL, array_var($report_data, 'end_value')); } else { $style = 'display:none;'; $st = DateTimeValueLib::now(); $et = $st; } ?> <tr class="dateTr" style="<?php echo $style; ?> "> <td><span class="bold"><?php echo lang("start date"); ?> : </span></td> <td align='left'><?php
/** * 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); } } } }
/** * Execute search * TODO: Performance gus: * Fetch only ids and execute a select statement by pk (fer each result) * @param void * @return null */ function search() { // Init vars $search_for = array_var($_GET, 'search_for'); $search_dimension = array_var($_GET, 'search_dimension'); $advanced = array_var($_GET, 'advanced'); $minWordLength = $this->minWordLength($search_for); $useLike = $minWordLength && $this->ignoreMinWordLength && $minWordLength < self::$MYSQL_MIN_WORD_LENGHT; $search_pieces = explode(" ", $search_for); $search_string = ""; if (!$useLike) { // Prepare MATCH AGAINST string foreach ($search_pieces as $word) { if ((strpos($word, "@") || strpos($word, ".") || strpos($word, ",")) === false) { // STRING Dont containt special characheters that mysql use as separator. Noramal flow if ($this->wildCardSearch) { $word .= "*"; } } else { $word = str_replace($this->mysqlWordSeparator, " +", $word); } if (!str_starts_with($word, " ")) { $word = " +" . $word; } $search_string .= mysql_escape_string($word) . " "; } $search_string = substr($search_string, 0, -1); } else { // USE Like Query $search_string = mysql_escape_string($search_for); } $this->search_for = $search_for; $limit = $this->limit; $start = array_var($_REQUEST, 'start', $this->start); $this->start = $start; $limitTest = max($this->limitTest, $this->limit); $filteredResults = 0; $uid = logged_user()->getId(); if (!isset($search_dimension)) { $members = active_context_members(false); } else { if ($search_dimension == 0) { $members = array(); } else { $members = array($search_dimension); } } $members_sql = ""; if (count($members) > 0) { $members_sql = "AND rel_object_id IN (SELECT object_id FROM " . TABLE_PREFIX . "object_members om WHERE member_id IN (" . implode(',', $members) . ") \n GROUP BY object_id\n HAVING count(member_id) = " . count($members) . ")"; $this->search_dimension = implode(',', $members); } else { $this->search_dimension = 0; } $revisionObjectTypeId = ObjectTypes::findByName("file revision")->getId(); $listableObjectTypeIds = implode(",", ObjectTypes::getListableObjectTypeIds()); if ($_POST) { $conditions = array_var($_POST, 'conditions'); $search = array_var($_POST, 'search'); $type_object = array_var($search, 'search_object_type_id'); if (!is_array($conditions)) { $conditions = array(); } $where_condiition = ''; $conditions_view = array(); $cont = 0; foreach ($conditions as $condition) { $condValue = array_key_exists('value', $condition) ? $condition['value'] : ''; if ($condition['field_type'] == 'boolean') { $value = array_key_exists('value', $condition); } else { if ($condition['field_type'] == 'date') { if ($condValue != '') { $dtFromWidget = DateTimeValueLib::dateFromFormatAndString(user_config_option('date_format'), $condValue); $value = date("m/d/Y", $dtFromWidget->getTimestamp()); } } else { $value = $condValue; } } if ($condition['condition'] == "like") { $where_condiition .= " AND " . $condition['field_name'] . " " . $condition['condition'] . " '" . $value . "%' "; } else { $where_condiition .= " AND " . $condition['field_name'] . " " . $condition['condition'] . " '" . $value . "' "; } $conditions_view[$cont]['id'] = $condition['id']; $conditions_view[$cont]['custom_property_id'] = $condition['custom_property_id']; $conditions_view[$cont]['field_name'] = $condition['field_name']; $conditions_view[$cont]['condition'] = $condition['condition']; $conditions_view[$cont]['value'] = $value; $cont++; } tpl_assign('conditions', $conditions_view); if ($type_object) { $object_table = ObjectTypes::findById($type_object); $table = $object_table->getTableName(); } $sql = "\t\n\t\t\tSELECT distinct(so.rel_object_id) AS id\n\t\t\tFROM " . TABLE_PREFIX . "searchable_objects so\n INNER JOIN " . TABLE_PREFIX . $table . " nto ON nto.object_id = so.rel_object_id \n\t\t\tINNER JOIN " . TABLE_PREFIX . "objects o ON o.id = so.rel_object_id \n\t\t\tWHERE (\n\t\t\t\t(\n\t\t\t\t\tso.rel_object_id IN (\n\t\t\t \t\tSELECT object_id FROM " . TABLE_PREFIX . "sharing_table WHERE group_id IN (\n\t\t\t \t\t\tSELECT permission_group_id FROM " . TABLE_PREFIX . "contact_permission_groups WHERE contact_id = {$uid}\n\t\t\t \t\t)\n\t\t\t \t\t)\n\t\t\t \t)\n\t\t\t) " . $where_condiition . $members_sql . " ORDER by o.updated_on DESC\n\t\t\tLIMIT {$start}, {$limitTest} "; } else { $type_object = ''; $sql = "\t\n\t\t\tSELECT distinct(so.rel_object_id) AS id\n\t\t\tFROM " . TABLE_PREFIX . "searchable_objects so\n\t\t\tINNER JOIN " . TABLE_PREFIX . "objects o ON o.id = so.rel_object_id \n\t\t\tWHERE (\n\t\t\t\t(\t\n\t\t\t\t\to.object_type_id = {$revisionObjectTypeId} AND \n\t\t\t\t\tEXISTS ( \n\t\t\t\t\t\tSELECT id FROM " . TABLE_PREFIX . "sharing_table WHERE object_id = ( SELECT file_id FROM " . TABLE_PREFIX . "project_file_revisions WHERE object_id = o.id ) \n\t\t\t\t\t\tAND group_id IN (SELECT permission_group_id FROM " . TABLE_PREFIX . "contact_permission_groups WHERE contact_id = {$uid} )\n\t\t\t\t\t)\n\t\t\t\t\t\n\t\t\t\t) \n\t\t\t\tOR (\n\t\t\t\t\tso.rel_object_id IN (\n\t\t\t \t\tSELECT object_id FROM " . TABLE_PREFIX . "sharing_table WHERE group_id IN (\n\t\t\t \t\t\tSELECT permission_group_id FROM " . TABLE_PREFIX . "contact_permission_groups WHERE contact_id = {$uid}\n\t\t\t \t\t)\n\t\t\t \t\t)\n\t\t\t \t)\n\t\t\t)" . ($useLike ? "AND\tso.content LIKE '%{$search_string}%' " : "AND MATCH (so.content) AGAINST ('{$search_string}' IN BOOLEAN MODE) ") . " \n\t\t\tAND o.object_type_id IN ({$listableObjectTypeIds}) \n " . $members_sql . "\n\t\t\tORDER by o.updated_on DESC\n\t\t\tLIMIT {$start}, {$limitTest} "; } tpl_assign('type_object', $type_object); $db_search_results = array(); $search_results_ids = array(); $timeBegin = time(); $res = DB::execute($sql); $timeEnd = time(); if ($this->debug) { alert_r("<br>SQL:<br>" . $sql . "<hr>TIME:" . ($timeEnd - $timeBegin)); } while ($row = $res->fetchRow()) { $search_results_ids[] = $row['id']; } // Prepare results for view to avoid processing at presentation layer $search_results = $this->prepareResults($search_results_ids, $null, $limit); // Calculate or approximate total for pagination $total = count($search_results_ids) + $start; if (count($search_results_ids) < $limitTest) { $total = count($search_results_ids) + $start; } else { $total = "Many"; } //$total -= $filteredResults ; $this->total = $total; // Pagination $this->buildPagination($search_results); // Extra data $extra = new stdClass(); if ($this->showQueryTime) { $extra->time = $timeEnd - $timeBegin; } //$extra->filteredResults = $filteredResults ; // Template asigns tpl_assign('pagination', $this->pagination); tpl_assign('search_string', $search_for); tpl_assign('search_dimension', $this->search_dimension); tpl_assign('search_results', $search_results); tpl_assign('advanced', $advanced); tpl_assign('extra', $extra); $types = array(array("", lang("select one"))); $object_types = ObjectTypes::getAvailableObjectTypes(); foreach ($object_types as $ot) { $types[] = array($ot->getId(), lang($ot->getName())); } // if ($selected_type != '') // tpl_assign('allowed_columns', $this->get_allowed_columns($selected_type)); tpl_assign('object_types', $types); // //Ajax if (!$total && !$advanced) { if ($_POST && count($search_results < 0)) { tpl_assign('msg_advanced', true); } else { $this->setTemplate('no_results'); } } ajx_set_no_toolbar(true); }
/** * Returns timeslots based on the set query parameters * * @param User $user * @param string $workspacesCSV * @param DateTimeValue $start_date * @param DateTimeValue $end_date * @param string $object_manager * @param string $object_id * @param array $group_by * @param array $order_by * @return array */ static function getTaskTimeslots($workspace = null, $user = null, $workspacesCSV = null, $start_date = null, $end_date = null, $object_id = 0, $group_by = null, $order_by = null, $limit = 0, $offset = 0, $timeslot_type = 0, $custom_conditions = null, $object_subtype = null) { $wslevels = 0; foreach ($group_by as $gb) { if ($gb == "project_id") { $wslevels++; } } $wsDepth = 0; if ($workspace instanceof Project) { $wsDepth = $workspace->getDepth(); } $wslevels = min(array($wslevels, 10 - $wsDepth)); if ($wslevels < 0) { $wslevels = 0; } $select = "SELECT `ts`.*"; for ($i = 0; $i < $wslevels; $i++) { $select .= ", `ws" . $i . "`.`name` AS `wsName" . $i . "`, `ws" . $i . "`.`id` AS `wsId" . $i . "`"; } $preFrom = " FROM "; for ($i = 0; $i < $wslevels; $i++) { $preFrom .= "("; } $postFrom = ""; for ($i = 0; $i < $wslevels; $i++) { $postFrom .= ") LEFT OUTER JOIN `" . TABLE_PREFIX . "projects` AS `ws" . $i . "` ON `pr`.`p" . ($wsDepth + $i + 1) . "` = `ws" . $i . "`.`id`"; } $commonConditions = ""; if ($start_date) { $commonConditions .= DB::prepareString(' AND `ts`.`start_time` >= ? ', array($start_date)); } if ($end_date) { $commonConditions .= DB::prepareString(' AND (`ts`.`paused_on` <> 0 OR `ts`.`end_time` <> 0) AND `ts`.`end_time` < ? ', array($end_date)); } //$commonConditions .= DB::prepareString(' AND (`ts`.`paused_on` <> 0 OR `ts`.`end_time` <> 0) AND `ts`.`end_time` > 0 AND `ts`.`end_time` < ? ', array($end_date)); -- another fix reported by a user, but we have to test it yet //User condition $commonConditions .= $user ? ' AND `ts`.`user_id` = ' . $user->getId() : ''; //Object condition $commonConditions .= $object_id > 0 ? ' AND `ts`.`object_manager` = "ProjectTasks" AND `ts`.`object_id` = ' . $object_id : ''; //Only applies to tasks $sql = ''; //Custom properties conditions $custom_cond = ''; $custom = false; if (count($custom_conditions) > 0) { $custom = true; foreach ($custom_conditions as $condCp) { //array_var($condCp, 'custom_property_id'); $cp = CustomProperties::getCustomProperty(array_var($condCp, 'custom_property_id')); //$skip_condition = false; $dateFormat = 'm/d/Y'; if (isset($params[array_var($condCp, 'id') . "_" . $cp->getName()])) { $value = $params[array_var($condCp, 'id') . "_" . $cp->getName()]; if ($cp->getType() == 'date') { $dateFormat = user_config_option('date_format'); } } else { $value = array_var($condCp, 'value'); } $custom_cond .= ' AND `pt`.id IN ( SELECT object_id as id FROM ' . TABLE_PREFIX . 'custom_property_values cpv WHERE '; $custom_cond .= ' cpv.custom_property_id = ' . array_var($condCp, 'custom_property_id'); if (array_var($condCp, 'condition') == 'like' || array_var($condCp, 'condition') == 'not like') { $value = '%' . $value . '%'; } if ($cp->getType() == 'date') { $dtValue = DateTimeValueLib::dateFromFormatAndString($dateFormat, $value); $value = $dtValue->format('Y-m-d H:i:s'); } if (array_var($condCp, 'condition') != '%') { if ($cp->getType() == 'numeric') { $custom_cond .= ' AND cpv.value ' . array_var($condCp, 'condition') . ' ' . mysql_real_escape_string($value); } else { $custom_cond .= ' AND cpv.value ' . array_var($condCp, 'condition') . ' "' . mysql_real_escape_string($value) . '"'; } } else { $custom_cond .= ' AND cpv.value like "%' . mysql_real_escape_string($value) . '"'; } $custom_cond .= ')'; } } switch ($timeslot_type) { case 0: //Task timeslots $from = "`" . TABLE_PREFIX . "timeslots` AS `ts`, `" . TABLE_PREFIX . "project_tasks` AS `pt`, `" . TABLE_PREFIX . "projects` AS `pr`, `" . TABLE_PREFIX . "workspace_objects` AS `wo`"; $conditions = " WHERE `ts`.`object_manager` = 'ProjectTasks' AND `pt`.`id` = `ts`.`object_id` AND `pt`.`trashed_on` = " . DB::escape(EMPTY_DATETIME) . " AND `pt`.`archived_by_id` = 0 AND `wo`.`object_manager` = 'ProjectTasks' AND `wo`.`object_id` = `ts`.`object_id` AND `wo`.`workspace_id` = `pr`.`id`"; //Project condition $conditions .= $workspacesCSV ? ' AND `pr`.`id` IN (' . $workspacesCSV . ')' : ''; if ($custom) { $commonConditions .= $custom_cond; } if ($object_subtype) { $conditions .= " AND `pt`.`object_subtype`={$object_subtype}"; } $sql = $select . $preFrom . $from . $postFrom . $conditions . $commonConditions; break; case 1: //Time timeslots $from = "`" . TABLE_PREFIX . "timeslots` AS `ts`, `" . TABLE_PREFIX . "projects` AS `pr`"; $conditions = " WHERE `ts`.`object_manager` = 'Projects'"; $conditions .= $workspacesCSV ? ' AND `ts`.`object_id` IN (' . $workspacesCSV . ") AND `ts`.`object_id` = `pr`.`id`" : " AND `ts`.`object_id` = `pr`.`id`"; $sql = $select . $preFrom . $from . $postFrom . $conditions . $commonConditions; break; case 2: //All timeslots $from1 = "`" . TABLE_PREFIX . "timeslots` AS `ts`, `" . TABLE_PREFIX . "project_tasks` AS `pt`, `" . TABLE_PREFIX . "projects` AS `pr`, `" . TABLE_PREFIX . "workspace_objects` AS `wo`"; $from2 = "`" . TABLE_PREFIX . "timeslots` AS `ts`, `" . TABLE_PREFIX . "projects` AS `pr`"; $conditions1 = " WHERE `ts`.`object_manager` = 'ProjectTasks' AND `pt`.`id` = `ts`.`object_id` AND `pt`.`trashed_on` = " . DB::escape(EMPTY_DATETIME) . " AND `pt`.`archived_by_id` = 0 AND `wo`.`object_manager` = 'ProjectTasks' AND `wo`.`object_id` = `ts`.`object_id` AND `wo`.`workspace_id` = `pr`.`id`"; //Project condition $conditions1 .= $workspacesCSV ? ' AND `pr`.`id` IN (' . $workspacesCSV . ')' : ''; if ($object_subtype) { $conditions1 .= " AND `pt`.`object_subtype`={$object_subtype}"; } $conditions2 = " WHERE `object_manager` = 'Projects'"; $conditions2 .= $workspacesCSV ? ' AND `ts`.`object_id` IN (' . $workspacesCSV . ") AND `ts`.`object_id` = `pr`.`id`" : " AND `ts`.`object_id` = `pr`.`id`"; $sql = $select . $preFrom . $from1 . $postFrom . $conditions1 . $commonConditions . $custom_cond . ' UNION ' . $select . $preFrom . $from2 . $postFrom . $conditions2 . $commonConditions; break; default: throw new Error("Timeslot type not recognised: " . $timeslot_type); } //Group by $wsCount = 0; $sql .= ' ORDER BY '; if (is_array($group_by)) { foreach ($group_by as $gb) { switch ($gb) { case 'project_id': $sql .= "`wsName" . $wsCount . "` ASC, "; $wsCount++; break; case 'id': case 'priority': case 'milestone_id': case 'state': if ($timeslot_type == 0) { $sql .= "`pt`.`{$gb}` ASC, "; } break; default: if (is_string($gb) && trim($gb) != '') { $sql .= "`{$gb}` ASC, "; } break; } } } //Order by if (is_array($order_by)) { foreach ($order_by as $ob) { if (is_string($ob) && trim($ob) != '') { $sql .= "`{$ob}` ASC, "; } } } $sql .= " `start_time`"; if ($limit > 0 && $offset > 0) { $sql .= " LIMIT {$offset}, {$limit}"; } $timeslots = array(); $rows = DB::executeAll($sql); if (is_array($rows)) { foreach ($rows as $row) { $tsRow = array("ts" => Timeslots::instance()->loadFromRow($row)); for ($i = 0; $i < $wslevels; $i++) { $tsRow["wsId" . $i] = $row["wsId" . $i]; } $timeslots[] = $tsRow; } // foreach } // if return count($timeslots) ? $timeslots : null; }
function instantiate_template_task_parameters(TemplateTask $object, ProjectTask $copy, $parameterValues = array()) { $objProp = TemplateObjectProperties::getPropertiesByTemplateObject($object->getTemplateId(), $object->getId()); $manager = $copy->manager(); foreach ($objProp as $property) { $propName = $property->getProperty(); $value = $property->getValue(); if ($manager->getColumnType($propName) == DATA_TYPE_STRING || $manager->getColumnType($propName) == DATA_TYPE_INTEGER) { if (is_array($parameterValues)) { $is_present = false; foreach ($parameterValues as $param => $val) { if (strpos($value, '{' . $param . '}') !== FALSE) { $value = str_replace('{' . $param . '}', $val, $value); $is_present = true; } } // if parameter not present replace the parameter code with empty string if (!$is_present) { $value = preg_replace('/[{].*[}]/U', '', $value); } } } else { if ($manager->getColumnType($propName) == DATA_TYPE_DATE || $manager->getColumnType($propName) == DATA_TYPE_DATETIME) { $operator = '+'; if (strpos($value, '+') === false) { $operator = '-'; } $opPos = strpos($value, $operator); if ($opPos !== false) { // Is parametric $dateParam = substr($value, 1, strpos($value, '}') - 1); if ($dateParam == 'task_creation') { $date = DateTimeValueLib::now(); } else { $date = getDateValue($parameterValues[$dateParam]); if (!$date instanceof DateTimeValue) { $date = DateTimeValueLib::now(); } if ($copy instanceof ProjectTask && config_option('use_time_in_task_dates') && $propName == "due_date") { $copy->setUseDueTime(1); $hour_min = getTimeValue(user_config_option('work_day_end_time')); $hour_min['hours']; $hour_min['mins']; $date->setHour($hour_min['hours']); $date->setMinute($hour_min['mins']); $date = $date->add('s', -logged_user()->getTimezone() * 3600); } if ($copy instanceof ProjectTask && config_option('use_time_in_task_dates') && $propName == "start_date") { $copy->setUseStartTime(1); $hour_min = getTimeValue(user_config_option('work_day_start_time')); $hour_min['hours']; $hour_min['mins']; $date->setHour($hour_min['hours']); $date->setMinute($hour_min['mins']); $date = $date->add('s', -logged_user()->getTimezone() * 3600); } } $dateUnit = substr($value, strlen($value) - 1); // d, w or m (for days, weeks or months) if ($dateUnit == 'm') { $dateUnit = 'M'; // make month unit uppercase to call DateTimeValue::add with correct parameter } $dateNum = (int) substr($value, strpos($value, $operator), strlen($value) - 2); //Hook::fire('template_param_date_calculation', array('op' => $operator, 'date' => $date, 'template_id' => $object->getTemplateId(), 'original' => $object, 'copy' => $copy), $dateNum); $value = $date->add($dateUnit, $dateNum); } else { $value = DateTimeValueLib::dateFromFormatAndString(user_config_option('date_format'), $value); } } } if ($value != '') { if (!$copy->setColumnValue($propName, $value)) { $copy->object->setColumnValue($propName, $value); } if ($propName == 'text' && $copy->getTypeContent() == 'text') { $copy->setText(html_to_text($copy->getText())); } $copy->save(); } } // Ensure that assigned user is subscribed if ($copy instanceof ProjectTask && $copy->getAssignedTo() instanceof Contact) { $copy->subscribeUser($copy->getAssignedTo()); } $ret = null; Hook::fire('after_template_object_param_instantiation', array('template_id' => $object->getTemplateId(), 'original' => $object, 'copy' => $copy, 'parameter_values' => $parameterValues), $ret); }
/** * 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() . '"> </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
?> <tr class="<?php echo $alt ? 'altRow' : ''; ?> "> <td class="name" title="<?php echo clean($customProp->getName()); ?> "><?php echo clean($customProp->getName()); ?> : </td> <?php // dates are in standard format "Y-m-d H:i:s", must be formatted if ($customProp->getType() == 'date') { $dtv = DateTimeValueLib::dateFromFormatAndString("Y-m-d H:i:s", $cpv->getValue()); $format = user_config_option('date_format'); Hook::fire("custom_property_date_format", null, $format); $value = $dtv->format($format); } else { $value = clean($cpv->getValue()); } $title = ''; $style = ''; if ($customProp->getType() == 'contact') { $c = Contacts::findById($value); if ($c instanceof Contact) { $htmlValue = '<div class="db-ico ico-contact" style="padding-left:18px;width:100%;">' . clean($c->getObjectName()) . '</div>'; } } else { if ($customProp->getType() == 'boolean') {
echo clean($description) . '<br/>'; } $conditionHtml = ''; if (count($conditions) > 0) { foreach ($conditions as $condition) { if ($condition->getCustomPropertyId() > 0) { $cp = CustomProperties::getCustomProperty($condition->getCustomPropertyId()); $name = clean($cp->getName()); $paramName = $condition->getId() . "_" . $cp->getName(); $coltype = $cp->getOgType(); } else { $name = lang('field ' . $model . ' ' . $condition->getFieldName()); $coltype = array_key_exists($condition->getFieldName(), $types) ? $types[$condition->getFieldName()] : ''; $paramName = $condition->getFieldName(); if (str_starts_with($coltype, 'DATE') && !$condition->getIsParametrizable()) { $cond_value = DateTimeValueLib::dateFromFormatAndString('m/d/Y', $condition->getValue())->format(user_config_option('date_format')); $condition->setValue($cond_value); } } $paramValue = isset($parameters[$paramName]) ? $parameters[$paramName] : ''; $value = $condition->getIsParametrizable() ? clean($paramValue) : clean($condition->getValue()); eval('$managerInstance = ' . $model . "::instance();"); $externalCols = $managerInstance->getExternalColumns(); if (in_array($condition->getFieldName(), $externalCols)) { $value = clean(Reports::instance()->getExternalColumnValue($condition->getFieldName(), $value, $managerInstance)); } if ($value != '') { $conditionHtml .= '- ' . $name . ' ' . ($condition->getCondition() != '%' ? $condition->getCondition() : lang('ends with')) . ' ' . format_value_to_print($condition->getFieldName(), $value, $coltype, '', '"', user_config_option('date_format')) . '<br/>'; } } }
<tr style='height:30px;'> <td><b><?php echo lang("date"); ?> : </b></td> <td align='left'><?php echo select_box('report[date_type]', array(option_tag(lang('today'), 1, array_var($report_data, "date_type") == 1 ? array('selected' => 'selected') : null), option_tag(lang('this week'), 2, array_var($report_data, "date_type") == 2 ? array('selected' => 'selected') : null), option_tag(lang('last week'), 3, array_var($report_data, "date_type") == 3 ? array('selected' => 'selected') : null), option_tag(lang('this month'), 4, array_var($report_data, "date_type") == 4 ? array('selected' => 'selected') : null), option_tag(lang('last month'), 5, array_var($report_data, "date_type") == 5 ? array('selected' => 'selected') : null), option_tag(lang('select dates...'), 6, array_var($report_data, "date_type") == 6 ? array('selected' => 'selected') : null)), array('onchange' => 'og.dateselectchange(this)')); ?> </td> </tr> <?php if (array_var($report_data, "date_type") == 6) { //echo var_dump($_SESSION); die(); $style = ""; $st = DateTimeValueLib::dateFromFormatAndString(user_config_option('date_format'), array_var($report_data, 'start_value')); $et = DateTimeValueLib::dateFromFormatAndString(user_config_option('date_format'), array_var($report_data, 'end_value')); } else { $style = 'display:none;'; $st = DateTimeValueLib::now(); $et = $st; } ?> <tr class="dateTr" style="<?php echo $style; ?> "> <td><b><?php echo lang("start date"); ?> : </b></td> <td align='left'><?php
function move_event() { if (logged_user()->isGuest()) { flash_error(lang('no access permissions')); ajx_current("empty"); return; } $event = ProjectEvents::findById(get_id()); if(!$event->canEdit(logged_user())){ flash_error(lang('no access permissions')); ajx_current("empty"); return; } $is_read = $event->getIsRead(logged_user()->getId()); $year = array_var($_GET, 'year', $event->getStart()->getYear()); $month = array_var($_GET, 'month', $event->getStart()->getMonth()); $day = array_var($_GET, 'day', $event->getStart()->getDay()); $hour = array_var($_GET, 'hour', 0); $min = array_var($_GET, 'min', 0); if ($hour == -1) $hour = format_date($event->getStart(), 'H', logged_user()->getTimezone() ); if ($min == -1) $min = format_date($event->getStart(), 'i', logged_user()->getTimezone() ); if ($event->isRepetitive()) { $orig_date = DateTimeValueLib::dateFromFormatAndString('Y-m-d H:i:s', array_var($_GET, 'orig_date')); $diff = DateTimeValueLib::get_time_difference($orig_date->getTimestamp(), mktime($hour, $min, 0, $month, $day, $year)); $new_start = new DateTimeValue($event->getStart()->getTimestamp()); $new_start->add('d', $diff['days']); $new_start->add('h', $diff['hours']); $new_start->add('m', $diff['minutes']); if ($event->getRepeatH()) { $event->setRepeatDow(date("w", mktime($hour, $min, 0, $month, $day, $year))+1); $wnum = 0; $tmp_day = $new_start->getDay(); while ($tmp_day > 0) { $tmp_day -= 7; $wnum++; } $event->setRepeatWnum($wnum); } } else { $new_start = new DateTimeValue(mktime($hour, $min, 0, $month, $day, $year) - logged_user()->getTimezone() * 3600); } $diff = DateTimeValueLib::get_time_difference($event->getStart()->getTimestamp(), $event->getDuration()->getTimestamp()); $new_duration = new DateTimeValue($new_start->getTimestamp()); $new_duration->add('d', $diff['days']); $new_duration->add('h', $diff['hours']); $new_duration->add('m', $diff['minutes']); // see if we have to reload $os = format_date($event->getStart(), 'd', logged_user()->getTimezone() ); $od = format_date($event->getDuration(), 'd', logged_user()->getTimezone() ); $ohm = format_date($event->getDuration(), 'H:i', logged_user()->getTimezone() ); $nd = format_date($new_duration, 'd', logged_user()->getTimezone() ); $nhm = format_date($new_duration, 'H:i', logged_user()->getTimezone() ); $different_days = ($os != $od && $ohm != '00:00') || ($day != $nd && $nhm != '00:00'); DB::beginWork(); $event->setStart($new_start->format("Y-m-d H:i:s")); $event->setDuration($new_duration->format("Y-m-d H:i:s")); $event->save(); $old_reminders = ObjectReminders::getByObject($event); if($old_reminders != null){ $object_controller = new ObjectController(); $object_controller->update_reminders($event, $old_reminders); //updating the old ones }else if(user_config_option("add_event_autoreminder")){ $reminder = new ObjectReminder(); $def = explode(",",user_config_option("reminders_events")); $minutes = array_var($def, 2) * array_var($def, 1); $reminder->setMinutesBefore($minutes); $reminder->setType(array_var($def, 0)); $reminder->setContext("start"); $reminder->setObject($event); $reminder->setUserId(0); $date = $event->getStart(); if ($date instanceof DateTimeValue) { $rdate = new DateTimeValue($date->getTimestamp() - $minutes * 60); $reminder->setDate($rdate); } $reminder->save(); } if (!$is_read) { $event->setIsRead(logged_user()->getId(), false); } if($event->getSpecialID() != ""){ $this->sync_calendar_extern($event); } DB::commit(); ajx_extra_data($this->get_updated_event_data($event)); if ($different_days || $event->isRepetitive()) ajx_current("reload"); else ajx_current("empty"); }
<?php $margin_left = '20px'; } ?> </div> <div class="clear"></div> <div class="section-content section1"> <?php $is_alt = false; foreach ($members as $member) { /* @var $member Member */ if (!is_null($log_data[$member->getId()]['created_by_id'])) { $created_by = Contacts::findById($log_data[$member->getId()]['created_by_id']); $created_by_name = $created_by instanceof Contact ? clean($created_by->getObjectName()) : lang('n/a'); $created_on = DateTimeValueLib::dateFromFormatAndString(DATE_MYSQL, $log_data[$member->getId()]['created_on']); } ?> <div class="member-row <?php echo $is_alt ? "alt" : ""; ?> "> <div class="member-name db-ico <?php echo $member->getIconClass(); ?> " id="member-<?php echo $member->getId(); ?> "><?php echo $member->getName(); $p = $member->getParentMember();
function edit_custom_report() { if (logged_user()->isGuest()) { flash_error(lang('no access permissions')); ajx_current("empty"); return; } $report_id = array_var($_GET, 'id'); $report = Reports::getReport($report_id); if (!$report->canEdit(logged_user())) { flash_error(lang('no access permissions')); ajx_current("empty"); return; } // if if (is_array(array_var($_POST, 'report'))) { try { ajx_current("empty"); $report_data = array_var($_POST, 'report'); $member_ids = json_decode(array_var($_POST, 'members')); if (!is_array($member_ids) || count($member_ids) == 0) { flash_error(lang('must choose at least one member')); ajx_current("empty"); return; } $members = Members::findAll(array("conditions" => array("`id` IN(?)", $member_ids))); DB::beginWork(); $report->setObjectName($report_data['name']); $report->setDescription($report_data['description']); $report->setReportObjectTypeId($report_data['report_object_type_id']); $report->setOrderBy($report_data['order_by']); $report->setIsOrderByAsc($report_data['order_by_asc'] == 'asc'); $report->save(); $conditions = array_var($_POST, 'conditions'); if (!is_array($conditions)) { $conditions = array(); } foreach ($conditions as $condition) { $newCondition = new ReportCondition(); if ($condition['id'] > 0) { $newCondition = ReportConditions::getCondition($condition['id']); } if ($condition['deleted'] == "1") { $newCondition->delete(); continue; } $newCondition->setReportId($report_id); $custom_prop_id = isset($condition['custom_property_id']) ? $condition['custom_property_id'] : 0; $newCondition->setCustomPropertyId($custom_prop_id); $newCondition->setFieldName($condition['field_name']); $newCondition->setCondition($condition['condition']); if ($condition['field_type'] == 'boolean') { $newCondition->setValue(isset($condition['value']) && $condition['value']); } else { if ($condition['field_type'] == 'date') { if ($condition['value'] == '') { $newCondition->setValue(''); } else { $dtFromWidget = DateTimeValueLib::dateFromFormatAndString(user_config_option('date_format'), $condition['value']); $newCondition->setValue(date("m/d/Y", $dtFromWidget->getTimestamp())); } } else { $newCondition->setValue(isset($condition['value']) ? $condition['value'] : ''); } } $newCondition->setIsParametrizable(isset($condition['is_parametrizable'])); $newCondition->save(); } ReportColumns::delete('report_id = ' . $report_id); $columns = array_var($_POST, 'columns'); asort($columns); //sort the array by column order foreach ($columns as $column => $order) { if ($order > 0) { $newColumn = new ReportColumn(); $newColumn->setReportId($report_id); if (is_numeric($column)) { $newColumn->setCustomPropertyId($column); } else { $newColumn->setFieldName($column); } $newColumn->save(); } } $object_controller = new ObjectController(); $object_controller->add_to_members($report, $member_ids); DB::commit(); flash_success(lang('custom report updated')); ajx_current('back'); } catch (Exception $e) { DB::rollback(); flash_error($e->getMessage()); ajx_current("empty"); } // try } else { $this->setTemplate('add_custom_report'); tpl_assign('url', get_url('reporting', 'edit_custom_report', array('id' => $report_id))); if ($report instanceof Report) { tpl_assign('id', $report_id); $report_data = array('name' => $report->getObjectName(), 'description' => $report->getDescription(), 'report_object_type_id' => $report->getReportObjectTypeId(), 'order_by' => $report->getOrderBy(), 'order_by_asc' => $report->getIsOrderByAsc()); tpl_assign('report_data', $report_data); $conditions = ReportConditions::getAllReportConditions($report_id); tpl_assign('conditions', $conditions); $columns = ReportColumns::getAllReportColumns($report_id); $colIds = array(); foreach ($columns as $col) { if ($col->getCustomPropertyId() > 0) { $colIds[] = $col->getCustomPropertyId(); } else { $colIds[] = $col->getFieldName(); } } tpl_assign('columns', $colIds); } $selected_type = $report->getReportObjectTypeId(); $types = array(array("", lang("select one"))); $object_types = ObjectTypes::getAvailableObjectTypes(); foreach ($object_types as $ot) { $types[] = array($ot->getId(), lang($ot->getName())); } tpl_assign('object_types', $types); tpl_assign('selected_type', $selected_type); tpl_assign('object', $report); tpl_assign('allowed_columns', $this->get_allowed_columns($selected_type), true); } }
/** * Execute search * TODO: Performance gus: * Fetch only ids and execute a select statement by pk (fer each result) * @param void * @return null */ function search() { // Init vars $search_for = array_var($_GET, 'search_for'); $search_dimension = array_var($_GET, 'search_dimension'); $advanced = array_var($_GET, 'advanced'); //$minWordLength = $this->minWordLength($search_for); //$useLike = ( $minWordLength && ($this->ignoreMinWordLength) && ($minWordLength < self::$MYSQL_MIN_WORD_LENGHT) ); $useLike = false; if (strlen($search_for) < 4) { $useLike = true; } $search_pieces = explode(" ", $search_for); $search_string = ""; $search_string = mysql_real_escape_string($search_for, DB::connection()->getLink()); $this->search_for = $search_for; $limit = $this->limit; $start = array_var($_REQUEST, 'start', $this->start); $this->start = $start; $limitTest = max($this->limitTest, $this->limit); $filteredResults = 0; $uid = logged_user()->getId(); if (!isset($search_dimension)) { $members = active_context_members(false); } else { if ($search_dimension == 0) { $members = array(); } else { $members = array($search_dimension); } } // click on search everywhere if (array_var($_REQUEST, 'search_all_projects')) { $members = array(); } $revisionObjectTypeId = ObjectTypes::findByName("file revision")->getId(); $members_sql = ""; if (count($members) > 0) { $context_condition = "(EXISTS\r\n\t\t\t\t\t\t\t\t\t\t(SELECT om.object_id\r\n\t\t\t\t\t\t\t\t\t\t\tFROM " . TABLE_PREFIX . "object_members om\r\n\t\t\t\t\t\t\t\t\t\t\tWHERE\tom.member_id IN (" . implode(',', $members) . ") AND so.rel_object_id = om.object_id\r\n\t\t\t\t\t\t\t\t\t\t\tGROUP BY object_id\r\n\t\t\t\t\t\t\t\t\t\t\tHAVING count(member_id) = " . count($members) . "\r\n\t\t\t\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t)"; $context_condition_rev = "(EXISTS\r\n\t\t\t\t\t\t\t\t\t\t(SELECT fr.object_id FROM " . TABLE_PREFIX . "object_members om\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tINNER JOIN " . TABLE_PREFIX . "project_file_revisions fr ON om.object_id=fr.file_id\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tINNER JOIN " . TABLE_PREFIX . "objects ob ON fr.object_id=ob.id\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tWHERE fr.file_id = so.rel_object_id AND ob.object_type_id = {$revisionObjectTypeId} AND member_id IN (" . implode(',', $members) . ") \r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tGROUP BY object_id \r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tHAVING count(member_id) = " . count($members) . "\r\n\t\t\t\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t)"; $members_sql = "AND ( " . $context_condition . " OR " . $context_condition_rev . ")"; $this->search_dimension = implode(',', $members); } else { $this->search_dimension = 0; } $listableObjectTypeIds = implode(",", ObjectTypes::getListableObjectTypeIds()); $can_see_all_tasks_cond = ""; if (!SystemPermissions::userHasSystemPermission(logged_user(), 'can_see_assigned_to_other_tasks')) { $can_see_all_tasks_cond = " AND IF((SELECT ot.name FROM " . TABLE_PREFIX . "object_types ot WHERE ot.id=o.object_type_id)='task',\r\n\t\t\t (SELECT t.assigned_to_contact_id FROM " . TABLE_PREFIX . "project_tasks t WHERE t.object_id=o.id) = " . logged_user()->getId() . ",\r\n\t\t\t true)"; } if ($_POST) { $conditions = array_var($_POST, 'conditions'); $search = array_var($_POST, 'search'); $type_object = array_var($search, 'search_object_type_id'); if (!is_array($conditions)) { $conditions = array(); } $where_condiition = ''; $conditions_view = array(); $cont = 0; $joincp = ""; $value = ""; $custom_prop_id = ""; foreach ($conditions as $condition) { $condValue = array_key_exists('value', $condition) ? $condition['value'] : ''; if ($condition['field_type'] == 'boolean') { $value = array_key_exists('value', $condition); } else { if ($condition['field_type'] == 'date') { if ($condValue != '') { $dtFromWidget = DateTimeValueLib::dateFromFormatAndString(user_config_option('date_format'), $condValue); $value = date("m/d/Y", $dtFromWidget->getTimestamp()); } } else { $value = mysql_real_escape_string($condValue, DB::connection()->getLink()); } } $condition_condition = mysql_real_escape_string(array_var($condition, 'condition'), DB::connection()->getLink()); $condition_field_name = mysql_real_escape_string(array_var($condition, 'field_name'), DB::connection()->getLink()); $conditionLocal = "like"; tpl_assign('type_object', $type_object); //CREO QUE ESTO ESTA MAL if (isset($condition['custom_property_id']) and is_numeric($condition['custom_property_id'])) { $condition_field_name = 'value'; $joincp = 'JOIN ' . TABLE_PREFIX . 'custom_property_values cp ON cp.object_id = so.rel_object_id'; } if ($condition['custom_property_id'] == 'phone_number') { $condition_field_name = 'number'; $joincp = 'JOIN ' . TABLE_PREFIX . 'contact_telephones ct ON ct.contact_id = so.rel_object_id'; } if ($condition['custom_property_id'] == 'email_address') { $condition_field_name = 'email_address'; $joincp = 'JOIN ' . TABLE_PREFIX . 'contact_emails ce ON ce.contact_id = so.rel_object_id'; } if ($condition['custom_property_id'] == 'web_url') { $condition_field_name = 'url'; $joincp = 'JOIN ' . TABLE_PREFIX . 'contact_web_pages cw ON cw.contact_id = so.rel_object_id'; } if ($condition['custom_property_id'] == 'im_value') { $condition_field_name = 'value'; $joincp = 'JOIN ' . TABLE_PREFIX . 'contact_im_values cim ON cim.contact_id = so.rel_object_id'; } if ($condition_condition == "=" or $condition_condition == ">" or $condition_condition == "<" or $condition_condition == "<>" or $condition_condition == ">=" or $condition_condition == "<=") { $conditionLocal = $condition_condition; } if ($condition_field_name == "id") { $condition_field_name = "o`.`id"; } if ($condition_condition == "like") { $where_condiition .= " AND `" . $condition_field_name . "` " . "like" . " '%" . $value . "%' "; $con = "like '%" . $value . "%' "; } else { if ($condition_condition == "ends with") { $where_condiition .= " AND `" . $condition_field_name . "` " . "like" . " '%" . $value . "' "; $con = "like '%" . $value . "' "; } else { if ($condition_condition == "start with") { $where_condiition .= " AND `" . $condition_field_name . "` " . "like" . " '" . $value . "%' "; $con = "like '" . $value . "%' "; } else { if ($condition_condition == "not like") { $where_condiition .= " AND `" . $condition_field_name . "` " . "not like" . " '%" . $value . "%' "; $con = "not like '%" . $value . "%' "; } else { $where_condiition .= " AND `" . $condition_field_name . "` " . $conditionLocal . " '" . $value . "' "; $con = $conditionLocal . " '" . $value . "' "; } } } } if ($condition['custom_property_id'] == 'address') { $addressCondiition .= " AND (street " . $con; $addressCondiition .= " OR city " . $con; $addressCondiition .= " OR state " . $con; $addressCondiition .= " OR country " . $con; $addressCondiition .= " OR zip_code " . $con . ")"; $where_condiition = $addressCondiition; $joincp = 'JOIN ' . TABLE_PREFIX . 'contact_addresses ca ON ca.contact_id = so.rel_object_id'; } $conditions_view[$cont]['id'] = $condition['id']; $conditions_view[$cont]['custom_property_id'] = $custom_prop_id; $conditions_view[$cont]['field_name'] = $condition['field_name']; $conditions_view[$cont]['condition'] = $condition['condition']; $conditions_view[$cont]['value'] = $value; $cont++; } tpl_assign('conditions', $conditions_view); if (empty($conditions)) { $search_string = array_var($search, 'text'); $where_condiition .= " AND so.content LIKE '%{$search_string}%'"; } if ($type_object) { $object_table = ObjectTypes::findById($type_object); $table = $object_table->getTableName(); } $sql = "\r\n\t\t\tSELECT DISTINCT so.rel_object_id AS id\r\n\t\t\tFROM " . TABLE_PREFIX . "searchable_objects so\r\n\t\t\t" . $joincp . "\r\n\t\t\tINNER JOIN " . TABLE_PREFIX . $table . " nto ON nto.object_id = so.rel_object_id \r\n\t\t\tINNER JOIN " . TABLE_PREFIX . "objects o ON o.id = so.rel_object_id \r\n\t\t\tWHERE (\r\n\t\t\t\t(\r\n\t\t\t\t\tEXISTS ( \r\n\t\t\t\t\t\tSELECT object_id FROM " . TABLE_PREFIX . "sharing_table sh\r\n\t\t\t\t\t\tWHERE o.id = sh.object_id \r\n\t\t\t\t\t\tAND sh.group_id IN (\r\n\t\t \t\t\t\t\t\t\t\t\tSELECT permission_group_id FROM " . TABLE_PREFIX . "contact_permission_groups WHERE contact_id = {$uid}\r\n\t\t\t\t\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t)\t\t\t\t\r\n\t\t\t \t)\r\n\t\t\t) " . $where_condiition . $members_sql . $can_see_all_tasks_cond . " ORDER by o.updated_on DESC\r\n\t\t\tLIMIT {$start}, {$limitTest}"; } else { $type_object = ''; $sql = "\t\r\n\t\t\tSELECT DISTINCT so.rel_object_id AS id \r\n\t\t\tFROM " . TABLE_PREFIX . "searchable_objects so\r\n\t\t\tWHERE " . ($useLike ? " so.content LIKE '%{$search_string}%' " : " MATCH (so.content) AGAINST ('\"{$search_string}\"' IN BOOLEAN MODE) ") . " \r\n\t\t\tAND (EXISTS\r\n\t\t\t\t(SELECT o.id\r\n\t\t\t\t FROM " . TABLE_PREFIX . "objects o\r\n\t\t\t\t WHERE\to.id = so.rel_object_id AND (\t\r\n\t\t\t\t\t\t\t(o.object_type_id = {$revisionObjectTypeId} AND \r\n\t\t\t\t\t\t\t\tEXISTS ( \r\n\t\t\t\t\t\t\t\t\tSELECT group_id FROM " . TABLE_PREFIX . "sharing_table WHERE object_id = ( SELECT file_id FROM " . TABLE_PREFIX . "project_file_revisions WHERE object_id = o.id ) \r\n\t\t\t\t\t\t\t\t\tAND group_id IN (SELECT permission_group_id FROM " . TABLE_PREFIX . "contact_permission_groups WHERE contact_id = {$uid} )\r\n\t\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t) \r\n\t\t\t\t\t\t\tOR (\r\n\t\t\t\t\t\t\t\t(EXISTS\r\n\t\t\t\t\t\t\t\t\t(SELECT object_id\r\n\t\t\t\t\t\t\t\t\t\tFROM " . TABLE_PREFIX . "sharing_table sh\r\n\t\t\t\t\t\t\t\t\t\tWHERE o.id = sh.object_id \r\n\t\t\t\t\t\t\t\t\t\tAND sh.group_id IN (\r\n\t\t\t\t\t\t\t\t\t\t\tSELECT permission_group_id FROM " . TABLE_PREFIX . "contact_permission_groups WHERE contact_id = {$uid}\r\n\t\t\t\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t)\r\n\t\t\t \t\t\t\t)\r\n\t\t\t \t\t) AND o.object_type_id IN ({$listableObjectTypeIds}) " . $members_sql . $can_see_all_tasks_cond . "\r\n\t\t\t\t)\r\n\t\t\t)\t\t\t\r\n\t\t\t\r\n\t\t\tORDER BY id DESC \r\n\t\t\tLIMIT {$start}, {$limitTest}"; } tpl_assign('type_object', $type_object); $db_search_results = array(); $search_results_ids = array(); if (!$advanced) { $timeBegin = time(); $res = DB::execute($sql); $timeEnd = time(); while ($row = $res->fetchRow()) { $search_results_ids[$row['id']] = $row['id']; } } // Prepare results for view to avoid processing at presentation layer $search_results = $this->prepareResults($search_results_ids, $null, $limit); // Calculate or approximate total for pagination $total = count($search_results_ids) + $start; if (count($search_results_ids) < $limitTest) { $total = count($search_results_ids) + $start; } else { $total = lang("many"); } //$total -= $filteredResults ; $this->total = $total; // Pagination $this->buildPagination($search_results, $search_for); // Extra data $extra = new stdClass(); if ($this->showQueryTime) { $extra->time = $timeEnd - $timeBegin; } //$extra->filteredResults = $filteredResults ; // Template asigns tpl_assign('pagination', $this->pagination); tpl_assign('search_string', $search_for); tpl_assign('search_dimension', $this->search_dimension); tpl_assign('search_results', $search_results); tpl_assign('advanced', $advanced); tpl_assign('extra', $extra); $types = array(array("", lang("select one"))); $object_types = ObjectTypes::getAvailableObjectTypes(); foreach ($object_types as $ot) { $types[] = array($ot->getId(), lang($ot->getName())); } // if ($selected_type != '') // tpl_assign('allowed_columns', $this->get_allowed_columns($selected_type)); tpl_assign('object_types', $types); //Ajax if (!$total && !$advanced) { if ($_POST && count($search_results < 0)) { tpl_assign('msg_advanced', true); } else { $this->setTemplate('no_results'); } } ajx_set_no_toolbar(true); }
function instantiate() { $selected_members = array(); $id = get_id(); $template = COTemplates::findById($id); if (!$template instanceof COTemplate) { flash_error(lang("template dnx")); ajx_current("empty"); return; } $parameters = TemplateParameters::getParametersByTemplate($id); $parameterValues = array_var($_POST, 'parameterValues'); if (count($parameters) > 0 && !isset($parameterValues)) { ajx_current("back"); return; } if (array_var($_POST, 'members')) { $selected_members = json_decode(array_var($_POST, 'members')); } else { $context = active_context(); foreach ($context as $selection) { if ($selection instanceof Member) { $selected_members[] = $selection->getId(); } } } $objects = $template->getObjects(); $controller = new ObjectController(); if (count($selected_members > 0)) { $selected_members_instances = Members::findAll(array('conditions' => 'id IN (' . implode($selected_members) . ')')); } else { $selected_members_instances = array(); } DB::beginWork(); $active_context = active_context(); foreach ($objects as $object) { if (!$object instanceof ContentDataObject) { continue; } // copy object $copy = $object->copy(); if ($copy->columnExists('is_template')) { $copy->setColumnValue('is_template', false); } if ($copy instanceof ProjectTask) { // don't copy parent task and milestone $copy->setMilestoneId(0); $copy->setParentId(0); } $copy->save(); /* if (!can_write(logged_user(), $selected_members_instances, $copy->getObjectTypeId()) ) { flash_error(lang('no context permissions to add', $copy instanceof ProjectTask ? lang("tasks") : ($copy instanceof ProjectMilestone ? lang('milestones') : ''))); DB::rollback(); ajx_current("empty"); return; }*/ // Copy members from origial object, if it doesn't have then use active context members /* $template_object_members = $object->getMemberIds(); if (count($template_object_members) == 0) { $object_member_ids = active_context_members(false); if (count($object_member_ids) > 0) { $template_object_members = Members::findAll(array("id" => true, "conditions" => "id IN (".implode(",", $object_member_ids).")")); } }*/ /* Set instantiated object members: * foreach dimension: * if no member is active then the instantiated object is put in the same members as the original for current dimension * if a member is selected in current dimension then the instantiated object will be put in that member */ $template_object_members = $object->getMembers(); $object_members = array(); foreach ($active_context as $selection) { if ($selection instanceof Member) { // member selected $object_members[] = $selection->getId(); } else { if ($selection instanceof Dimension) { // no member selected foreach ($template_object_members as $tom) { if ($tom->getDimensionId() == $selection->getId()) { $object_members[] = $tom->getId(); } } } } } $controller->add_to_members($copy, $object_members); // copy linked objects $copy->copyLinkedObjectsFrom($object); // copy subtasks if applicable if ($copy instanceof ProjectTask) { ProjectTasks::copySubTasks($object, $copy, false); foreach ($copy->getOpenSubTasks(false) as $m_task) { $controller->add_to_members($m_task, $object_members); } $manager = $copy->manager(); } else { if ($copy instanceof ProjectMilestone) { ProjectMilestones::copyTasks($object, $copy, false); foreach ($copy->getTasks(false) as $m_task) { $controller->add_to_members($m_task, $object_members); } $manager = $copy->manager(); } } // copy custom properties $copy->copyCustomPropertiesFrom($object); // set property values as defined in template $objProp = TemplateObjectProperties::getPropertiesByTemplateObject($id, $object->getId()); foreach ($objProp as $property) { $propName = $property->getProperty(); $value = $property->getValue(); if ($manager->getColumnType($propName) == DATA_TYPE_STRING || $manager->getColumnType($propName) == DATA_TYPE_INTEGER) { if (is_array($parameterValues)) { foreach ($parameterValues as $param => $val) { if (strpos($value, '{' . $param . '}') !== FALSE) { $value = str_replace('{' . $param . '}', $val, $value); } } } } else { if ($manager->getColumnType($propName) == DATA_TYPE_DATE || $manager->getColumnType($propName) == DATA_TYPE_DATETIME) { $operator = '+'; if (strpos($value, '+') === false) { $operator = '-'; } $opPos = strpos($value, $operator); if ($opPos !== false) { // Is parametric $dateParam = substr($value, 1, strpos($value, '}') - 1); $date = $parameterValues[$dateParam]; $dateUnit = substr($value, strlen($value) - 1); // d, w or m (for days, weeks or months) if ($dateUnit == 'm') { $dateUnit = 'M'; // make month unit uppercase to call DateTimeValue::add with correct parameter } $dateNum = (int) substr($value, strpos($value, $operator), strlen($value) - 2); $date = DateTimeValueLib::dateFromFormatAndString(user_config_option('date_format'), $date); $date = new DateTimeValue($date->getTimestamp() - logged_user()->getTimezone() * 3600); // set date to GMT 0 $value = $date->add($dateUnit, $dateNum); } else { $value = DateTimeValueLib::dateFromFormatAndString(user_config_option('date_format'), $value); } } } if ($value != '') { if (!$copy->setColumnValue($propName, $value)) { $copy->object->setColumnValue($propName, $value); } $copy->save(); } } // subscribe assigned to if ($copy instanceof ProjectTask) { foreach ($copy->getOpenSubTasks(false) as $m_task) { if ($m_task->getAssignedTo() instanceof Contact) { $m_task->subscribeUser($copy->getAssignedTo()); } } if ($copy->getAssignedTo() instanceof Contact) { $copy->subscribeUser($copy->getAssignedTo()); } } else { if ($copy instanceof ProjectMilestone) { foreach ($copy->getTasks(false) as $m_task) { if ($m_task->getAssignedTo() instanceof Contact) { $m_task->subscribeUser($copy->getAssignedTo()); } } } } // copy reminders $reminders = ObjectReminders::getByObject($object); foreach ($reminders as $reminder) { $copy_reminder = new ObjectReminder(); $copy_reminder->setContext($reminder->getContext()); $reminder_date = $copy->getColumnValue($reminder->getContext()); if ($reminder_date instanceof DateTimeValue) { $reminder_date = new DateTimeValue($reminder_date->getTimestamp()); $reminder_date->add('m', -$reminder->getMinutesBefore()); } $copy_reminder->setDate($reminder_date); $copy_reminder->setMinutesBefore($reminder->getMinutesBefore()); $copy_reminder->setObject($copy); $copy_reminder->setType($reminder->getType()); $copy_reminder->setUserId($reminder->getUserId()); $copy_reminder->save(); } } DB::commit(); if (is_array($parameters) && count($parameters) > 0) { ajx_current("back"); } else { if (!$choose_ctx) { ajx_current("back"); } else { ajx_current("reload"); } } }
echo '<tr><td style="width:150px;">'; echo pick_date_widget2($name, $value, null, $startTi + $ti, null, $genid . 'cp' . $customProp->getId()); echo '</td><td>'; echo '<a href="#" class="link-ico ico-delete" onclick="og.removeCPDateValue(\'' . $genid . '\',' . $customProp->getId() . ',' . $count . ')"></a>'; echo '</td></tr>'; $count++; } echo '</table>'; echo ' <a href="#" class="link-ico ico-add" onclick="og.addCPDateValue(\'' . $genid . '\',' . $customProp->getId() . ')">' . lang('add value') . '</a><br/>'; } else { if ($default_value != '') { try { $value = DateTimeValueLib::dateFromFormatAndString("Y-m-d H:i:s", $default_value); } catch (Exception $e) { try { $value = DateTimeValueLib::dateFromFormatAndString(user_config_option('date_format'), $default_value); } catch (Exception $e2) { Logger::log("Error when setting date custom property value:\n" . $e2->getMessage() . "\n\n" . get_back_trace()); $value = ''; } } } echo pick_date_widget2($name, $value, null, $startTi + $ti, null, $genid . 'cp' . $customProp->getId()); } break; case 'list': $options = array(); if (!$customProp->getIsRequired() || ($customProp->getIsRequired() || $default_value == '')) { $options[] = '<option value=""></option>'; } $totalOptions = 0;
$fieldValues = array($def_cp_value); } echo '<table id="table' . $genid . $customProp->getId() . '">'; foreach ($fieldValues as $val) { $value = DateTimeValueLib::dateFromFormatAndString("Y-m-d H:i:s", $val->getValue()); echo '<tr><td style="width:150px;">'; echo pick_date_widget2($name, $value, null, $startTi + $ti, null, $genid . 'cp' . $customProp->getId()); echo '</td><td>'; echo '<a href="#" class="link-ico ico-delete" onclick="og.removeCPDateValue(\'' . $genid . '\',' . $customProp->getId() . ',' . $count . ')"></a>'; echo '</td></tr>'; $count++; } echo '</table>'; echo ' <a href="#" class="link-ico ico-add" onclick="og.addCPDateValue(\'' . $genid . '\',' . $customProp->getId() . ')">' . lang('add value') . '</a><br/>'; } else { $value = DateTimeValueLib::dateFromFormatAndString("Y-m-d H:i:s", $default_value); echo pick_date_widget2($name, $value, null, $startTi + $ti, null, $genid . 'cp' . $customProp->getId()); } break; case 'list': $options = array(); if (!$customProp->getIsRequired()) { $options[] = '<option value=""></option>'; } $totalOptions = 0; $multValues = CustomPropertyValues::getCustomPropertyValues($_custom_properties_object->getId(), $customProp->getId()); $toSelect = array(); foreach ($multValues as $m) { $toSelect[] = $m->getValue(); } foreach (explode(',', $customProp->getValues()) as $value) {
/** * Execute search * TODO: Performance gus: * Fetch only ids and execute a select statement by pk (fer each result) * @param void * @return null */ function search() { // Init vars $search_for = array_var($_GET, 'search_for'); $search_dimension = array_var($_GET, 'search_dimension'); $advanced = array_var($_GET, 'advanced'); $minWordLength = $this->minWordLength($search_for); $useLike = ( $minWordLength && ($this->ignoreMinWordLength) && ($minWordLength < self::$MYSQL_MIN_WORD_LENGHT) ); $search_pieces= explode(" ", $search_for); $search_string = ""; if (!$useLike){ // Prepare MATCH AGAINST string foreach ($search_pieces as $word ) { if (( strpos($word, "@") || strpos($word, ".") || strpos($word, ",")) === false ) { // STRING Dont containt special characheters that mysql use as separator. Noramal flow if ($this->wildCardSearch) { $word.="*"; } }else{ $word = str_replace($this->mysqlWordSeparator, " +", $word) ; } if ( !str_starts_with($word, " ") ) { $word = " +".$word; } $search_string .= mysql_real_escape_string( $word ). " "; } $search_string = substr($search_string, 0 , -1); }else{ // USE Like Query $search_string = mysql_real_escape_string($search_for, DB::connection()->getLink()); } $this->search_for = $search_for; $limit = $this->limit; $start = array_var($_REQUEST, 'start' , $this->start); $this->start = $start; $limitTest = max( $this->limitTest , $this->limit); $filteredResults = 0; $uid = logged_user()->getId(); if(!isset($search_dimension)){ $members = active_context_members(false); }else{ if($search_dimension == 0){ $members = array(); }else{ $members = array($search_dimension); } } // click on search everywhere if (array_var($_REQUEST, 'search_all_projects')) { $members = array(); } $revisionObjectTypeId = ObjectTypes::findByName("file revision")->getId(); $members_sql = ""; if(count($members) > 0){ $members_sql = "AND (rel_object_id IN (SELECT object_id FROM " . TABLE_PREFIX . "object_members om WHERE member_id IN (" . implode ( ',', $members ) . ") GROUP BY object_id HAVING count(member_id) = ".count($members).") OR o.object_type_id = $revisionObjectTypeId AND rel_object_id IN (SELECT fr.object_id FROM " . TABLE_PREFIX . "object_members om INNER JOIN ".TABLE_PREFIX."project_file_revisions fr ON om.object_id=fr.file_id WHERE member_id IN (" . implode ( ',', $members ) . ") GROUP BY object_id HAVING count(member_id) = ".count($members)."))"; $this->search_dimension = implode ( ',', $members ); }else{ $this->search_dimension = 0; } $listableObjectTypeIds = implode(",",ObjectTypes::getListableObjectTypeIds()); if($_POST) { $conditions = array_var($_POST, 'conditions'); $search = array_var($_POST, 'search'); $type_object = array_var($search, 'search_object_type_id'); if(!is_array($conditions)) $conditions = array(); $where_condiition = ''; $conditions_view = array(); $cont = 0; $joincp =""; foreach($conditions as $condition){ $condValue = array_key_exists('value', $condition) ? $condition['value'] : ''; if($condition['field_type'] == 'boolean'){ $value = array_key_exists('value', $condition); }else if($condition['field_type'] == 'date'){ if ($condValue != '') { $dtFromWidget = DateTimeValueLib::dateFromFormatAndString(user_config_option('date_format'), $condValue); $value = date("m/d/Y", $dtFromWidget->getTimestamp()); } }else{ $value = mysql_real_escape_string($condValue, DB::connection()->getLink()); } $condition_condition = mysql_real_escape_string(array_var($condition, 'condition'), DB::connection()->getLink()); $condition_field_name = mysql_real_escape_string(array_var($condition, 'field_name'), DB::connection()->getLink()); $conditionLocal = "like"; tpl_assign('type_object', $type_object); if (isset($condition['custom_property_id']) and is_numeric($condition['custom_property_id'])){ $condition_field_name = 'value'; $joincp = 'JOIN fo_custom_property_values cp ON cp.object_id = so.rel_object_id'; }; if ($condition_condition == "=" or $condition_condition == ">" or $condition_condition == "<" or $condition_condition == "<>" or $condition_condition == ">=" or $condition_condition == "<="){ $conditionLocal = $condition_condition; }; if($condition_field_name == "id"){ $condition_field_name = "o`.`id" ; }; if($condition_condition == "like"){ $where_condiition .= " AND `" . $condition_field_name . "` " . "like" . " '%" . $value . "%' "; }else if($condition_condition == "ends with"){ $where_condiition .= " AND `" . $condition_field_name . "` " . "like" . " '%" . $value . "' "; }else if($condition_condition == "start with"){ $where_condiition .= " AND `" . $condition_field_name . "` " . "like" . " '" . $value . "%' "; }else if($condition_condition == "not like"){ $where_condiition .= " AND `" . $condition_field_name . "` " . "not like" . " '%" . $value . "%' "; }else{ $where_condiition .= " AND `" . $condition_field_name . "` " . $conditionLocal . " '" . $value . "' "; } $conditions_view[$cont]['id'] = $condition['id']; $conditions_view[$cont]['custom_property_id'] = $custom_prop_id; $conditions_view[$cont]['field_name'] = $condition['field_name']; $conditions_view[$cont]['condition'] = $condition['condition']; $conditions_view[$cont]['value'] = $value; $cont++; } tpl_assign('conditions', $conditions_view); if($type_object){ $object_table = ObjectTypes::findById($type_object); $table = $object_table->getTableName(); } $sql = " SELECT distinct(so.rel_object_id) AS id FROM ".TABLE_PREFIX."searchable_objects so ".$joincp." INNER JOIN ".TABLE_PREFIX.$table." nto ON nto.object_id = so.rel_object_id INNER JOIN ".TABLE_PREFIX."objects o ON o.id = so.rel_object_id WHERE ( ( so.rel_object_id IN ( SELECT object_id FROM ".TABLE_PREFIX."sharing_table WHERE group_id IN ( SELECT permission_group_id FROM ".TABLE_PREFIX."contact_permission_groups WHERE contact_id = $uid ) ) ) ) " . $where_condiition . $members_sql . " ORDER by o.updated_on DESC LIMIT $start, $limitTest "; } else { $type_object = ''; $sql = " SELECT distinct(so.rel_object_id) AS id FROM ".TABLE_PREFIX."searchable_objects so INNER JOIN ".TABLE_PREFIX."objects o ON o.id = so.rel_object_id WHERE ( ( o.object_type_id = $revisionObjectTypeId AND EXISTS ( SELECT id FROM ".TABLE_PREFIX."sharing_table WHERE object_id = ( SELECT file_id FROM ".TABLE_PREFIX."project_file_revisions WHERE object_id = o.id ) AND group_id IN (SELECT permission_group_id FROM ".TABLE_PREFIX."contact_permission_groups WHERE contact_id = $uid ) ) ) OR ( so.rel_object_id IN ( SELECT object_id FROM ".TABLE_PREFIX."sharing_table WHERE group_id IN ( SELECT permission_group_id FROM ".TABLE_PREFIX."contact_permission_groups WHERE contact_id = $uid ) ) ) )" . (($useLike) ? "AND so.content LIKE '%$search_string%' " : "AND MATCH (so.content) AGAINST ('$search_string' IN BOOLEAN MODE) ") . " AND o.object_type_id IN ($listableObjectTypeIds) " . $members_sql . " ORDER by o.updated_on DESC LIMIT $start, $limitTest "; } tpl_assign('type_object', $type_object); $db_search_results = array(); $search_results_ids = array(); $timeBegin = time(); $res = DB::execute($sql); $timeEnd = time(); while ($row = $res->fetchRow() ) { $search_results_ids[] = $row['id'] ; } // Prepare results for view to avoid processing at presentation layer $search_results = $this->prepareResults($search_results_ids, $null, $limit); // Calculate or approximate total for pagination $total = count($search_results_ids) + $start ; if ( count ( $search_results_ids ) < $limitTest ) { $total = count($search_results_ids) + $start ; }else{ $total = "Many" ; } //$total -= $filteredResults ; $this->total = $total ; // Pagination $this->buildPagination($search_results, $search_for); // Extra data $extra = new stdClass() ; if ($this->showQueryTime) { $extra->time = $timeEnd-$timeBegin ; } //$extra->filteredResults = $filteredResults ; // Template asigns tpl_assign('pagination', $this->pagination); tpl_assign('search_string', $search_for); tpl_assign('search_dimension', $this->search_dimension); tpl_assign('search_results', $search_results); tpl_assign('advanced', $advanced); tpl_assign('extra', $extra ); $types = array(array("", lang("select one"))); $object_types = ObjectTypes::getAvailableObjectTypes(); foreach ($object_types as $ot) { $types[] = array($ot->getId(), lang($ot->getName())); } // if ($selected_type != '') // tpl_assign('allowed_columns', $this->get_allowed_columns($selected_type)); tpl_assign('object_types', $types); //Ajax if (!$total && !$advanced){ if($_POST && count($search_results < 0)){ tpl_assign('msg_advanced', true); }else{ $this->setTemplate('no_results'); } } ajx_set_no_toolbar(true); }
/** * 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() . '"> </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 move_event() { if (logged_user()->isGuest()) { flash_error(lang('no access permissions')); ajx_current("empty"); return; } $event = ProjectEvents::findById(get_id()); if (!$event->canEdit(logged_user())) { flash_error(lang('no access permissions')); ajx_current("empty"); return; } $is_read = $event->getIsRead(logged_user()->getId()); $year = array_var($_GET, 'year', $event->getStart()->getYear()); $month = array_var($_GET, 'month', $event->getStart()->getMonth()); $day = array_var($_GET, 'day', $event->getStart()->getDay()); $hour = array_var($_GET, 'hour', 0); $min = array_var($_GET, 'min', 0); if ($hour == -1) { $hour = format_date($event->getStart(), 'H', logged_user()->getTimezone()); } if ($min == -1) { $min = format_date($event->getStart(), 'i', logged_user()->getTimezone()); } if ($event->isRepetitive()) { $orig_date = DateTimeValueLib::dateFromFormatAndString('Y-m-d H:i:s', array_var($_GET, 'orig_date')); $diff = DateTimeValueLib::get_time_difference($orig_date->getTimestamp(), mktime($hour, $min, 0, $month, $day, $year)); $new_start = new DateTimeValue($event->getStart()->getTimestamp()); $new_start->add('d', $diff['days']); $new_start->add('h', $diff['hours']); $new_start->add('m', $diff['minutes']); if ($event->getRepeatH()) { $event->setRepeatDow(date("w", mktime($hour, $min, 0, $month, $day, $year)) + 1); $wnum = 0; $tmp_day = $new_start->getDay(); while ($tmp_day > 0) { $tmp_day -= 7; $wnum++; } $event->setRepeatWnum($wnum); } } else { $new_start = new DateTimeValue(mktime($hour, $min, 0, $month, $day, $year) - logged_user()->getTimezone() * 3600); } $diff = DateTimeValueLib::get_time_difference($event->getStart()->getTimestamp(), $event->getDuration()->getTimestamp()); $new_duration = new DateTimeValue($new_start->getTimestamp()); $new_duration->add('d', $diff['days']); $new_duration->add('h', $diff['hours']); $new_duration->add('m', $diff['minutes']); // see if we have to reload $os = format_date($event->getStart(), 'd', logged_user()->getTimezone()); $od = format_date($event->getDuration(), 'd', logged_user()->getTimezone()); $ohm = format_date($event->getDuration(), 'H:i', logged_user()->getTimezone()); $nd = format_date($new_duration, 'd', logged_user()->getTimezone()); $nhm = format_date($new_duration, 'H:i', logged_user()->getTimezone()); $different_days = $os != $od && $ohm != '00:00' || $day != $nd && $nhm != '00:00'; DB::beginWork(); $event->setStart($new_start->format("Y-m-d H:i:s")); $event->setDuration($new_duration->format("Y-m-d H:i:s")); $event->save(); if (!$is_read) { $event->setIsRead(logged_user()->getId(), false); } if ($event->getSpecialID() != "") { $this->sync_calendar_extern($event); } DB::commit(); ajx_extra_data($this->get_updated_event_data($event)); if ($different_days || $event->isRepetitive()) { ajx_current("reload"); } else { ajx_current("empty"); } }
function format_value_to_print($col, $value, $type, $obj_type_id, $textWrapper = '', $dateformat = 'Y-m-d') { switch ($type) { case DATA_TYPE_STRING: if (preg_match(EMAIL_FORMAT, strip_tags($value))) { $formatted = strip_tags($value); } else { $formatted = $textWrapper . clean($value) . $textWrapper; } break; case DATA_TYPE_INTEGER: if ($col == 'priority') { switch ($value) { case 100: $formatted = lang('low priority'); break; case 200: $formatted = lang('normal priority'); break; case 300: $formatted = lang('high priority'); break; case 400: $formatted = lang('urgent priority'); break; default: $formatted = clean($value); } } elseif ($col == 'time_estimate') { if ($value > 0) { $formatted = DateTimeValue::FormatTimeDiff(new DateTimeValue(0), new DateTimeValue($value * 60), 'hm', 60); } else { $formatted = clean($value); } } else { $formatted = clean($value); } break; case DATA_TYPE_BOOLEAN: $formatted = $value == 1 ? lang('yes') : lang('no'); break; case DATA_TYPE_DATE: if ($value != 0) { if (str_ends_with($value, "00:00:00")) { $dateformat .= " H:i:s"; } $dtVal = DateTimeValueLib::dateFromFormatAndString($dateformat, $value); $formatted = format_date($dtVal, null, 0); } else { $formatted = ''; } break; case DATA_TYPE_DATETIME: if ($value != 0) { $dtVal = DateTimeValueLib::dateFromFormatAndString("{$dateformat} H:i:s", $value); if ($obj_type_id == ProjectEvents::instance()->getObjectTypeId() && $col == 'start') { $formatted = format_datetime($dtVal); } else { $formatted = format_date($dtVal, null, 0); } } else { $formatted = ''; } break; default: $formatted = $value; } if ($formatted == '') { $formatted = '--'; } return $formatted; }
function format_value() { $formatted = ""; $cp = MemberCustomProperties::getCustomProperty($this->getCustomPropertyId()); if ($cp instanceof MemberCustomProperty) { switch ($cp->getType()) { case 'text': case 'numeric': case 'memo': $formatted = $this->getValue(); break; case 'user': case 'contact': $c = Contacts::findById($this->getValue()); $formatted = $c instanceof Contact ? clean($c->getObjectName()) : ''; break; case 'boolean': $formatted = '<div class="db-ico ico-' . ($this->getValue() ? 'complete' : 'delete') . '"> </div>'; break; case 'date': if ($this->getValue() != '' && $this->getValue() != EMPTY_DATE && $this->getValue() != EMPTY_DATETIME) { $dtv = DateTimeValueLib::dateFromFormatAndString(DATE_MYSQL, $this->getValue()); if ($dtv instanceof DateTimeValue) { $formatted = format_date($dtv, null, 0); } } break; case 'list': $formatted = $this->getValue(); break; case 'table': $formatted = $this->getValue(); break; case 'address': $values = str_replace("\\|", "%%_PIPE_%%", $this->getValue()); $exploded = explode("|", $values); foreach ($exploded as &$v) { $v = str_replace("%%_PIPE_%%", "|", $v); $v = escape_character($v); } if (count($exploded) > 0) { $address_type = array_var($exploded, 0, ''); $street = array_var($exploded, 1, ''); $city = array_var($exploded, 2, ''); $state = array_var($exploded, 3, ''); $country = array_var($exploded, 4, ''); $zip_code = array_var($exploded, 5, ''); $out = $street; if ($city != '') { $out .= ' - ' . $city; } if ($state != '') { $out .= ' - ' . $state; } if ($country != '') { $out .= ' - ' . lang("country {$country}"); } $formatted = '<div class="info-content-item">' . $out . ' <a class="map-link coViewAction ico-map" href="http://maps.google.com/?q=' . $out . '" target="_blank">' . lang('map') . '</a></div>'; } break; default: $formatted = $this->getValue(); } } return $formatted; }