static function getLastActivities() { $members = active_context_members(false); // Context Members Ids $options = explode(",",user_config_option("filters_dashboard",null,null,true)); $extra_conditions = "action <> 'login' AND action <> 'logout' AND action <> 'subscribe' "; if($options[1] == 0){//do not show timeslots $extra_conditions .= "AND action <> 'open' AND action <> 'close' AND ((action <> 'add' OR action <> 'edit' OR action <> 'delete') AND object_name NOT LIKE 'Time%')"; } // task assignment conditions if (!SystemPermissions::userHasSystemPermission(logged_user(), 'can_see_assigned_to_other_tasks')) { $extra_conditions .= " AND IF((SELECT o.object_type_id FROM ".TABLE_PREFIX."objects o WHERE o.id=rel_object_id)=(SELECT ot.id FROM ".TABLE_PREFIX."object_types ot WHERE ot.name='task'), (SELECT t.assigned_to_contact_id FROM ".TABLE_PREFIX."project_tasks t WHERE t.object_id=rel_object_id) = ".logged_user()->getId().", true)"; } $members_sql = ""; if(count($members) > 0){ $object_ids_rows = DB::executeAll("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).""); $object_ids = implode(',', array_flat($object_ids_rows)); if ($object_ids == "") $object_ids = "0"; $members_sql = "rel_object_id IN ($object_ids)"; } $permissions_sql = "AND 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 = ".logged_user()->getId().") )"; $condition = ($members_sql != "" ? $members_sql . " AND " : "") . $extra_conditions . $permissions_sql; return ApplicationLogs::findAll(array( "condition" => $condition, "order" => "created_on DESC", "limit" => "100" )); }
function list_objects() { /* get query parameters */ $filesPerPage = config_option('files_per_page'); $start = array_var($_GET,'start') ? (integer)array_var($_GET,'start') : 0; $limit = array_var($_GET,'limit') ? array_var($_GET,'limit') : $filesPerPage; $order = array_var($_GET,'sort'); $id_no_select = array_var($_GET,'id_no_select',"undefined"); $ignore_context = (bool) array_var($_GET, 'ignore_context'); $member_ids = json_decode(array_var($_GET, 'member_ids')); $extra_member_ids = json_decode(array_var($_GET, 'extra_member_ids')); $orderdir = array_var($_GET,'dir'); if (!in_array(strtoupper($orderdir), array('ASC', 'DESC'))) $orderdir = 'ASC'; if ($order == "dateUpdated") { $order = "updated_on"; }elseif ($order == "dateArchived") { $order = "archived_on"; }elseif ($order == "dateDeleted") { $order = "trashed_on"; } else { $order = ""; $orderdir = ""; } $page = (integer) ($start / $limit) + 1; $hide_private = !logged_user()->isMemberOfOwnerCompany(); $typeCSV = array_var($_GET, 'type'); $types = null; if ($typeCSV) { $types = explode(",", $typeCSV); } $name_filter = mysql_escape_string( array_var($_GET, 'name') ); $linked_obj_filter = array_var($_GET, 'linkedobject'); $object_ids_filter = ''; $show_all_linked_objects = false; if (!is_null($linked_obj_filter)) { $show_all_linked_objects = true; $linkedObject = Objects::findObject($linked_obj_filter); $objs = $linkedObject->getLinkedObjects(); foreach ($objs as $obj) $object_ids_filter .= ($object_ids_filter == '' ? '' : ',') . $obj->getId(); } $filters = array(); if (!is_null($types)) $filters['types'] = $types; if (!is_null($name_filter)) $filters['name'] = $name_filter; if ($object_ids_filter != '') $filters['object_ids'] = $object_ids_filter; $user = array_var($_GET,'user'); $trashed = array_var($_GET, 'trashed', false); $archived = array_var($_GET, 'archived', false); /* if there's an action to execute, do so */ if (!$show_all_linked_objects){ $linkedObject = null; if (array_var($_GET, 'action') == 'delete') { $ids = explode(',', array_var($_GET, 'objects')); $result = ContentDataObjects::listing(array( "extra_conditions" => " AND o.id IN (".implode(",",$ids).") ", "include_deleted" => true )); $objects = $result->objects; $real_deleted_ids = array(); list($succ, $err) = $this->do_delete_objects($objects, false, $real_deleted_ids); if ($err > 0) { flash_error(lang('error delete objects', $err)); } else { Hook::fire('after_object_delete_permanently', $real_deleted_ids, $ignored); flash_success(lang('success delete objects', $succ)); } } else if (array_var($_GET, 'action') == 'delete_permanently') { $ids = explode(',', array_var($_GET, 'objects')); $objects = Objects::instance()->findAll(array("conditions" => "id IN (".implode(",",$ids).")")); $real_deleted_ids = array(); list($succ, $err) = $this->do_delete_objects($objects, true, $real_deleted_ids); if ($err > 0) { flash_error(lang('error delete objects', $err)); } if ($succ > 0) { Hook::fire('after_object_delete_permanently', $real_deleted_ids, $ignored); flash_success(lang('success delete objects', $succ)); } }else if (array_var($_GET, 'action') == 'markasread') { $ids = explode(',', array_var($_GET, 'objects')); list($succ, $err) = $this->do_mark_as_read_unread_objects($ids, true); }else if (array_var($_GET, 'action') == 'markasunread') { $ids = explode(',', array_var($_GET, 'objects')); list($succ, $err) = $this->do_mark_as_read_unread_objects($ids, false); }else if (array_var($_GET, 'action') == 'empty_trash_can') { $result = Objects::getObjectsFromContext(active_context(), 'trashed_on', 'desc', true); $objects = $result->objects; list($succ, $err) = $this->do_delete_objects($objects, true); if ($err > 0) { flash_error(lang('error delete objects', $err)); } if ($succ > 0) { flash_success(lang('success delete objects', $succ)); } } else if (array_var($_GET, 'action') == 'archive') { $ids = explode(',', array_var($_GET, 'objects')); list($succ, $err) = $this->do_archive_unarchive_objects($ids, 'archive'); if ($err > 0) { flash_error(lang('error archive objects', $err)); } else { flash_success(lang('success archive objects', $succ)); } } else if (array_var($_GET, 'action') == 'unarchive') { $ids = explode(',', array_var($_GET, 'objects')); list($succ, $err) = $this->do_archive_unarchive_objects($ids, 'unarchive'); if ($err > 0) { flash_error(lang('error unarchive objects', $err)); } else { flash_success(lang('success unarchive objects', $succ)); } } else if (array_var($_GET, 'action') == 'unclassify') { $ids = explode(',', array_var($_GET, 'objects')); $err = 0; $succ = 0; foreach ($ids as $id) { $split = explode(":", $id); $type = $split[0]; if (Plugins::instance()->isActivePlugin('mail') && $type == 'MailContents') { $email = MailContents::findById($split[1]); if (isset($email) && !$email->isDeleted() && $email->canEdit(logged_user())){ if (MailController::do_unclassify($email)) $succ++; else $err++; } else $err++; } } if ($err > 0) { flash_error(lang('error unclassify emails', $err)); } else { flash_success(lang('success unclassify emails', $succ)); } } else if (array_var($_GET, 'action') == 'restore') { $errorMessage = null; $ids = explode(',', array_var($_GET, 'objects')); $success = 0; $error = 0; foreach ($ids as $id) { $obj = Objects::findObject($id); if ($obj->canDelete(logged_user())) { try { $obj->untrash($errorMessage); if($obj->getObjectTypeId() == 11){ $event = ProjectEvents::findById($obj->getId()); if($event->getExtCalId() != ""){ $this->created_event_google_calendar($obj,$event); } } ApplicationLogs::createLog($obj, ApplicationLogs::ACTION_UNTRASH); $success++; } catch (Exception $e) { $error++; } } else { $error++; } } if ($success > 0) { flash_success(lang("success untrash objects", $success)); } if ($error > 0) { $errorString = is_null($errorMessage) ? lang("error untrash objects", $error) : $errorMessage; flash_error($errorString); } } } $filterName = array_var($_GET,'name'); $result = null; $context = active_context(); $obj_type_types = array('content_object', 'dimension_object'); if (array_var($_GET, 'include_comments')) $obj_type_types[] = 'comment'; $type_condition = ""; if ($types) { $type_condition = " AND name IN ('".implode("','",$types) ."')"; } $res = DB::executeAll("SELECT id from ".TABLE_PREFIX."object_types WHERE type IN ('". implode("','",$obj_type_types)."') AND name <> 'file revision' $type_condition "); $type_ids = array(); foreach ($res as $row){ if (ObjectTypes::isListableObjectType($row['id']) ){ $types_ids[] = $row['id'] ; } } //Hook::fire('list_objects_type_ids', null, $types_ids); $type_ids_csv = implode(',', $types_ids); $extra_conditions = array() ; $extra_conditions[] = "object_type_id in ($type_ids_csv)"; if ($name_filter) { $extra_conditions[] = "name LIKE '%$name_filter%'" ; } if ($id_no_select != "undefined") { $extra_conditions[] = "id <> $id_no_select" ; } if($object_ids_filter != ""){ $extra_conditions[] = "id in ($object_ids_filter)"; } if (!SystemPermissions::userHasSystemPermission(logged_user(), 'can_see_assigned_to_other_tasks')) { $extra_conditions[] = "IF((SELECT ot.name FROM ".TABLE_PREFIX."object_types ot WHERE ot.id=o.object_type_id)='task', (SELECT t.assigned_to_contact_id FROM ".TABLE_PREFIX."project_tasks t WHERE t.object_id=o.id) = ".logged_user()->getId().", true)"; } if($object_ids_filter == "" && $show_all_linked_objects){ $pagination = array(); }else{ $pagination = ContentDataObjects::listing(array( "start" => $start, "limit" => $limit, "order" => $order, "order_dir" => $orderdir, "trashed" => $trashed, "archived" => $archived, "types" => $types, "extra_conditions" => " AND ".implode(" AND ", $extra_conditions), "ignore_context" => $ignore_context, "extra_member_ids" => $extra_member_ids )); } $result = $pagination->objects; $total_items = $pagination->total; if(!$result) $result = array(); /* prepare response object */ $info = array(); foreach ($result as $obj /* @var $obj Object */) { $info_elem = $obj->getArrayInfo($trashed, $archived); $instance = Objects::instance()->findObject($info_elem['object_id']); if (!$instance instanceof ContentDataObject) continue; $info_elem['url'] = $instance->getViewUrl(); /* @var $instance Contact */ if ($instance instanceof Contact /* @var $instance Contact */ ) { if( $instance->isCompany() ) { $info_elem['icon'] = 'ico-company'; $info_elem['type'] = 'company'; } } else if ($instance instanceof ProjectFile) { $info_elem['mimeType'] = $instance->getTypeString(); } $info_elem['isRead'] = $instance->getIsRead(logged_user()->getId()) ; $info_elem['manager'] = get_class($instance->manager()) ; $info_elem['memPath'] = json_encode($instance->getMembersToDisplayPath()); $info[] = $info_elem; } $listing = array( "totalCount" => $total_items, "start" => $start, "objects" => $info ); ajx_extra_data($listing); tpl_assign("listing", $listing); if (isset($reload) && $reload) ajx_current("reload"); else ajx_current("empty"); }
static function getLastActivities() { $members = active_context_members(false); // Context Members Ids $options = explode(",", user_config_option("filters_dashboard", null, null, true)); $extra_conditions = "action <> 'login' AND action <> 'logout' AND action <> 'subscribe' AND created_by_id > '0'"; if ($options[1] == 0) { //do not show timeslots $extra_conditions .= "AND action <> 'open' AND action <> 'close' AND ((action <> 'add' OR action <> 'edit' OR action <> 'delete') AND object_name NOT LIKE 'Time%')"; } // task assignment conditions if (!SystemPermissions::userHasSystemPermission(logged_user(), 'can_see_assigned_to_other_tasks')) { $extra_conditions .= " AND IF((SELECT o.object_type_id FROM " . TABLE_PREFIX . "objects o WHERE o.id=rel_object_id)=(SELECT ot.id FROM " . TABLE_PREFIX . "object_types ot WHERE ot.name='task'),\r\n\t\t\t\t(SELECT t.assigned_to_contact_id FROM " . TABLE_PREFIX . "project_tasks t WHERE t.object_id=rel_object_id) = " . logged_user()->getId() . ",\r\n\t\t\t\ttrue)"; } //do not display template tasks logs $extra_conditions .= " AND IF((SELECT o.object_type_id FROM " . TABLE_PREFIX . "objects o WHERE o.id=rel_object_id)=(SELECT ot.id FROM " . TABLE_PREFIX . "object_types ot WHERE ot.name='template_task'), false, true)"; // if logged user is guest dont show other users logs if (logged_user()->isGuest()) { $extra_conditions .= " AND `created_by_id`=" . logged_user()->getId(); } $members_sql = ""; $is_member_child = ""; if (count($members) > 0) { $members_sql = "(EXISTS(\r\n\t\t\t\tSELECT om.object_id FROM " . TABLE_PREFIX . "object_members om\r\n\t\t\t\tWHERE om.member_id IN (" . implode(',', $members) . ") AND rel_object_id = om.object_id\r\n\t\t\t\tGROUP BY object_id\r\n\t\t\t\tHAVING count(member_id) = " . count($members) . "\r\n\t\t\t))"; $is_member_child = "AND mem.parent_member_id IN (" . implode(',', $members) . ")"; } //permissions $logged_user_pgs = implode(',', logged_user()->getPermissionGroupIds()); $permissions_condition = "al.rel_object_id IN (\r\n\t\tSELECT sh.object_id FROM " . TABLE_PREFIX . "sharing_table sh\r\n\t\tWHERE al.rel_object_id = sh.object_id AND sh.object_id > 0\r\n\t\tAND sh.group_id IN ({$logged_user_pgs})\r\n\t\t)"; $sql = "SELECT al.id FROM " . TABLE_PREFIX . "application_logs al \r\n\t\t\t\tWHERE {$permissions_condition} AND {$extra_conditions}"; if ($members_sql != "") { $sql .= " AND {$members_sql}"; //do not display users logs $sql .= " AND NOT EXISTS(SELECT con.object_id FROM " . TABLE_PREFIX . "contacts con WHERE con.object_id=rel_object_id AND user_type > 0)"; } $sql .= " ORDER BY created_on DESC LIMIT 100"; $id_rows = array_flat(DB::executeAll($sql)); // if logged user is guest dont show other users logs $user_condition = ""; if (logged_user()->isGuest()) { $user_condition .= " AND `created_by_id`=" . logged_user()->getId(); } $member_logs_sql = "SELECT al.id FROM " . TABLE_PREFIX . "application_logs al\r\n\t\t\t\t\t\t\t\t\tINNER JOIN " . TABLE_PREFIX . "members mem ON mem.id=al.member_id \r\n\t\t\t\t\t\t\t\t\t\tINNER JOIN " . TABLE_PREFIX . "contact_member_cache cmcache ON cmcache.member_id=mem.id AND cmcache.contact_id = " . logged_user()->getId() . "\r\n\t\t\t\t\t\t\t\t\t\t\tWHERE al.member_id>0\r\n\t\t\t\t\t\t\t\t\t\t\t{$user_condition}\r\n\t\t\t\t\t\t\t\t\t\t\t{$is_member_child}\r\n\t\t\t\t\t\t\tORDER BY created_on DESC LIMIT 100"; $m_id_rows = array_flat(DB::executeAll($member_logs_sql)); $id_rows = array_filter(array_merge($id_rows, $m_id_rows)); $logs = array(); if (count($id_rows) > 0) { $logs = ApplicationLogs::findAll(array("condition" => "id IN (" . implode(',', $id_rows) . ")", "order" => "created_on DESC")); } return $logs; }
/** * 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_id * @param array $group_by * @param array $order_by * @return array */ static function getTaskTimeslots($context, $members = null, $user = null, $start_date = null, $end_date = null, $object_id = 0, $group_by = null, $order_by = null, $limit = 0, $offset = 0, $timeslot_type = 0, $extra_conditions = '') { $commonConditions = ""; if ($start_date) { $commonConditions .= DB::prepareString(' AND `e`.`start_time` >= ? ', array($start_date)); } if ($end_date) { $commonConditions .= DB::prepareString(' AND (`e`.`paused_on` <> 0 AND `e`.`paused_on` <= ? OR `e`.`end_time` <> 0 AND `e`.`end_time` <= ?) ', array($end_date, $end_date)); } //User condition $commonConditions .= $user ? ' AND `e`.`contact_id` = ' . $user->getId() : ''; //Object condition $commonConditions .= $object_id > 0 ? ' AND `e`.`rel_object_id` = ' . $object_id : ''; switch ($timeslot_type) { case 0: //Task timeslots $conditions = " AND EXISTS (SELECT `obj`.`id` FROM `" . TABLE_PREFIX . "objects` `obj` WHERE `obj`.`id` = `e`.`rel_object_id` AND `obj`.`trashed_on` = 0 AND `obj`.`archived_on` = 0)"; break; case 1: //Time timeslots $conditions = " AND `e`.`rel_object_id` = 0"; break; case 2: //All timeslots $conditions = " AND (`e`.`rel_object_id` = 0 OR `e`.`rel_object_id` IN (SELECT `obj`.`id` FROM `" . TABLE_PREFIX . "objects` `obj` WHERE `obj`.`trashed_on` = 0 AND `obj`.`archived_on` = 0))"; break; default: throw new Error("Timeslot type not recognised: " . $timeslot_type); } if (!SystemPermissions::userHasSystemPermission(logged_user(), 'can_see_assigned_to_other_tasks')) { $conditions .= " AND `e`.`contact_id` = " . logged_user()->getId(); } $conditions .= $commonConditions . $extra_conditions; $order_by[] = 'start_time'; $result = self::instance()->listing(array('order' => $order_by, 'extra_conditions' => $conditions)); return $result->objects; }
<?php $genid = gen_id(); $limit = 20; $total = $limit; $page = 10; $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(); } $tasks_result = ProjectTasks::instance()->listing(array("order" => "completed_on", "order_dir" => "DESC", "extra_conditions" => " AND is_template = 0 AND completed_by_id > 0 {$task_assignment_conditions}", "limit" => $limit + 1)); $tasks = $tasks_result->objects; $active_members = array(); $context = active_context(); if (is_array($context)) { foreach ($context as $selection) { if ($selection instanceof Member) { $active_members[] = $selection; } } } if (count($active_members) > 0) { $mnames = array(); $allowed_contact_ids = array(); foreach ($active_members as $member) { $mnames[] = clean($member->getName()); } $widget_title = lang('completed tasks') . ' ' . lang('in') . ' ' . implode(", ", $mnames); } if ($tasks_result->total > 0) { include 'template.php';
/** * 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
function add_timeslot() { $object_id = array_var($_REQUEST, "object_id", false); ajx_current("empty"); $timeslot_data = array_var($_POST, 'timeslot'); if ($object_id) { $object = Objects::findObject($object_id); if (!$object instanceof ContentDataObject || !$object->canAddTimeslot(logged_user())) { flash_error(lang('no access permissions')); ajx_current("empty"); return; } $member_ids = $object->getMemberIds(); } else { $member_ids = json_decode(array_var($_POST, 'members', array())); // clean member_ids $tmp_mids = array(); foreach ($member_ids as $mid) { if (!is_null($mid) && trim($mid) != "") { $tmp_mids[] = $mid; } } $member_ids = $tmp_mids; if (empty($member_ids)) { if (!can_add(logged_user(), active_context(), Timeslots::instance()->getObjectTypeId())) { flash_error(lang('no access permissions')); ajx_current("empty"); return; } } else { if (count($member_ids) > 0) { $enteredMembers = Members::findAll(array('conditions' => 'id IN (' . implode(",", $member_ids) . ')')); } else { $enteredMembers = array(); } if (!can_add(logged_user(), $enteredMembers, Timeslots::instance()->getObjectTypeId())) { flash_error(lang('no access permissions')); ajx_current("empty"); return; } } $object_id = 0; } try { $hoursToAdd = array_var($timeslot_data, 'hours', 0); $minutes = array_var($timeslot_data, 'minutes', 0); if (strpos($hoursToAdd, ',') && !strpos($hoursToAdd, '.')) { $hoursToAdd = str_replace(',', '.', $hoursToAdd); } if (strpos($hoursToAdd, ':') && !strpos($hoursToAdd, '.')) { $pos = strpos($hoursToAdd, ':') + 1; $len = strlen($hoursToAdd) - $pos; $minutesToAdd = substr($hoursToAdd, $pos, $len); if (!strlen($minutesToAdd) <= 2 || !strlen($minutesToAdd) > 0) { $minutesToAdd = substr($minutesToAdd, 0, 2); } $mins = $minutesToAdd / 60; $hours = substr($hoursToAdd, 0, $pos - 1); $hoursToAdd = $hours + $mins; } if ($minutes) { $min = str_replace('.', '', $minutes / 6); $hoursToAdd = $hoursToAdd + ("0." . $min); } if ($hoursToAdd <= 0) { flash_error(lang('time has to be greater than 0')); return; } $startTime = getDateValue(array_var($timeslot_data, 'date')); $startTime = $startTime->add('h', 8 - logged_user()->getTimezone()); $endTime = getDateValue(array_var($timeslot_data, 'date')); $endTime = $endTime->add('h', 8 - logged_user()->getTimezone() + $hoursToAdd); //use current time if (array_var($_REQUEST, "use_current_time", false)) { $currentStartTime = DateTimeValueLib::now(); $currentEndTime = DateTimeValueLib::now(); $currentStartTime = $currentStartTime->add('h', -$hoursToAdd); $startTime->setHour($currentStartTime->getHour()); $startTime->setMinute($currentStartTime->getMinute()); $endTime->setHour($currentEndTime->getHour()); $endTime->setMinute($currentEndTime->getMinute()); } $timeslot_data['start_time'] = $startTime; $timeslot_data['end_time'] = $endTime; $timeslot_data['description'] = html_to_text($timeslot_data['description']); $timeslot_data['name'] = $timeslot_data['description']; $timeslot_data['rel_object_id'] = $object_id; //array_var($timeslot_data,'project_id'); $timeslot = new Timeslot(); //Only admins can change timeslot user if (!array_var($timeslot_data, 'contact_id', false) || !SystemPermissions::userHasSystemPermission(logged_user(), 'can_manage_time')) { $timeslot_data['contact_id'] = logged_user()->getId(); } $timeslot->setFromAttributes($timeslot_data); $user = Contacts::findById($timeslot_data['contact_id']); $billing_category_id = $user->getDefaultBillingId(); $bc = BillingCategories::findById($billing_category_id); if ($bc instanceof BillingCategory) { $timeslot->setBillingId($billing_category_id); $hourly_billing = $bc->getDefaultValue(); $timeslot->setHourlyBilling($hourly_billing); $timeslot->setFixedBilling($hourly_billing * $hoursToAdd); $timeslot->setIsFixedBilling(false); } DB::beginWork(); $timeslot->save(); $task = ProjectTasks::findById($object_id); if ($task instanceof ProjectTask) { $task->calculatePercentComplete(); } if (!isset($member_ids) || !is_array($member_ids) || count($member_ids) == 0) { $member_ids = json_decode(array_var($_POST, 'members')); } $object_controller = new ObjectController(); $object_controller->add_to_members($timeslot, $member_ids); DB::commit(); ApplicationLogs::createLog($timeslot, ApplicationLogs::ACTION_ADD); $show_billing = can_manage_billing(logged_user()); ajx_extra_data(array("timeslot" => $timeslot->getArrayInfo($show_billing), "real_obj_id" => $timeslot->getRelObjectId())); } catch (Exception $e) { DB::rollback(); flash_error($e->getMessage()); } // try }
/** * 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; }
/** * Returns whether a user can manage configuration. * * @param Contact $user * @return boolean */ function can_manage_configuration(Contact $user) { return SystemPermissions::userHasSystemPermission($user, 'can_manage_configuration'); }
function add_timeslot(){ if (!can_add(logged_user(), active_context(), Timeslots::instance()->getObjectTypeId())) { flash_error(lang('no access permissions')); ajx_current("empty"); return; } ajx_current("empty"); $timeslot_data = array_var($_POST, 'timeslot'); try { $hoursToAdd = array_var($timeslot_data, 'hours',0); $minutes = array_var($timeslot_data, 'minutes',0); if (strpos($hoursToAdd,',') && !strpos($hoursToAdd,'.')) $hoursToAdd = str_replace(',','.',$hoursToAdd); if (strpos($hoursToAdd,':') && !strpos($hoursToAdd,'.')) { $pos = strpos($hoursToAdd,':') + 1; $len = strlen($hoursToAdd) - $pos; $minutesToAdd = substr($hoursToAdd,$pos,$len); if( !strlen($minutesToAdd)<=2 || !strlen($minutesToAdd)>0){ $minutesToAdd = substr($minutesToAdd,0,2); } $mins = $minutesToAdd / 60; $hours = substr($hoursToAdd, 0, $pos-1); $hoursToAdd = $hours + $mins; } if($minutes){ $min = str_replace('.','',($minutes/6)); $hoursToAdd = $hoursToAdd + ("0.".$min); } if ($hoursToAdd <= 0){ flash_error(lang('time has to be greater than 0')); return; } $startTime = getDateValue(array_var($timeslot_data, 'date')); $startTime = $startTime->add('h', 8 - logged_user()->getTimezone()); $endTime = getDateValue(array_var($timeslot_data, 'date')); $endTime = $endTime->add('h', 8 - logged_user()->getTimezone() + $hoursToAdd); $timeslot_data['start_time'] = $startTime; $timeslot_data['end_time'] = $endTime; $timeslot_data['name'] = $timeslot_data['description']; $timeslot_data['object_id'] = 0;//array_var($timeslot_data,'project_id'); $timeslot = new Timeslot(); //Only admins can change timeslot user if (!array_var($timeslot_data, 'contact_id', false) || !SystemPermissions::userHasSystemPermission(logged_user(), 'can_manage_time')) { $timeslot_data['contact_id'] = logged_user()->getId(); } $timeslot->setFromAttributes($timeslot_data); $user = Contacts::findById($timeslot_data['contact_id']); $billing_category_id = $user->getDefaultBillingId(); $bc = BillingCategories::findById($billing_category_id); if ($bc instanceof BillingCategory) { $timeslot->setBillingId($billing_category_id); $hourly_billing = $bc->getDefaultValue(); $timeslot->setHourlyBilling($hourly_billing); $timeslot->setFixedBilling($hourly_billing * $hoursToAdd); $timeslot->setIsFixedBilling(false); } DB::beginWork(); $timeslot->save(); $member_ids = json_decode(array_var($_POST, 'members')); $object_controller = new ObjectController(); $object_controller->add_to_members($timeslot, $member_ids); ApplicationLogs::createLog($timeslot, ApplicationLogs::ACTION_ADD); DB::commit(); $show_billing = can_manage_billing(logged_user()); ajx_extra_data(array("timeslot" => $timeslot->getArrayInfo($show_billing))); } catch(Exception $e) { DB::rollback(); flash_error($e->getMessage()); } // try }
function list_objects() { /* get query parameters */ $filesPerPage = config_option('files_per_page'); $start = array_var($_GET, 'start') ? (int) array_var($_GET, 'start') : 0; $limit = array_var($_GET, 'limit') ? array_var($_GET, 'limit') : $filesPerPage; $order = array_var($_GET, 'sort'); $id_no_select = array_var($_GET, 'id_no_select', "undefined"); $ignore_context = (bool) array_var($_GET, 'ignore_context'); $member_ids = json_decode(array_var($_GET, 'member_ids')); $extra_member_ids = json_decode(array_var($_GET, 'extra_member_ids')); $orderdir = array_var($_GET, 'dir'); if (!in_array(strtoupper($orderdir), array('ASC', 'DESC'))) { $orderdir = 'ASC'; } if ($order == "dateUpdated") { $order = "updated_on"; } elseif ($order == "dateArchived") { $order = "archived_on"; } elseif ($order == "dateDeleted") { $order = "trashed_on"; } elseif ($order == "name") { $order = "name"; } else { $order = ""; $orderdir = ""; } $extra_list_params = array_var($_GET, 'extra_list_params'); $extra_list_params = json_decode($extra_list_params); $page = (int) ($start / $limit) + 1; $hide_private = !logged_user()->isMemberOfOwnerCompany(); $typeCSV = array_var($_GET, 'type'); $types = null; if ($typeCSV) { $types = explode(",", $typeCSV); } $name_filter = mysql_real_escape_string(array_var($_GET, 'name')); $linked_obj_filter = array_var($_GET, 'linkedobject'); $object_ids_filter = ''; $show_all_linked_objects = false; if (!is_null($linked_obj_filter)) { $show_all_linked_objects = true; $linkedObject = Objects::findObject($linked_obj_filter); $objs = $linkedObject->getLinkedObjects(); foreach ($objs as $obj) { $object_ids_filter .= ($object_ids_filter == '' ? '' : ',') . $obj->getId(); } } $filters = array(); if (!is_null($types)) { $filters['types'] = $types; } if (!is_null($name_filter)) { $filters['name'] = $name_filter; } if ($object_ids_filter != '') { $filters['object_ids'] = $object_ids_filter; } $user = array_var($_GET, 'user'); $trashed = array_var($_GET, 'trashed', false); $archived = array_var($_GET, 'archived', false); /* if there's an action to execute, do so */ if (!$show_all_linked_objects) { $this->processListActions(); } $filterName = array_var($_GET, 'name'); $template_object_names = ""; $template_extra_condition = "true"; $template_objects = false; if (in_array("template_task", array_var($filters, 'types', array())) || in_array("template_milestone", array_var($filters, 'types', array()))) { $template_id = 0; $template_objects = true; if (isset($extra_list_params->template_id)) { $template_id = $extra_list_params->template_id; } $tmpl_task = TemplateTasks::findById(intval($id_no_select)); if ($tmpl_task instanceof TemplateTask) { $template_extra_condition = "o.id IN (SELECT object_id from " . TABLE_PREFIX . "template_tasks WHERE `template_id`=" . $tmpl_task->getTemplateId() . " OR `template_id`=0 AND `session_id`=" . logged_user()->getId() . " )"; } else { $template_extra_condition = "o.id IN (SELECT object_id from " . TABLE_PREFIX . "template_tasks WHERE `template_id`=" . intval($template_id) . " OR `template_id`=0 AND `session_id`=" . logged_user()->getId() . " )"; } } else { $template_object_names = "AND name <> 'template_task' AND name <> 'template_milestone'"; } $result = null; $context = active_context(); $obj_type_types = array('content_object', 'dimension_object'); if (array_var($_GET, 'include_comments')) { $obj_type_types[] = 'comment'; } $type_condition = ""; if ($types) { $type_condition = " AND name IN ('" . implode("','", $types) . "')"; } $extra_conditions = array(); // user filter if (in_array("contact", array_var($filters, 'types', array())) && isset($extra_list_params->is_user)) { $joins[] = "\r\n\t\t\t\tLEFT JOIN " . TABLE_PREFIX . "contacts c on c.object_id=o.id"; $extra_conditions[] = "\r\n\t\t\t\tc.user_type " . ($extra_list_params->is_user == 1 ? ">" : "=") . " 0"; if (isset($extra_list_params->has_permissions) && $extra_list_params->has_permissions > 0) { $mem_id = $extra_list_params->has_permissions; $extra_conditions[] = " EXISTS (\r\n\t\t\t\t\tSELECT cmp.permission_group_id FROM " . TABLE_PREFIX . "contact_member_permissions cmp\r\n\t\t\t\t\tWHERE cmp.permission_group_id IN (SELECT x.permission_group_id FROM " . TABLE_PREFIX . "contact_permission_groups x WHERE x.contact_id=o.id)\r\n\t\t\t\t\tAND cmp.member_id='{$mem_id}' \r\n\t\t\t\t\tAND cmp.object_type_id NOT IN (SELECT tp.object_type_id FROM " . TABLE_PREFIX . "tab_panels tp WHERE tp.enabled=0)\r\n\t\t\t\t\tAND cmp.object_type_id NOT IN (SELECT oott.id FROM " . TABLE_PREFIX . "object_types oott WHERE oott.name IN ('comment','template'))\r\n\t\t\t\t\tAND cmp.object_type_id IN (SELECT oott2.id FROM " . TABLE_PREFIX . "object_types oott2 WHERE oott2.type IN ('content_object','dimension_object'))\r\n\t\t\t\t)"; } } // Object type filter - exclude template types (if not template picker), filter by required type names (if specified) and match value with objects table $extra_object_type_conditions = "\r\n\t\t\tAND name <> 'file revision' {$template_object_names} {$type_condition} AND o.object_type_id = ot.id"; $extra_conditions[] = ObjectTypes::getListableObjectsSqlCondition($extra_object_type_conditions); // -- // logged user permission group ids $logged_user_pg_ids = implode(',', logged_user()->getPermissionGroupIds()); // used in template object picker $extra_conditions[] = $template_extra_condition; // when filtering by name if ($name_filter) { $extra_conditions[] = "\r\n\t\t\t\tname LIKE '%{$name_filter}%'"; } // when excluding some object in particular if ($id_no_select != "undefined") { $extra_conditions[] = "\r\n\t\t\t\tid <> '{$id_no_select}'"; } // when filtering by some group of objects, for example in the linked objects view if ($object_ids_filter != "") { $extra_conditions[] = "\r\n\t\t\t\tid in ({$object_ids_filter})"; } $joins[] = "\r\n\t\t\tLEFT JOIN " . TABLE_PREFIX . "project_tasks pt on pt.object_id=o.id"; if (!SystemPermissions::userHasSystemPermission(logged_user(), 'can_see_assigned_to_other_tasks')) { // exclude other users' tasks if cannot see them $extra_conditions[] = "\r\n\t\t\t\t( pt.assigned_to_contact_id IS NULL OR pt.assigned_to_contact_id= " . logged_user()->getId() . ")"; } // don't include tasks which have is_template=1 $extra_conditions[] = "\r\n\t\t\t( pt.is_template IS NULL OR pt.is_template=0)"; // trashed conditions $extra_conditions[] = "\r\n\t\t\to.trashed_on" . ($trashed ? "<>" : "=") . "0"; // archived conditions $extra_conditions[] = "\r\n\t\t\to.archived_on" . ($archived ? "<>" : "=") . "0"; // don't include unclassified mails from other accounts if (Plugins::instance()->isActivePlugin('mail')) { $accounts_of_loggued_user = MailAccountContacts::getByContact(logged_user()); $account_ids = array(0); foreach ($accounts_of_loggued_user as $acc) { $account_ids[] = $acc->getAccountId(); } $joins[] = "\r\n\t\t\t\tLEFT JOIN " . TABLE_PREFIX . "mail_contents mc on mc.object_id=o.id\r\n\t\t\t"; $extra_conditions[] = "\r\n\t\t\t\tIF( mc.account_id IS NULL, true, mc.account_id IN (" . implode(',', $account_ids) . ") OR EXISTS (\r\n\t\t\t\t\tSELECT om1.object_id FROM " . TABLE_PREFIX . "object_members om1 \r\n\t\t\t\t\t\tINNER JOIN " . TABLE_PREFIX . "members m1 ON m1.id=om1.member_id \r\n\t\t\t\t\t\tINNER JOIN " . TABLE_PREFIX . "dimensions d1 ON d1.id=m1.dimension_id \r\n\t\t\t\t\tWHERE om1.object_id=o.id AND d1.is_manageable=1)\r\n\t\t\t\t)"; } // don't show attached files of emails that cannot be viewed if (logged_user()->isAdministrator() && Plugins::instance()->isActivePlugin('mail')) { $joins[] = "LEFT JOIN " . TABLE_PREFIX . "project_files pf on pf.object_id=o.id"; $extra_conditions[] = "IF(pf.mail_id IS NULL OR pf.mail_id = 0, true, \r\n\t\t\t\tpf.mail_id IN (SELECT sh.object_id FROM " . TABLE_PREFIX . "sharing_table sh WHERE pf.mail_id = sh.object_id AND sh.group_id IN ({$logged_user_pg_ids})))"; } $only_count_result = array_var($_GET, 'only_result', false); $count_results = array_var($_GET, 'count_results', false); // Members filter $sql_members = ""; if (!$ignore_context && !$member_ids) { $members = active_context_members(false); // Context Members Ids } elseif (count($member_ids)) { $members = $member_ids; } else { // get members from context if (!$ignore_context) { $members = active_context_members(false); } } if (is_array($extra_member_ids)) { if (isset($members)) { $members = array_merge($members, $extra_member_ids); } else { $members = $extra_member_ids; } } if (isset($members) && is_array($members) && count($members) > 0 && !(isset($template_id) && $template_id > 0)) { $sql_members = "\r\n\t\t\t\tAND (EXISTS (SELECT om.object_id\r\n\t\t\t\t\tFROM " . TABLE_PREFIX . "object_members om\r\n\t\t\t\t\tWHERE om.member_id IN (" . implode(',', $members) . ") AND o.id = om.object_id \r\n\t\t\t\t\tGROUP BY object_id\r\n\t\t\t\t\tHAVING count(member_id) = " . count($members) . "\r\n\t\t\t\t))\r\n\t\t\t"; } // -- // Permissions filter if (isset($template_id) && $template_id > 0) { // editing template items do not check permissions $sql_permissions = ""; } else { $sql_permissions = "\r\n\t\t\t\tAND EXISTS (SELECT sh.object_id FROM " . TABLE_PREFIX . "sharing_table sh WHERE sh.object_id=o.id AND sh.group_id IN ({$logged_user_pg_ids}))\r\n\t\t\t"; } // Main select $sql_select = "SELECT * FROM " . TABLE_PREFIX . "objects o "; // Joins $sql_joins = implode(" ", $joins); // Where $sql_where = "\r\n\t\t\tWHERE " . implode(" AND ", $extra_conditions) . $sql_permissions . $sql_members; // Order $sql_order = ""; if ($order) { $sql_order = "\r\n\t\t\t\tORDER BY {$order} {$orderdir}\r\n\t\t\t"; } // Limit $sql_limit = ""; if ($start >= 0 && $limit > 0) { $sql_limit = " LIMIT {$start}, {$limit}"; } // Full SQL $sql = "{$sql_select} {$sql_joins} {$sql_where} {$sql_order} {$sql_limit}"; // Execute query if (!$only_count_result) { $rows = DB::executeAll($sql); } // get total items if ($count_results) { $sql_count = "SELECT count(o.id) as total_items FROM " . TABLE_PREFIX . "objects o {$sql_joins} {$sql_where}"; $rows_count = DB::executeAll($sql_count); $total_items = $rows_count[0]['total_items']; } else { if (isset($rows) && is_array($rows)) { $total_items = count($rows) < $filesPerPage ? count($rows) : 1000000; } else { $total_items = 0; } } // prepare response object $info = array(); // get objects if (isset($rows) && is_array($rows)) { foreach ($rows as $row) { $instance = Objects::findObject($row['id']); if (!$instance instanceof ContentDataObject) { continue; } $info_elem = $instance->getObject()->getArrayInfo(); $info_elem['url'] = $instance->getViewUrl(); $info_elem['isRead'] = $instance->getIsRead(logged_user()->getId()); $info_elem['manager'] = get_class($instance->manager()); $info_elem['memPath'] = json_encode($instance->getMembersIdsToDisplayPath()); if ($instance instanceof Contact) { if ($instance->isCompany()) { $info_elem['icon'] = 'ico-company'; $info_elem['type'] = 'company'; } else { $info_elem['memPath'] = json_encode($instance->getUserType() ? "" : $instance->getMembersIdsToDisplayPath()); } } else { if ($instance instanceof ProjectFile) { $info_elem['mimeType'] = $instance->getTypeString(); } } $info[] = $info_elem; } } $listing = array("totalCount" => $total_items, "start" => $start, "objects" => $info); ajx_extra_data($listing); tpl_assign("listing", $listing); if (isset($reload) && $reload) { ajx_current("reload"); } else { ajx_current("empty"); } }
/** * Returns whether a user can link objects. * * @param Contact $user * @return boolean */ function can_link_objects(Contact $user) { return SystemPermissions::userHasSystemPermission($user, 'can_link_objects'); }
function new_list_tasks(){ //load config options into cache for better performance load_user_config_options_by_category_name('task panel'); // get query parameters, save user preferences if necessary $status = array_var($_GET,'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 = array_var($_GET, '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($_GET,'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 = "`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 `completed_on` = " . DB::escape(EMPTY_DATETIME) . " AND `id` IN(" . implode(',', $subs) . ")"; } }else{ $task_filter_condition = " AND `completed_on` = " . DB::escape(EMPTY_DATETIME) . " AND `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 `completed_on` = " . DB::escape(EMPTY_DATETIME); break; case 1: // Complete tasks $task_status_condition = " AND `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 `completed_on` = " . DB::escape(EMPTY_DATETIME) . " AND `due_date` < '$now'"; break; case 12: // Today tasks $task_status_condition = " AND `completed_on` = " . DB::escape(EMPTY_DATETIME) . " AND `due_date` >= '$now' AND `due_date` <= '$now_end'"; break; case 13: // Today + Overdue tasks $task_status_condition = " AND `completed_on` = " . DB::escape(EMPTY_DATETIME) . " AND `due_date` <= '$now_end'"; break; case 20: // Actives task by current user $task_status_condition = " AND `completed_on` = " . DB::escape(EMPTY_DATETIME) . " AND `start_date` <= '$now' AND `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 `completed_on` = " . DB::escape(EMPTY_DATETIME) . " AND `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"; //Now get the tasks $tasks = ProjectTasks::instance()->listing(array( "extra_conditions" => $conditions, "start" => 0, "limit" => user_config_option('task_display_limit', 501), "count_results" => false, "raw_data" => true, ))->objects; $pendingstr = $status == 0 ? " AND `completed_on` = " . DB::escape(EMPTY_DATETIME) . " " : ""; $milestone_conditions = " AND `is_template` = false " . $pendingstr; //Find all internal milestones for these tasks $internalMilestones = ProjectMilestones::instance()->listing(array("extra_conditions" => $milestone_conditions))->objects; //Find all external milestones for these tasks, external milestones are the ones that belong to a parent member and have tasks in the current member $milestone_ids = array(); if($tasks){ $task_ids = array(); foreach ($tasks as $task){ $task_ids[] = $task['id']; if ($task['milestone_id'] != 0) { $milestone_ids[$task['milestone_id']] = $task['milestone_id']; } } // generate request cache ObjectMembers::instance()->getCachedObjectMembers(0, $task_ids); ProjectTasks::instance()->findByRelatedCached(0, $task_ids); } $int_milestone_ids = array(); foreach($internalMilestones as $milestone) { $int_milestone_ids[] = $milestone->getId(); } $milestone_ids = array_diff($milestone_ids, $int_milestone_ids); if (count($milestone_ids) == 0) $milestone_ids[] = 0; $ext_milestone_conditions = " `is_template` = false " . $pendingstr . ' AND `object_id` IN (' . implode(',',$milestone_ids) . ')'; $externalMilestones = ProjectMilestones::findAll(array('conditions' => $ext_milestone_conditions)); // Get Users Info $users = allowed_users_in_context(ProjectTasks::instance()->getObjectTypeId(), active_context(), ACCESS_LEVEL_READ); $allUsers = Contacts::getAllUsers(); $user_ids = array(-1); foreach ($allUsers as $user) { $user_ids[] = $user->getId(); } // only companies with users $companies = Contacts::findAll(array( "conditions" => "e.is_company = 1", "join" => array( "table" => Contacts::instance()->getTableName(), "jt_field" => "object_id", "j_sub_q" => "SELECT xx.object_id FROM ".Contacts::instance()->getTableName(true)." xx WHERE xx.is_company=0 AND xx.company_id = e.object_id AND xx.object_id IN (".implode(",", $user_ids).") LIMIT 1" ) )); tpl_assign('tasks', $tasks); if (config_option('use tasks dependencies')) { $dependency_count = array(); foreach ($tasks as $task) { $previous = 0; $ptasks = ProjectTaskDependencies::getDependenciesForTask($task['id']); foreach ($ptasks as $pdep) { $ptask = ProjectTasks::findById($pdep->getPreviousTaskId()); if ($ptask instanceof ProjectTask && !$ptask->isCompleted()) $previous++; } $dependants = ProjectTaskDependencies::getDependantsForTask($task['id']); $dep_csv = ""; foreach ($dependants as $dep) $dep_csv .= ($dep_csv==""?"":",") . $dep->getTaskId(); $dependency_count[] = array('id' => $task['id'], 'count' => $previous, 'dependants' => $dep_csv); } tpl_assign('dependency_count', $dependency_count); } if (!$isJson){ $all_templates = COTemplates::findAll(array('conditions' => '`trashed_by_id` = 0 AND `archived_by_id` = 0')); tpl_assign('all_templates', $all_templates); if (user_config_option('task_display_limit') > 0 && count($tasks) > user_config_option('task_display_limit')) { tpl_assign('displayTooManyTasks', true); array_pop($tasks); } tpl_assign('object_subtypes',array()); tpl_assign('internalMilestones', $internalMilestones); tpl_assign('externalMilestones', $externalMilestones); tpl_assign('users', $users); tpl_assign('allUsers', $allUsers); tpl_assign('companies', $companies); $userPref = array(); $userPref = array( 'filterValue' => isset($filter_value) ? $filter_value : '', 'filter' => $filter, 'status' => $status, 'showWorkspaces' => user_config_option('tasksShowWorkspaces',1), 'showTime' => user_config_option('tasksShowTime'), 'showDates' => user_config_option('tasksShowDates'), 'showTags' => user_config_option('tasksShowTags',0), 'showEmptyMilestones' => user_config_option('tasksShowEmptyMilestones',1), 'showTimeEstimates' => user_config_option('tasksShowTimeEstimates',1), 'groupBy' => user_config_option('tasksGroupBy'), 'orderBy' => user_config_option('tasksOrderBy'), 'defaultNotifyValue' => user_config_option('can notify from quick add'), ); hook::fire('tasks_user_preferences', null, $userPref); tpl_assign('userPreferences', $userPref); ajx_set_no_toolbar(true); } }
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; }
function change_invitation_state($attendance = null, $event_id = null, $user_id = null) { $from_post_get = $attendance == null || $event_id == null; // Take variables from post if ($attendance == null) { $attendance = array_var($_POST, 'event_attendance'); } if ($event_id == null) { $event_id = array_var($_POST, 'event_id'); } if ($user_id == null) { $user_id = array_var($_POST, 'user_id'); } // If post is empty, take variables from get if ($attendance == null) { $attendance = array_var($_GET, 'at'); } if ($event_id == null) { $event_id = array_var($_GET, 'e'); } if ($user_id == null) { $user_id = array_var($_GET, 'u'); } $silent = array_var($_REQUEST, 'silent'); if ($attendance == null || $event_id == null) { flash_error('Missing parameters'); ajx_current("back"); } else { $conditions = array('conditions' => "`event_id` = " . DB::escape($event_id) . " AND `contact_id` = " . DB::escape($user_id)); $inv = EventInvitations::findOne($conditions); $conditions_all = array('conditions' => "`event_id` = " . DB::escape($event_id)); $invs = EventInvitations::findAll($conditions_all); if ($inv != null) { if (!SystemPermissions::userHasSystemPermission(logged_user(), 'can_update_other_users_invitations') && $inv->getContactId() != logged_user()->getId()) { flash_error(lang('no access permissions')); self::view_calendar(); return; } try { DB::beginWork(); $inv->setInvitationState($attendance); $inv->save(); DB::commit(); } catch (Exception $e) { DB::rollback(); flash_error($e->getMessage()); ajx_current("empty"); return; } } if ($from_post_get) { // Notify creator (only when invitation is accepted or declined) $event = ProjectEvents::findById(array('id' => $event_id)); if ($inv->getInvitationState() == 1 || $inv->getInvitationState() == 2) { $user = Contacts::findById(array('id' => $user_id)); session_commit(); Notifier::notifEventAssistance($event, $inv, $user, $invs); if (!$silent) { if ($inv->getInvitationState() == 1) { flash_success(lang('invitation accepted')); } else { flash_success(lang('invitation rejected')); } } } else { if (!$silent) { flash_success(lang('success edit event', $event instanceof ProjectEvent ? clean($event->getObjectName()) : '')); } } if (array_var($_GET, 'at')) { self::view_calendar(); } else { if (!$silent) { ajx_current("reload"); } else { ajx_current("empty"); } } } } }
static function getOverdueAndUpcomingObjects($limit = null) { $conditions_tasks = " AND is_template = 0 AND `e`.`completed_by_id` = 0 AND `e`.`due_date` > 0"; $conditions_milestones = " AND is_template = 0 AND `e`.`completed_by_id` = 0 AND `e`.`due_date` > 0"; if (!SystemPermissions::userHasSystemPermission(logged_user(), 'can_see_assigned_to_other_tasks')) { $conditions_tasks .= " AND assigned_to_contact_id = ".logged_user()->getId(); } $tasks_result = self::instance()->listing(array( "limit" => $limit, "extra_conditions" => $conditions_tasks, "order"=> array('due_date', 'priority'), "order_dir" => "ASC" )); $tasks = $tasks_result->objects; $milestones_result = ProjectMilestones::instance()->listing(array( "limit" => $limit, "extra_conditions" => $conditions_milestones, "order" => array('due_date'), "order_dir" => "ASC" )); $milestones = $milestones_result->objects; $ordered = array(); foreach ($tasks as $task) { /* @var $task ProjectTask */ if (!$task->isCompleted() && $task->getDueDate() instanceof DateTimeValue ) { if (!isset($ordered[$task->getDueDate()->getTimestamp()])){ $ordered[$task->getDueDate()->getTimestamp()] = array(); } $ordered[$task->getDueDate()->getTimestamp()][] = $task; } } foreach ($milestones as $milestone) { if (!isset($ordered[$milestone->getDueDate()->getTimestamp()])) { $ordered[$milestone->getDueDate()->getTimestamp()] = array(); } $ordered[$milestone->getDueDate()->getTimestamp()][] = $milestone; } ksort($ordered, SORT_NUMERIC); $ordered_flat = array(); foreach ($ordered as $k => $values) { foreach ($values as $v) $ordered_flat[] = $v; } return $ordered_flat; }
function general_search() { // Init vars $search_dimension = array_var($_GET, 'search_dimension'); $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\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)"; } $search_string = trim(array_var($_REQUEST, 'query', '')); $search_string = mysql_real_escape_string($search_string, DB::connection()->getLink()); $start = array_var($_REQUEST, 'start', 0); $orig_limit = array_var($_REQUEST, 'limit'); $limit = $orig_limit + 1; $useLike = false; if (user_config_option("search_engine") == 'like') { $useLike = true; } if (strlen($search_string) < 4) { $useLike = true; } if (strlen($search_string) > 0) { $this->search_for = $search_string; $logged_user_pgs = implode(',', logged_user()->getPermissionGroupIds()); $sql = "\r\n\t\t\tSELECT DISTINCT so.rel_object_id AS id, so.content AS text_match, so.column_name AS field_match\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\t\t\t WHERE\to.id = so.rel_object_id AND (\r\n\t\t\t\t\t\t\t (o.object_type_id = {$revisionObjectTypeId} AND\r\n\t\t\t\t\t\t\t EXISTS (\r\n\t\t\t\t\t\t\t SELECT 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 ({$logged_user_pgs})\r\n\t\t\t\t\t\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\tOR (\r\n\t\t\t\t\t\t\t\t\t\t\t\t(EXISTS\r\n\t\t\t\t\t\t\t\t\t\t\t\t(SELECT object_id\r\n\t\t\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\t{$logged_user_pgs}\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\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\t\t\t\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\tGROUP BY(id)\t\r\n\t\t\t\t\t\tORDER BY(id) DESC\t\t\t\t\t\t\t\r\n\t\t\t\t\t\tLIMIT {$start}, {$limit}"; $rows = DB::executeAll($sql); if (!is_array($rows)) { $rows = array(); } // show more $show_more = false; if (count($rows) > $orig_limit) { array_pop($rows); $show_more = true; } if ($show_more) { ajx_extra_data(array('show_more' => $show_more)); } $search_results = array(); $object_ids = array(); foreach ($rows as $ob_data) { // basic data $data = array('id' => $ob_data['id'], 'text_match' => $this->highlightOneResult($ob_data['text_match']), 'field_match' => $ob_data['field_match']); $object_ids[] = $ob_data['id']; $search_results[] = $data; } if (count($object_ids) > 0) { $result = ContentDataObjects::listing(array("extra_conditions" => " AND o.id IN (" . implode(",", $object_ids) . ") ", "include_deleted" => true)); $objects = $result->objects; foreach ($objects as $object) { foreach ($search_results as $key => $search_result) { if ($search_result['id'] == $object->getId()) { $search_results[$key]['name'] = $object->getObjectName(); $class = 'ico-' . $object->getObjectTypeName(); $search_results[$key]['iconCls'] = $class; $search_results[$key]['url'] = $object->getViewUrl(); continue; } } } } $row = "search-result-row-medium"; ajx_extra_data(array('row_class' => $row)); ajx_extra_data(array('search_results' => $search_results)); } ajx_current("empty"); }
} // if $otherInvitationsTable = ''; if (!$event->isNew()) { $otherInvitations = EventInvitations::findAll(array('conditions' => 'event_id = ' . $event->getId())); if (isset($otherInvitations) && is_array($otherInvitations)) { $otherInvitationsTable .= '<div class="coInputMainBlock adminMainBlock" style="width:70%;">'; $otherInvitationsTable .= '<table style="width:100%;"><col width="50%" /><col width="50%" />'; $otherInvitationsTable .= '<tr><th><b>' . lang('name') . '</b></th><th><b>' . lang('participate') . '</b></th></tr>'; $isAlt = false; $cant = 0; foreach ($otherInvitations as $inv) { $inv_user = Contacts::findById($inv->getContactId()); if ($inv_user instanceof Contact) { if (can_access($inv_user, $event->getMembers(), ProjectEvents::instance()->getObjectTypeId(), ACCESS_LEVEL_READ)) { if (!SystemPermissions::userHasSystemPermission(logged_user(), 'can_update_other_users_invitations')) { // only show status $state_desc = lang('pending response'); if ($inv->getInvitationState() == 1) { $state_desc = lang('yes'); } else { if ($inv->getInvitationState() == 2) { $state_desc = lang('no'); } else { if ($inv->getInvitationState() == 3) { $state_desc = lang('maybe'); } } } $otherInvitationsTable .= '<tr' . ($isAlt ? ' class="altRow"' : '') . '><td>' . clean($inv_user->getObjectName()) . '</td><td>' . $state_desc . '</td></tr>'; } else {
/** * Return true if $user can view this task lists * * @param Contact $user * @return boolean */ function canView(Contact $user) { $other_perm_conditions = SystemPermissions::userHasSystemPermission($user, 'can_see_assigned_to_other_tasks') || $this->getAssignedToContactId() == $user->getId(); return can_read($user, $this->getMembers(), $this->getObjectTypeId()) && $other_perm_conditions; }