function hasReferences() { $id = $this->getId(); //Check for objects in Person Member $objects_in_person_member_count = 0; if (Plugins::instance()->isActivePlugin('core_dimensions')) { $persons_dim = Dimensions::findByCode('feng_persons'); $members = Members::findByObjectId($this->getId(), $persons_dim->getId()); $member_ids = array(); foreach ($members as $member) { $member_ids[] = $member->getId(); } $objects_in_person_member_count = ObjectMembers::count("`member_id` IN (" . implode(",", $member_ids) . ") AND object_id <> {$id} "); } if ($objects_in_person_member_count > 0) { return true; } // Check form linked objects $linked_obj_references_count = LinkedObjects::count("`created_by_id` = {$id}"); if ($linked_obj_references_count > 0) { return true; } // Check direct references $references = DB::executeAll("SELECT id FROM " . TABLE_PREFIX . "objects WHERE `created_by_id` = {$id} OR `updated_by_id` = {$id} OR `trashed_by_id` = {$id} OR `archived_by_id` = {$id} limit 1"); if (count($references) > 0) { return true; } return false; }
/** * Removes the object from those members where the user can see the object(and its corresponding parents) * */ static function removeObjectFromMembers(ContentDataObject $object, Contact $contact, $context_members, $members_to_remove = null, $check_permissions = true) { if (is_null($members_to_remove)) { $member_ids = array_flat(DB::executeAll("SELECT om.member_id FROM " . TABLE_PREFIX . "object_members om\r\n \t\t\t\t\t\tINNER JOIN " . TABLE_PREFIX . "members m ON m.id=om.member_id\r\n \t\t\t\t\t\tINNER JOIN " . TABLE_PREFIX . "dimensions d On d.id=m.dimension_id \r\n \t\t\t\t\t\tWHERE d.is_manageable=1 AND om.object_id = " . $object->getId())); } else { $member_ids = $members_to_remove; } $memebers_deleted_ids = array(); foreach ($member_ids as $id) { $member = Members::findById($id); if (!$member instanceof Member) { continue; } if ($check_permissions) { //can write this object type in the member $can_write = $object->canAddToMember($contact, $member, $context_members); } else { $can_write = true; } if ($can_write) { $om = self::findById(array('object_id' => $object->getId(), 'member_id' => $id)); if ($om instanceof ObjectMember) { $om->delete(); $memebers_deleted_ids[] = $id; } $stop = false; while ($member->getParentMember() != null && !$stop) { $member = $member->getParentMember(); $obj_member = ObjectMembers::findOne(array("conditions" => array("`object_id` = ? AND `member_id` = ? AND \r\n\t\t\t\t\t\t\t\t\t`is_optimization` = 1", $object->getId(), $member->getId()))); if (!is_null($obj_member)) { $obj_member->delete(); } else { $stop = true; } } } } return $memebers_deleted_ids; }
/** * Removes the object from those members where the user can see the object(and its corresponding parents) * */ static function removeObjectFromMembers(ContentDataObject $object, Contact $contact, $context_members, $members_to_remove = null){ if (is_null($members_to_remove)) { $member_ids = array_flat(DB::executeAll("SELECT member_id FROM ".TABLE_PREFIX."object_members WHERE object_id = " . $object->getId())); } else { $member_ids = $members_to_remove; } foreach($member_ids as $id){ $member = Members::findById($id); if (!$member instanceof Member) continue; //can write this object type in the member $can_write = $object->canAddToMember($contact, $member, $context_members); if ($can_write){ $om = self::findById(array('object_id' => $object->getId(), 'member_id' => $id)); if ($om instanceof ObjectMember) { $om->delete(); } $stop = false; while ($member->getParentMember() != null && !$stop){ $member = $member->getParentMember(); $obj_member = ObjectMembers::findOne(array("conditions" => array("`object_id` = ? AND `member_id` = ? AND `is_optimization` = 1", $object->getId(),$member->getId()))); if (!is_null($obj_member)) { $obj_member->delete(); } else $stop = true; } } } }
/** * Removes the object from those members where the user can see the object(and its corresponding parents) * */ static function removeObjectFromMembers(ContentDataObject $object, Contact $contact, $context_members) { $object_type_id = $object->getObjectTypeId(); $member_ids = self::getMemberIdsbyObject($object->getId()); foreach ($member_ids as $id) { $member = Members::findById($id); //can write this object type in the member $can_write = $object->canAddToMember($contact, $member, $context_members); if ($can_write) { $om = self::findById(array('object_id' => $object->getId(), 'member_id' => $id)); $om->delete(); $stop = false; while ($member->getParentMember() != null && !$stop) { $member = $member->getParentMember(); $obj_member = ObjectMembers::findOne(array("conditions" => array("`object_id` = ? AND `member_id` = ? AND \n\t\t\t\t\t\t\t\t\t`is_optimization` = 1", $object->getId(), $member->getId()))); if (!is_null($obj_member)) { $obj_member->delete(); } else { $stop = true; } } } } }
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); } }
/** * 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; }
<?php chdir(dirname(__FILE__)); header("Content-type: text/plain"); define("CONSOLE_MODE", true); include "init.php"; Env::useHelper('format'); define('SCRIPT_MEMORY_LIMIT', 1024 * 1024 * 1024); // 1 GB @set_time_limit(0); ini_set('memory_limit', SCRIPT_MEMORY_LIMIT / (1024 * 1024) + 50 . 'M'); $i = 0; $objects_ids = Objects::instance()->findAll(array('columns' => array('id'), 'id' => true)); //,'conditions' => 'object_type_id = 6' echo "\nObjects to process: " . count($objects_ids) . "\n-----------------------------------------------------------------"; foreach ($objects_ids as $object_id) { $object = Objects::findObject($object_id); $i++; if ($object instanceof ContentDataObject) { $members = $object->getMembers(); DB::execute("DELETE FROM " . TABLE_PREFIX . "object_members WHERE object_id = " . $object->getId() . " AND is_optimization = 1;"); ObjectMembers::addObjectToMembers($object->getId(), $members); } else { // } if ($i % 100 == 0) { echo "\n{$i} objects processed. Mem usage: " . format_filesize(memory_get_usage(true)); } }
/** * Used for Drag & Drop, adds objects to a member * @author alvaro */ function add_objects_to_member() { $ids = json_decode(array_var($_POST, 'objects')); $mem_id = array_var($_POST, 'member'); if (!is_array($ids) || count($ids) == 0) { ajx_current("empty"); return; } try { DB::beginWork(); if ($mem_id) { $user_ids = array(); $member = Members::findById($mem_id); $objects = array(); $from = array(); foreach ($ids as $oid) { /* @var $obj ContentDataObject */ $obj = Objects::findObject($oid); if ($obj instanceof ContentDataObject && $obj->canAddToMember(logged_user(), $member, active_context())) { $dim_obj_type_content = DimensionObjectTypeContents::findOne(array('conditions' => array('`dimension_id`=? AND `dimension_object_type_id`=? AND `content_object_type_id`=?', $member->getDimensionId(), $member->getObjectTypeId(), $obj->getObjectTypeId()))); if (!$dim_obj_type_content instanceof DimensionObjectTypeContent) { continue; } if (!$dim_obj_type_content->getIsMultiple() || array_var($_POST, 'remove_prev')) { $db_res = DB::execute("SELECT group_concat(om.member_id) as old_members FROM " . TABLE_PREFIX . "object_members om INNER JOIN " . TABLE_PREFIX . "members m ON om.member_id=m.id WHERE m.dimension_id=" . $member->getDimensionId() . " AND om.object_id=" . $obj->getId()); $row = $db_res->fetchRow(); if (array_var($row, 'old_members') != "") { $from[$obj->getId()] = $row['old_members']; } // remove from previous members ObjectMembers::delete('`object_id` = ' . $obj->getId() . ' AND `member_id` IN (SELECT `m`.`id` FROM `' . TABLE_PREFIX . 'members` `m` WHERE `m`.`dimension_id` = ' . $member->getDimensionId() . ')'); } $obj->addToMembers(array($member)); $obj->addToSharingTable(); $objects[] = $obj; if (Plugins::instance()->isActivePlugin('mail') && $obj instanceof MailContent) { $conversation = MailContents::getMailsFromConversation($obj); foreach ($conversation as $conv_email) { if (array_var($_POST, 'attachment') && $conv_email->getHasAttachments()) { MailUtilities::parseMail($conv_email->getContent(), $decoded, $parsedEmail, $warnings); $classification_data = array(); for ($j = 0; $j < count(array_var($parsedEmail, "Attachments", array())); $j++) { $classification_data["att_" . $j] = true; } MailController::classifyFile($classification_data, $conv_email, $parsedEmail, array($member), array_var($_POST, 'remove_prev'), false); } } } // if object is contact ask to add default permissions in member if ($obj instanceof Contact && $obj->isUser() && can_manage_security(logged_user())) { $user_ids[] = $obj->getId(); } } else { throw new Exception(lang('you dont have permissions to classify object in member', $obj->getName(), $member->getName())); } } // if object is contact ask to add default permissions in member if (can_manage_security(logged_user()) && count($user_ids) > 0 && $member->getDimension()->getDefinesPermissions()) { evt_add('ask to assign default permissions', array('user_ids' => $user_ids, 'member' => array('id' => $member->getId(), 'name' => clean($member->getName())), '')); } Hook::fire('after_dragdrop_classify', $objects, $member); $display_name = $member->getName(); $lang_key = count($ids) > 1 ? 'objects moved to member success' : 'object moved to member success'; $log_datas = array(); $actions = array(); // add to application logs foreach ($objects as $obj) { $actions[$obj->getId()] = array_var($from, $obj->getId()) ? ApplicationLogs::ACTION_MOVE : ApplicationLogs::ACTION_COPY; $log_datas[$obj->getId()] = (array_var($from, $obj->getId()) ? "from:" . array_var($from, $obj->getId()) . ";" : "") . "to:" . $member->getId(); } } else { if ($dim_id = array_var($_POST, 'dimension')) { $dimension = Dimensions::getDimensionById($dim_id); $from = array(); foreach ($ids as $oid) { /* @var $obj ContentDataObject */ $obj = Objects::findObject($oid); if ($obj instanceof ContentDataObject) { $db_res = DB::execute("SELECT group_concat(om.member_id) as old_members FROM " . TABLE_PREFIX . "object_members om INNER JOIN " . TABLE_PREFIX . "members m ON om.member_id=m.id WHERE m.dimension_id=" . $dim_id . " AND om.object_id=" . $obj->getId()); $row = $db_res->fetchRow(); if (array_var($row, 'old_members') != "") { $from[$obj->getId()] = $row['old_members']; } // remove from previous members ObjectMembers::delete('`object_id` = ' . $obj->getId() . ' AND `member_id` IN ( SELECT `m`.`id` FROM `' . TABLE_PREFIX . 'members` `m` WHERE `m`.`dimension_id` = ' . $dim_id . ')'); } $obj->addToMembers(array()); $obj->addToSharingTable(); $objects[] = $obj; } $display_name = $dimension->getName(); $lang_key = count($ids) > 1 ? 'objects removed from' : 'object removed from'; $log_datas = array(); $actions = array(); // add to application logs foreach ($objects as $obj) { $actions[$obj->getId()] = array_var($from, $obj->getId()) ? ApplicationLogs::ACTION_MOVE : ApplicationLogs::ACTION_COPY; $log_datas[$obj->getId()] = array_var($from, $obj->getId()) ? "from:" . array_var($from, $obj->getId()) . ";" : ""; } } } DB::commit(); foreach ($objects as $object) { ApplicationLogs::instance()->createLog($object, $actions[$object->getId()], false, true, true, $log_datas[$object->getId()]); } flash_success(lang($lang_key, $display_name)); if (array_var($_POST, 'reload')) { ajx_current('reload'); } else { ajx_current('empty'); } } catch (Exception $e) { DB::rollback(); ajx_current("empty"); flash_error($e->getMessage()); } }
function makeDimensionGroups($objects, $dimension_id, &$parent_group = null) { // key = member_id - values = subset of objects or subgroups $groups = array(); $grouped_objects = array(); $max_level = 0; foreach ($objects as $object) { $object_id = $object instanceof Timeslot && $object->getColumnValue('rel_object_id') > 0 ? $object->getRelObjectId() : $object->getId(); $members = ObjectMembers::getMembersByObjectAndDimension($object_id, $dimension_id, "AND om.is_optimization = 0"); if (is_array($members) && count($members) > 0) { $member = $members[0]; $all_parents = array_reverse($member->getAllParentMembersInHierarchy(true)); $all_p_keys = ""; foreach ($all_parents as $p_member) { $all_p_keys .= ($all_p_keys == "" ? "" : "_") . $p_member->getId(); $new_group = array('group' => array('id' => $p_member->getId(), 'name' => $p_member->getName(), 'pid' => $p_member->getParentMemberId(), 'type' => $p_member->getObjectTypeId(), 'obj' => $p_member->getObjectId()), 'subgroups' => array()); $level = $p_member->getDepth(); $max_level = $level > $max_level ? $level : $max_level; if (isset($groups[$level]) && isset($groups[$level][$p_member->getId()])) { $new_group = $groups[$level][$p_member->getId()]; } if (!isset($groups[$level])) { $groups[$level] = array($p_member->getId() => $new_group); } else { if (!isset($groups[$level][$p_member->getId()])) { $groups[$level][$p_member->getId()] = $new_group; } } if ($p_member->getId() == $member->getId()) { if (!isset($grouped_objects[$all_p_keys])) { $grouped_objects[$all_p_keys] = array($object); } else { $grouped_objects[$all_p_keys][] = $object; } } } } } $i = $max_level; while ($i > 1) { foreach ($groups[$i] as $member_id => $gp) { $member = $gp['group']; $pid = $member['pid']; if (isset($groups[$i - 1][$pid])) { $groups[$i - 1][$pid]['subgroups'][$member_id] = $gp; } } $i--; } foreach ($groups as $level => $value) { if ($level > 1) { unset($groups[$level]); } } if ($parent_group != null && isset($groups[1])) { foreach ($groups[1] as $mid => $group) { $parent_group['subgroups'][$mid] = $group; } } return array('groups' => isset($groups[1]) ? $groups[1] : array(), 'grouped_objects' => $grouped_objects); }
function new_list_tasks() { //load config options into cache for better performance load_user_config_options_by_category_name('task panel'); $isJson = array_var($_GET, 'isJson', false); if ($isJson) { ajx_current("empty"); } $request_conditions = $this->get_tasks_request_conditions(); $conditions = $request_conditions['conditions']; $filter_value = $request_conditions['filterValue']; $filter = $request_conditions['filter']; $status = $request_conditions['status']; $tasks = array(); $pendingstr = $status == 0 ? " AND `e`.`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(); $task_ids = array(); if ($tasks) { 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); } $cp_values = array(); if (count($task_ids) > 0) { $cp_rows = DB::executeAll("SELECT * FROM " . TABLE_PREFIX . "custom_property_values WHERE object_id IN (" . implode(',', $task_ids) . ")"); if (is_array($cp_rows)) { foreach ($cp_rows as $row) { if (!isset($cp_values[$row['object_id']])) { $cp_values[$row['object_id']] = array(); } if (!isset($cp_values[$row['object_id']][$row['custom_property_id']])) { $cp_values[$row['object_id']][$row['custom_property_id']] = array(); } $cp_values[$row['object_id']][$row['custom_property_id']][] = $row['value']; } } } tpl_assign('cp_values', $cp_values); $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 if (logged_user()->isGuest()) { $users = array(logged_user()); } else { $users = allowed_users_in_context(ProjectTasks::instance()->getObjectTypeId(), active_context(), ACCESS_LEVEL_READ, '', true); } $allUsers = Contacts::getAllUsers(null, true); $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 \r\n\t\t\t\t\txx.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 (!$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); if (strtotime(user_config_option('tasksDateStart'))) { //this return null if date is 0000-00-00 00:00:00 $dateStart = new DateTime('@' . strtotime(user_config_option('tasksDateStart'))); $dateStart = $dateStart->format(user_config_option('date_format')); } else { $dateStart = ''; } if (strtotime(user_config_option('tasksDateEnd'))) { //this return null if date is 0000-00-00 00:00:00 $dateEnd = new DateTime('@' . strtotime(user_config_option('tasksDateEnd'))); $dateEnd = $dateEnd->format(user_config_option('date_format')); } else { $dateEnd = ''; } $userPref = array(); $showDimensionCols = array_map('intval', explode(',', user_config_option('tasksShowDimensionCols'))); $userPref = array('filterValue' => isset($filter_value) ? $filter_value : '', 'filter' => $filter, 'dateStart' => $dateStart, 'dateEnd' => $dateEnd, 'status' => $status, 'showTime' => user_config_option('tasksShowTime'), 'showDates' => user_config_option('tasksShowDates'), 'showStartDates' => user_config_option('tasksShowStartDates'), 'showEndDates' => user_config_option('tasksShowEndDates'), 'showBy' => user_config_option('tasksShowAssignedBy'), 'showClassification' => user_config_option('tasksShowClassification'), 'showSubtasksStructure' => user_config_option('tasksShowSubtasksStructure'), 'showTags' => user_config_option('tasksShowTags', 0), 'showEmptyMilestones' => user_config_option('tasksShowEmptyMilestones', 1), 'showTimeEstimates' => user_config_option('tasksShowTimeEstimates', 1), 'showTimePending' => user_config_option('tasksShowTimePending', 1), 'showTimeWorked' => user_config_option('tasksShowTimeWorked', 1), 'showPercentCompletedBar' => user_config_option('tasksShowPercentCompletedBar', 1), 'showQuickEdit' => user_config_option('tasksShowQuickEdit', 1), 'showQuickComplete' => user_config_option('tasksShowQuickComplete', 1), 'showQuickComment' => user_config_option('tasksShowQuickComment', 1), 'showQuickAddSubTasks' => user_config_option('tasksShowQuickAddSubTasks', 1), 'showDimensionCols' => $showDimensionCols, 'groupBy' => user_config_option('tasksGroupBy'), 'orderBy' => user_config_option('tasksOrderBy'), 'previousPendingTasks' => user_config_option('tasksPreviousPendingTasks', 1), 'defaultNotifyValue' => user_config_option('can notify from quick add')); hook::fire('tasks_user_preferences', null, $userPref); tpl_assign('userPreferences', $userPref); tpl_assign('userPermissions', array('can_add' => ProjectTask::canAdd(logged_user(), active_context()) ? 1 : 0)); ajx_set_no_toolbar(true); } }
/** * Returns an array with the members that this object belongs to * */ function getMembers() { if ( is_null($this->members) ) { $this->members = ObjectMembers::getMembersByObject($this->getRelObjectId() > 0 ? $this->getRelObjectId() : $this->getId()); } return $this->members ; }
function getMembersToDisplayPath() { $members_info = array(); $member_ids = ObjectMembers::getMemberIdsByObject($this->getId()); if (count($member_ids) == 0) { $member_ids[] = 0; } $db_res = DB::execute("SELECT id, name, dimension_id, object_type_id FROM " . TABLE_PREFIX . "members WHERE id IN (" . implode(",", $member_ids) . ")"); $members = $db_res->fetchAll(); $dimension_options = array(); if (count($members) > 0) { foreach ($members as $mem) { $options = Dimensions::getDimensionById($mem['dimension_id'])->getOptions(true); if (isset($options->showInPaths) && $options->showInPaths) { if (!isset($members_info[$mem['dimension_id']])) { $members_info[$mem['dimension_id']] = array(); } $members_info[$mem['dimension_id']][$mem['id']] = array('ot' => $mem['object_type_id'], 'c' => Members::findById($mem['id'])->getMemberColor(), 'name' => $mem['name']); } } } return $members_info; }
function classifyFile($classification_data, $email, $parsedEmail, $members, $remove_prev) { if (!is_array($classification_data)) $classification_data = array(); if (!isset($parsedEmail["Attachments"])) { return; //throw new Exception(lang('no attachments found for email')); } $account_owner = logged_user() instanceof contact ? logged_user() : Contacts::findById($email->getAccount()->getContactId()); for ($c = 0; $c < count($classification_data); $c++) { if (isset($classification_data["att_".$c]) && $classification_data["att_".$c]) { $att = $parsedEmail["Attachments"][$c]; $fName = str_starts_with($att["FileName"], "=?") ? iconv_mime_decode($att["FileName"], 0, "UTF-8") : utf8_safe($att["FileName"]); if (trim($fName) == "" && strlen($att["FileName"]) > 0) $fName = utf8_encode($att["FileName"]); $extension = get_file_extension(basename($fName)); $type_file_allow = FileTypes::getByExtension($extension); if(!($type_file_allow instanceof FileType) || $type_file_allow->getIsAllow() == 1){ try { //$sql = "SELECT o.id FROM ".TABLE_PREFIX."objects o,".TABLE_PREFIX."project_files f WHERE o.id = f.object_id AND f.mail_id = ".$email->getId()." AND o.name = ".DB::escape($fName).""; $sql = "SELECT o.id FROM ".TABLE_PREFIX."objects o,".TABLE_PREFIX."project_files f WHERE o.id = f.object_id AND o.name = ".DB::escape($fName).""; $db_res = DB::execute($sql); $row = $db_res->fetchRow(); $file = ProjectFiles::findById($row['id']); DB::beginWork(); if ($file == null){ $fileIsNew = true; $file = new ProjectFile(); $file->setFilename($fName); $file->setIsVisible(true); $file->setMailId($email->getId()); $file->save(); $object_controller = new ObjectController(); $object_controller->add_to_members($file, array(), $account_owner); } else { $fileIsNew = false; } if($remove_prev){ $dim_ids = array(0); foreach ($members as $m) $dim_ids[$m->getDimensionId()] = $m->getDimensionId(); ObjectMembers::delete('`object_id` = ' . $file->getId() . ' AND `member_id` IN (SELECT `m`.`id` FROM `'.TABLE_PREFIX.'members` `m` WHERE `m`.`dimension_id` IN ('.implode(',',$dim_ids).'))'); } $file->addToMembers($members); $file->addToSharingTable(); $enc = array_var($parsedMail,'Encoding','UTF-8'); $ext = utf8_substr($fName, strrpos($fName, '.') + 1, utf8_strlen($fName, $enc), $enc); $mime_type = ''; if (Mime_Types::instance()->has_type($att["content-type"])) { $mime_type = $att["content-type"]; //mime type is listed & valid } else { $mime_type = Mime_Types::instance()->get_type($ext); //Attempt to infer mime type } $userid = logged_user() ? logged_user()->getId() : "0"; $tempFileName = ROOT ."/tmp/". $userid ."x". gen_id(); $fh = fopen($tempFileName, 'w') or die("Can't open file"); fwrite($fh, $att["Data"]); fclose($fh); $fileToSave = array( "name" => $fName, "type" => $mime_type, "tmp_name" => $tempFileName, "error" => 0, "size" => filesize($tempFileName) ); if ($fileIsNew) { $revision = $file->handleUploadedFile($fileToSave, true, lang('attachment from email', $email->getSubject())); // handle uploaded file ApplicationLogs::createLog($file, ApplicationLogs::ACTION_ADD); }else{ $revision = $file->getLastRevision(); $new_hash = hash_file("sha256", $tempFileName); if ($revision->getHash() != $new_hash) { $revision = $file->handleUploadedFile($fileToSave, true, lang('attachment from email', $email->getSubject())); // handle uploaded file ApplicationLogs::createLog($file, ApplicationLogs::ACTION_ADD); } } DB::commit(); // Error... } catch(Exception $e) { DB::rollback(); flash_error($e->getMessage()); ajx_current("empty"); } }else{ flash_error(lang('file extension no allow classify', $fName)); } if (isset($tempFileName) && is_file($tempFileName)) unlink($tempFileName); } } }
/** * This function will return paginated result. Result is an array where first element is * array of returned object and second populated pagination object that can be used for * obtaining and rendering pagination data using various helpers. * * Items and pagination array vars are indexed with 0 for items and 1 for pagination * because you can't use associative indexing with list() construct * * @access public * @param array $arguments Query argumens (@see find()) Limit and offset are ignored! * @param integer $items_per_page Number of items per page * @param integer $current_page Current page number * @return array */ function paginate($arguments = null, $items_per_page = 10, $current_page = 1) { if (isset($this) && instance_of($this, 'ObjectMembers')) { return parent::paginate($arguments, $items_per_page, $current_page); } else { return ObjectMembers::instance()->paginate($arguments, $items_per_page, $current_page); } // if }
function save_permissions($pg_id, $is_guest = false, $permissions_data = null, $save_cmps = true, $update_sharing_table = true, $fire_hook = true, $update_contact_member_cache = true, $users_ids_to_check = array(), $only_member_permissions = false) { if (is_null($permissions_data)) { // system permissions $sys_permissions_data = array_var($_POST, 'sys_perm'); // module permissions $mod_permissions_data = array_var($_POST, 'mod_perm'); // root permissions if ($rp_genid = array_var($_POST, 'root_perm_genid')) { $rp_permissions_data = array(); foreach ($_POST as $name => $value) { if (str_starts_with($name, $rp_genid . 'rg_root_')) { $rp_permissions_data[$name] = $value; } } } // member permissions $permissionsString = array_var($_POST, 'permissions'); } else { // system permissions $sys_permissions_data = array_var($permissions_data, 'sys_perm'); // module permissions $mod_permissions_data = array_var($permissions_data, 'mod_perm'); // root permissions $rp_genid = array_var($permissions_data, 'root_perm_genid'); $rp_permissions_data = array_var($permissions_data, 'root_perm'); // member permissions $permissionsString = array_var($permissions_data, 'permissions'); } try { DB::beginWork(); $changed_members = array(); // save module permissions if (!$only_member_permissions) { try { TabPanelPermissions::clearByPermissionGroup($pg_id, true); if (!is_null($mod_permissions_data) && is_array($mod_permissions_data)) { foreach ($mod_permissions_data as $tab_id => $val) { DB::execute("INSERT INTO " . TABLE_PREFIX . "tab_panel_permissions (permission_group_id,tab_panel_id) VALUES ('{$pg_id}','{$tab_id}') ON DUPLICATE KEY UPDATE permission_group_id=permission_group_id"); } } } catch (Exception $e) { Logger::log("Error saving module permissions for permission group {$pg_id}: " . $e->getMessage() . "\n" . $e->getTraceAsString()); throw $e; } } $root_permissions_sharing_table_delete = array(); $root_permissions_sharing_table_add = array(); if (logged_user() instanceof Contact && can_manage_security(logged_user())) { try { if (!$only_member_permissions) { // save system permissions $system_permissions = SystemPermissions::findById($pg_id); if (!$system_permissions instanceof SystemPermission) { $system_permissions = new SystemPermission(); $system_permissions->setPermissionGroupId($pg_id); } $system_permissions->setAllPermissions(false); $other_permissions = array(); Hook::fire('add_user_permissions', $pg_id, $other_permissions); foreach ($other_permissions as $k => $v) { $system_permissions->setColumnValue($k, false); } // check max permissions for role, in case of modifying user's permissions $role_id = "-1"; $tmp_contact = Contacts::findOne(array('conditions' => 'permission_group_id = ' . $pg_id)); if ($tmp_contact instanceof Contact) { $role_id = $tmp_contact->getUserType(); } $max_role_system_permissions = MaxSystemPermissions::findOne(array('conditions' => 'permission_group_id = ' . $role_id)); if ($max_role_system_permissions instanceof MaxSystemPermission) { foreach ($sys_permissions_data as $col => &$val) { $max_val = $max_role_system_permissions->getColumnValue($col); if (!$max_val) { unset($sys_permissions_data[$col]); } } } // don't allow to write emails for collaborators and guests if ($tmp_contact instanceof Contact) { $user_type_name = $tmp_contact->getUserTypeName(); if (!in_array($user_type_name, array('Super Administrator', 'Administrator', 'Manager', 'Executive'))) { $mail_ot = ObjectTypes::findByName('mail'); if ($mail_ot instanceof ObjectType) { DB::executeAll("UPDATE " . TABLE_PREFIX . "contact_member_permissions SET can_write=0, can_delete=0 WHERE object_type_id=" . $mail_ot->getId() . " AND permission_group_id={$pg_id}"); } } } $sys_permissions_data['can_task_assignee'] = !$is_guest; $system_permissions->setFromAttributes($sys_permissions_data); $system_permissions->setUseOnDuplicateKeyWhenInsert(true); $system_permissions->save(); //object type root permissions $can_have_root_permissions = config_option('let_users_create_objects_in_root') && in_array($user_type_name, array('Super Administrator', 'Administrator', 'Manager', 'Executive')); if ($rp_genid && $can_have_root_permissions) { ContactMemberPermissions::delete("permission_group_id = {$pg_id} AND member_id = 0"); foreach ($rp_permissions_data as $name => $value) { if (str_starts_with($name, $rp_genid . 'rg_root_')) { $rp_ot = substr($name, strrpos($name, '_') + 1); if (is_numeric($rp_ot) && $rp_ot > 0 && $value == 0) { $root_permissions_sharing_table_delete[] = $rp_ot; } if (!is_numeric($rp_ot) || $rp_ot <= 0 || $value < 1) { continue; } $root_permissions_sharing_table_add[] = $rp_ot; // save with member_id = 0 $root_perm_cmp = new ContactMemberPermission(); $root_perm_cmp->setPermissionGroupId($pg_id); $root_perm_cmp->setMemberId('0'); $root_perm_cmp->setObjectTypeId($rp_ot); $root_perm_cmp->setCanWrite($value >= 2); $root_perm_cmp->setCanDelete($value >= 3); $root_perm_cmp->save(); } } } if (!$can_have_root_permissions) { ContactMemberPermissions::delete("permission_group_id = {$pg_id} AND member_id = 0"); $sh_controller = new SharingTableController(); $all_object_type_ids = ObjectTypes::findAll(array('id' => true)); $sh_controller->adjust_root_permissions($pg_id, array('root_permissions_sharing_table_delete' => $all_object_type_ids)); } } } catch (Exception $e) { Logger::log("Error saving system and root permissions for permission group {$pg_id}: " . $e->getMessage() . "\n" . $e->getTraceAsString()); throw $e; } } // set all permissions to read_only if user is guest if ($is_guest) { try { $all_saved_permissions = ContactMemberPermissions::findAll(array("conditions" => "`permission_group_id` = {$pg_id}")); foreach ($all_saved_permissions as $sp) { /* @var $sp ContactMemberPermission */ if ($sp->getCanDelete() || $sp->getCanWrite()) { $sp->setCanDelete(false); $sp->setCanWrite(false); $sp->save(); } } $cdps = ContactDimensionPermissions::findAll(array("conditions" => "`permission_type` = 'allow all'")); foreach ($cdps as $cdp) { $cdp->setPermissionType('check'); $cdp->save(); } } catch (Exception $e) { Logger::log("Error setting guest user permissions to read_only for permission group {$pg_id}: " . $e->getMessage() . "\n" . $e->getTraceAsString()); throw $e; } } // check the status of the changed dimensions to set 'allow_all', 'deny_all' or 'check' try { $dimensions = Dimensions::findAll(array("conditions" => array("`id` IN (SELECT DISTINCT `dimension_id` FROM " . Members::instance()->getTableName(true) . " WHERE `id` IN (?))", $changed_members))); foreach ($dimensions as $dimension) { $dimension->setContactDimensionPermission($pg_id, 'check'); } } catch (Exception $e) { Logger::log("Error setting dimension permissions for permission group {$pg_id}: " . $e->getMessage() . "\n" . $e->getTraceAsString()); throw $e; } //member permissions if ($permissionsString && $permissionsString != '') { $permissions = json_decode($permissionsString); } if (isset($permissions) && !is_null($permissions) && is_array($permissions)) { try { $tmp_contact = Contacts::findOne(array('conditions' => 'permission_group_id = ' . $pg_id)); if ($tmp_contact instanceof Contact) { $user_type_name = $tmp_contact->getUserTypeName(); $role_id = $tmp_contact->getUserType(); $max_role_ot_perms = MaxRoleObjectTypePermissions::instance()->findAll(array('conditions' => "role_id = '{$role_id}'")); } $mail_ot = ObjectTypes::findByName('mail'); $sql_insert_values = ""; $member_object_types_to_delete = array(); $allowed_members_ids = array(); foreach ($permissions as &$perm) { if (!isset($all_perm_deleted[$perm->m])) { $all_perm_deleted[$perm->m] = true; } $allowed_members_ids[$perm->m] = array(); $allowed_members_ids[$perm->m]['pg'] = $pg_id; if ($perm->r) { if (isset($allowed_members_ids[$perm->m]['w'])) { if ($allowed_members_ids[$perm->m]['w'] != 1) { $allowed_members_ids[$perm->m]['w'] = $is_guest ? false : $perm->w; } } else { $allowed_members_ids[$perm->m]['w'] = $is_guest ? false : $perm->w; } if (isset($allowed_members_ids[$perm->m]['d'])) { if ($allowed_members_ids[$perm->m]['d'] != 1) { $allowed_members_ids[$perm->m]['d'] = $is_guest ? false : $perm->d; } } else { $allowed_members_ids[$perm->m]['d'] = $is_guest ? false : $perm->d; } // check max permissions for user type if ($tmp_contact instanceof Contact) { $max_perm = null; foreach ($max_role_ot_perms as $max_role_ot_perm) { if ($max_role_ot_perm->getObjectTypeId() == $perm->o) { $max_perm = $max_role_ot_perm; } } if ($max_perm) { if (!$max_perm->getCanDelete()) { $perm->d = 0; } if (!$max_perm->getCanWrite()) { $perm->w = 0; } } else { $perm->d = 0; $perm->w = 0; $perm->r = 0; } } if ($save_cmps) { // don't allow to write emails for collaborators and guests if ($tmp_contact instanceof Contact && !in_array($user_type_name, array('Super Administrator', 'Administrator', 'Manager', 'Executive'))) { if ($mail_ot instanceof ObjectType && $perm->o == $mail_ot->getId()) { $perm->d = 0; $perm->w = 0; } } $sql_insert_values .= ($sql_insert_values == "" ? "" : ",") . "('" . $pg_id . "','" . $perm->m . "','" . $perm->o . "','" . $perm->d . "','" . $perm->w . "')"; if (!isset($member_object_types_to_delete[$perm->m])) { $member_object_types_to_delete[$perm->m] = array(); } $member_object_types_to_delete[$perm->m][] = $perm->o; } $all_perm_deleted[$perm->m] = false; } else { if (is_numeric($perm->m) && is_numeric($perm->o)) { DB::execute("DELETE FROM " . TABLE_PREFIX . "contact_member_permissions WHERE member_id='" . $perm->m . "' AND object_type_id='" . $perm->o . "' AND permission_group_id={$pg_id}"); } } $changed_members[] = $perm->m; } if ($save_cmps) { if (count($all_perm_deleted) > 0) { $member_ids_to_delete = array(); foreach ($all_perm_deleted as $mid => $del) { // also check in contact_member_permissions $cmps = ContactMemberPermissions::findAll(array('conditions' => 'permission_group_id=' . $pg_id . " AND member_id={$mid}")); if ($del && (!is_array($cmps) || count($cmps) == 0)) { $member_ids_to_delete[] = $mid; } } if (count($member_ids_to_delete) > 0) { DB::execute("DELETE FROM " . TABLE_PREFIX . "contact_member_permissions WHERE member_id IN (" . implode(',', $member_ids_to_delete) . ") AND permission_group_id={$pg_id}"); } } foreach ($member_object_types_to_delete as $mid => $obj_type_ids) { if (count($obj_type_ids) > 0) { DB::execute("DELETE FROM " . TABLE_PREFIX . "contact_member_permissions WHERE member_id={$mid} AND object_type_id IN (" . implode(',', $obj_type_ids) . ") AND permission_group_id={$pg_id}"); } } if ($sql_insert_values != "") { DB::execute("INSERT INTO " . TABLE_PREFIX . "contact_member_permissions (permission_group_id, member_id, object_type_id, can_delete, can_write) VALUES {$sql_insert_values} ON DUPLICATE KEY UPDATE member_id=member_id"); } } } catch (Exception $e) { Logger::log("Error saving member permissions for permission group {$pg_id}: " . $e->getMessage() . "\n" . $e->getTraceAsString()); throw $e; } } DB::commit(); } catch (Exception $e) { Logger::log("Error saving permissions for permission group {$pg_id}: " . $e->getMessage() . "\n" . $e->getTraceAsString()); DB::rollback(); } try { if (isset($permissions) && !is_null($permissions) && is_array($permissions)) { if ($update_sharing_table) { try { $sharingTablecontroller = new SharingTableController(); $rp_info = array('root_permissions_sharing_table_delete' => $root_permissions_sharing_table_delete, 'root_permissions_sharing_table_add' => $root_permissions_sharing_table_add); $sharingTablecontroller->afterPermissionChanged($pg_id, $permissions, $rp_info); } catch (Exception $e) { Logger::log("Error saving permissions to sharing table for permission group {$pg_id}: " . $e->getMessage() . "\n" . $e->getTraceAsString()); throw $e; } } if ($update_contact_member_cache) { try { $contactMemberCacheController = new ContactMemberCacheController(); $group = PermissionGroups::findById($pg_id); $real_group = null; if ($group->getType() == 'user_groups') { $real_group = $group; } $users = $group->getUsers(); $users_ids_checked = array(); foreach ($users as $us) { $users_ids_checked[] = $us->getId(); $contactMemberCacheController->afterUserPermissionChanged($us, $permissions, $real_group); } //check all users related to the group foreach ($users_ids_to_check as $us_id) { if (!in_array($us_id, $users_ids_checked)) { $users_ids_checked[] = $us_id; $us = Contacts::findById($us_id); if ($us instanceof Contact) { $contactMemberCacheController->afterUserPermissionChanged($us, $permissions, $real_group); } } } } catch (Exception $e) { Logger::log("Error saving permissions to contact member cache for permission group {$pg_id}: " . $e->getMessage() . "\n" . $e->getTraceAsString()); throw $e; } } } } catch (Exception $e) { Logger::log("Error saving module permissions for permission group {$pg_id}: " . $e->getMessage() . "\n" . $e->getTraceAsString()); } if ($fire_hook) { Hook::fire('after_save_contact_permissions', $pg_id, $pg_id); } // remove contact object from members where permissions were deleted $user = Contacts::findOne(array('conditions' => 'permission_group_id=' . $pg_id)); if ($user instanceof Contact) { $to_remove = array(); if (isset($all_perm_deleted) && is_array($all_perm_deleted)) { foreach ($all_perm_deleted as $m_id => $must_remove) { if ($must_remove) { $to_remove[] = $m_id; } } ObjectMembers::removeObjectFromMembers($user, logged_user(), null, $to_remove); } } }
/** * Add contact * * @access public * @param void * @return null */ function add() { if (logged_user()->isGuest()) { flash_error(lang('no access permissions')); ajx_current("empty"); return; } $this->setTemplate('edit_contact'); if (array_var($_GET, 'is_user') || array_var(array_var(array_var($_POST, 'contact'), 'user'), 'create-user')) { if (!can_manage_security(logged_user())) { flash_error(lang('no access permissions')); ajx_current("empty"); return; } } else { $notAllowedMember = ''; if (!Contact::canAdd(logged_user(), active_context(), $notAllowedMember)) { if (str_starts_with($notAllowedMember, '-- req dim --')) { flash_error(lang('must choose at least one member of', str_replace_first('-- req dim --', '', $notAllowedMember, $in))); } else { trim($notAllowedMember) == "" ? flash_error(lang('you must select where to keep', lang('the contact'))) : flash_error(lang('no context permissions to add', lang("contacts"), $notAllowedMember)); } ajx_current("empty"); return; } } if (!is_array(array_var($_POST, 'contact'))) { // set layout for modal form if (array_var($_REQUEST, 'modal')) { $this->setLayout("json"); tpl_assign('modal', true); } } $contact = new Contact(); $im_types = ImTypes::findAll(array('order' => '`id`')); $contact_data = array_var($_POST, 'contact'); if (!array_var($contact_data, 'company_id')) { $contact_data['company_id'] = get_id('company_id'); $contact_data['timezone'] = logged_user()->getTimezone(); } $redirect_to = get_url('contact'); // Create contact from mail content, when writing an email... $contact_email = array_var($_GET, 'ce'); if ($contact_email) { $contact_data['email'] = $contact_email; } if (array_var($_GET, 'div_id')) { $contact_data['new_contact_from_mail_div_id'] = array_var($_GET, 'div_id'); $contact_data['hf_contacts'] = array_var($_GET, 'hf_contacts'); } if (!array_var($_GET, 'is_user')) { tpl_assign('contact_mail', true); } else { if (isset($_GET['user_type'])) { tpl_assign('user_type', array_var($_GET, 'user_type')); } tpl_assign('contact_mail', false); } $contact_data['all_phones'] = array(); $contact_data['all_addresses'] = array(); $contact_data['all_webpages'] = array(); $contact_data['all_emails'] = array(); //User From Contact if (array_var($_REQUEST, 'create_user_from_contact')) { $contact_old = Contacts::findById(get_id()); if (!$contact_old instanceof Contact) { flash_error(lang('contact dnx')); ajx_current("empty"); return; } // if if (!$contact_old->canEdit(logged_user())) { flash_error(lang('no access permissions')); ajx_current("empty"); return; } // if if (array_var($_REQUEST, 'create_user_from_contact')) { $contact_data = $this->get_contact_data_from_contact($contact_old); tpl_assign('userFromContactId', get_id()); $contact_old->setNew(true); // to keep custom properties and linked objects tpl_assign('object', $contact_old); } } if (array_var($_REQUEST, 'user_from_contact_id') > 0) { $contact = Contacts::findById(array_var($_REQUEST, 'user_from_contact_id')); } //END User From Contact tpl_assign('contact', $contact); tpl_assign('contact_data', $contact_data); tpl_assign('im_types', $im_types); // telephone types $all_telephone_types = TelephoneTypes::getAllTelephoneTypesInfo(); tpl_assign('all_telephone_types', $all_telephone_types); // address types $all_address_types = AddressTypes::getAllAddressTypesInfo(); tpl_assign('all_address_types', $all_address_types); // webpage types $all_webpage_types = WebpageTypes::getAllWebpageTypesInfo(); tpl_assign('all_webpage_types', $all_webpage_types); // email types $all_email_types = EmailTypes::getAllEmailTypesInfo(); tpl_assign('all_email_types', $all_email_types); // Submit if (is_array(array_var($_POST, 'contact'))) { foreach ($contact_data as $k => &$v) { $v = remove_scripts($v); } ajx_current("empty"); try { //when creating user from contact remove classification from contact first if (array_var($_REQUEST, 'user_from_contact_id') > 0) { $members_to_remove = array_flat(DB::executeAll("SELECT m.id FROM " . TABLE_PREFIX . "members m INNER JOIN " . TABLE_PREFIX . "dimensions d ON d.id=m.dimension_id WHERE d.defines_permissions=1")); $removedMemebersIds = ObjectMembers::removeObjectFromMembers($contact, logged_user(), null, $members_to_remove, false); } DB::beginWork(); $contact_data['email'] = trim($contact_data['email']); $newCompany = false; if (array_var($contact_data, 'isNewCompany') == 'true' && is_array(array_var($_POST, 'company'))) { $company_data = array_var($_POST, 'company'); $company = new Contact(); $company->setFromAttributes($company_data); $company->setIsCompany(true); $company->setObjectName(); $company->save(); // save phones, addresses and webpages $this->save_phones_addresses_webpages($company_data, $company); if ($company_data['email'] != "") { $company->addEmail($company_data['email'], 'work', true); } $newCompany = true; } $contact_data['birthday'] = getDateValue($contact_data["birthday"]); $contact_data['name'] = $contact_data['first_name'] . " " . $contact_data['surname']; $contact->setFromAttributes($contact_data); if ($newCompany) { $contact->setCompanyId($company->getId()); } $contact->setObjectName(); $contact->save(); // save phones, addresses and webpages $this->save_phones_addresses_webpages($contact_data, $contact); // main email if ($contact_data['email'] != "") { $contact->addEmail($contact_data['email'], 'personal', true); } // save additional emails $this->save_non_main_emails($contact_data, $contact); // autodetect timezone $autotimezone = array_var($contact_data, 'autodetect_time_zone', null); if ($autotimezone !== null) { set_user_config_option('autodetect_time_zone', $autotimezone, $contact->getId()); } //link it! $object_controller = new ObjectController(); $member_ids = json_decode(array_var($_POST, 'members')); if (!is_null($member_ids) && !array_var(array_var($contact_data, 'user'), 'create_user')) { $object_controller->add_to_members($contact, $member_ids); } $no_perm_members_ids = json_decode(array_var($_POST, 'no_perm_members')); if (count($no_perm_members_ids)) { $object_controller->add_to_members($contact, $no_perm_members_ids); } if ($newCompany) { $object_controller->add_to_members($company, $member_ids); } $object_controller->link_to_new_object($contact); $object_controller->add_subscribers($contact); $object_controller->add_custom_properties($contact); foreach ($im_types as $im_type) { $value = trim(array_var($contact_data, 'im_' . $im_type->getId())); if ($value != '') { $contact_im_value = new ContactImValue(); $contact_im_value->setContactId($contact->getId()); $contact_im_value->setImTypeId($im_type->getId()); $contact_im_value->setValue($value); $contact_im_value->setIsMain(array_var($contact_data, 'default_im') == $im_type->getId()); $contact_im_value->save(); } // if } // foreach //NEW ! User data in the same form $user = array_var(array_var($_POST, 'contact'), 'user'); if (isset($contact_data['specify_username'])) { if ($contact_data['user']['username'] != "") { $user['username'] = $contact_data['user']['username']; } else { $user['username'] = str_replace(" ", "", strtolower($contact_data['name'])); } } else { $user['username'] = str_replace(" ", "", strtolower($contact_data['name'])); } if (isset($_POST['notify-user'])) { set_user_config_option("sendEmailNotification", 1, logged_user()->getId()); } else { set_user_config_option("sendEmailNotification", 0, logged_user()->getId()); } if ($user) { $user_data = $this->createUserFromContactForm($user, $contact->getId(), $contact_data['email'], isset($_POST['notify-user']), false); // add user groups if (isset($_REQUEST['user_groups'])) { $insert_values = ""; $group_ids = explode(',', $_REQUEST['user_groups']); foreach ($group_ids as $gid) { if (trim($gid) == "" || !is_numeric($gid)) { continue; } $insert_values .= ($insert_values == "" ? "" : ",") . "(" . $contact->getId() . ", {$gid})"; } if ($insert_values != "") { DB::execute("INSERT INTO " . TABLE_PREFIX . "contact_permission_groups VALUES {$insert_values} ON DUPLICATE KEY UPDATE contact_id=contact_id;"); } } if (array_var($contact_data, 'isNewCompany') == 'true' && is_array(array_var($_POST, 'company'))) { ApplicationLogs::createLog($company, ApplicationLogs::ACTION_ADD); } ApplicationLogs::createLog($contact, ApplicationLogs::ACTION_ADD); if (isset($contact_data['new_contact_from_mail_div_id'])) { $combo_val = trim($contact->getFirstName() . ' ' . $contact->getSurname() . ' <' . $contact->getEmailAddress('personal') . '>'); evt_add("contact added from mail", array("div_id" => $contact_data['new_contact_from_mail_div_id'], "combo_val" => $combo_val, "hf_contacts" => $contact_data['hf_contacts'])); } $contact = Contacts::findById($contact->getId()); ContactMemberCaches::updateContactMemberCacheAllMembers($contact); evt_add("new user added", $contact->getArrayInfo()); } $null = null; Hook::fire('after_add_contact', $contact, $null); DB::commit(); // save user permissions if ($user) { DB::beginWork(); $contact = Contacts::findById($contact->getId()); save_user_permissions_background(logged_user(), $contact->getPermissionGroupId(), $contact->isGuest()); DB::commit(); } flash_success(lang('success add contact', $contact->getObjectName())); ajx_current("back"); if (array_var($_REQUEST, 'modal')) { evt_add("reload current panel"); } // Error... } catch (Exception $e) { DB::rollback(); flash_error($e->getMessage()); mark_dao_validation_error_fields($e); return; } // try try { if ($user) { // Send notification send_notification($user_data, $contact->getId()); } } catch (Exception $e) { flash_error($e->getMessage()); } } // if }
/** * End task templates */ function getArrayInfo($full = false) { if (config_option("wysiwyg_tasks")) { if ($this->getTypeContent() == "text") { $desc = nl2br(htmlspecialchars($this->getText())); } else { $desc = purify_html(nl2br($this->getText())); } } else { if ($this->getTypeContent() == "text") { $desc = htmlspecialchars($this->getText()); } else { $desc = html_to_text(html_entity_decode(nl2br($this->getText()), null, "UTF-8")); } } $member_ids = ObjectMembers::instance()->getCachedObjectMembers($this->getId()); $result = array('id' => $this->getId(), 't' => $this->getObjectName(), 'desc' => $desc, 'members' => $member_ids, 'c' => $this->getCreatedOn() instanceof DateTimeValue ? $this->getCreatedOn()->getTimestamp() : 0, 'cid' => $this->getCreatedById(), 'otype' => $this->getObjectSubtype(), 'pc' => $this->getPercentCompleted(), 'memPath' => str_replace('"', "'", escape_character(json_encode($this->getMembersIdsToDisplayPath())))); if ($full) { $result['description'] = $this->getText(); } $result['mas'] = $this->getColumnValue('multi_assignment', 0); if ($this->isCompleted()) { $result['s'] = 1; } if ($this->getParentId() > 0) { $result['pid'] = $this->getParentId(); } //if ($this->getPriority() != 200) $result['pr'] = $this->getPriority(); if ($this->getMilestoneId() > 0) { $result['mid'] = $this->getMilestoneId(); } if ($this->getAssignedToContactId() > 0) { $result['atid'] = $this->getAssignedToContactId(); } $result['atName'] = $this->getAssignedToName(); if ($this->getCompletedById() > 0) { $result['cbid'] = $this->getCompletedById(); $result['con'] = $this->getCompletedOn()->getTimestamp(); } if ($this->getDueDate() instanceof DateTimeValue) { $result['dd'] = $this->getDueDate()->getTimestamp() + logged_user()->getTimezone() * 3600; $result['udt'] = $this->getUseDueTime() ? 1 : 0; } if ($this->getStartDate() instanceof DateTimeValue) { $result['sd'] = $this->getStartDate()->getTimestamp() + logged_user()->getTimezone() * 3600; $result['ust'] = $this->getUseStartTime() ? 1 : 0; } $time_estimate = $this->getTimeEstimate(); $result['te'] = $this->getTimeEstimate(); if ($time_estimate > 0) { $result['et'] = DateTimeValue::FormatTimeDiff(new DateTimeValue(0), new DateTimeValue($time_estimate * 60), 'hm', 60); } $result['tz'] = logged_user()->getTimezone() * 3600; $ot = $this->getOpenTimeslots(); if ($ot) { $users = array(); $time = array(); $paused = array(); foreach ($ot as $t) { if (!$t instanceof Timeslot) { continue; } $time[] = $t->getSeconds(); $users[] = $t->getContactId(); $paused[] = $t->isPaused() ? 1 : 0; if ($t->isPaused() && $t->getContactId() == logged_user()->getId()) { $result['wpt'] = $t->getPausedOn()->getTimestamp(); } } $result['wt'] = $time; $result['wid'] = $users; $result['wp'] = $paused; } if ($this->isRepetitive()) { $result['rep'] = 1; } return $result; }
/** * Used for Drag & Drop, adds objects to a member * @author alvaro */ function add_objects_to_member() { $ids = json_decode(array_var($_POST, 'objects')); $mem_id = array_var($_POST, 'member'); if (!is_array($ids) || count($ids) == 0) { ajx_current("empty"); return; } $member = Members::findById($mem_id); try { DB::beginWork(); $objects = array(); $from = array(); foreach ($ids as $oid) { /* @var $obj ContentDataObject */ $obj = Objects::findObject($oid); if ($obj instanceof ContentDataObject && $obj->canAddToMember(logged_user(), $member, active_context())) { $dim_obj_type_content = DimensionObjectTypeContents::findOne(array('conditions' => array('`dimension_id`=? AND `dimension_object_type_id`=? AND `content_object_type_id`=?', $member->getDimensionId(), $member->getObjectTypeId(), $obj->getObjectTypeId()))); if (!($dim_obj_type_content instanceof DimensionObjectTypeContent)) continue; if (!$dim_obj_type_content->getIsMultiple() || array_var($_POST, 'remove_prev')) { $db_res = DB::execute("SELECT group_concat(om.member_id) as old_members FROM ".TABLE_PREFIX."object_members om INNER JOIN ".TABLE_PREFIX."members m ON om.member_id=m.id WHERE m.dimension_id=".$member->getDimensionId()." AND om.object_id=".$obj->getId()); $row = $db_res->fetchRow(); if (array_var($row, 'old_members') != "") $from[$obj->getId()] = $row['old_members']; // remove from previous members ObjectMembers::delete('`object_id` = ' . $obj->getId() . ' AND `member_id` IN (SELECT `m`.`id` FROM `'.TABLE_PREFIX.'members` `m` WHERE `m`.`dimension_id` = '.$member->getDimensionId().')'); } $obj->addToMembers(array($member)); $obj->addToSharingTable(); $objects[] = $obj; if ($obj->allowsTimeslots()) { $timeslots = $obj->getTimeslots(); foreach ($timeslots as $timeslot) { $ts_mids = ObjectMembers::getMemberIdsByObject($timeslot->getId()); // if classified then reclassify if (count($ts_mids)) { if (array_var($_POST, 'remove_prev')) { ObjectMembers::delete('`object_id` = ' . $timeslot->getId() . ' AND `member_id` IN (SELECT `m`.`id` FROM `'.TABLE_PREFIX.'members` `m` WHERE `m`.`dimension_id` = '.$member->getDimensionId().')'); } $timeslot->addToMembers(array($member)); $timeslot->addToSharingTable(); $objects[] = $timeslot; } } } if ($obj instanceof MailContent) { $conversation = MailContents::getMailsFromConversation($obj); foreach ($conversation as $conv_email) { if (array_var($_POST, 'attachment') && $conv_email->getHasAttachments()) { MailUtilities::parseMail($conv_email->getContent(), $decoded, $parsedEmail, $warnings); $classification_data = array(); for ($j=0; $j < count(array_var($parsedEmail, "Attachments", array())); $j++) { $classification_data["att_".$j] = true; } MailController::classifyFile($classification_data, $conv_email, $parsedEmail, array($member), array_var($_POST, 'remove_prev')); } } } } else { throw new Exception(lang('you dont have permissions to classify object in member', $obj->getName(), $member->getName())); } } Hook::fire('after_dragdrop_classify', $objects, $member); DB::commit(); // add to application logs foreach ($objects as $object) { $action = array_var($from, $obj->getId()) ? ApplicationLogs::ACTION_MOVE : ApplicationLogs::ACTION_COPY; $log_data = (array_var($from, $obj->getId()) ? "from:" . array_var($from, $obj->getId()) . ";" : "") . "to:" . $member->getId(); ApplicationLogs::instance()->createLog($object, $action, false, true, true, $log_data); } $lang_key = count($ids)>1 ? 'objects moved to member success' : 'object moved to member success'; flash_success(lang($lang_key, $member->getName())); if (array_var($_POST, 'reload')) ajx_current('reload'); else ajx_current('empty'); } catch (Exception $e) { DB::rollback(); ajx_current("empty"); flash_error($e->getMessage()); } }
function add_to_members($object, $member_ids, $user = null, $check_allowed_members = true) { if (!$user instanceof Contact) $user = logged_user(); // 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 ($user->isGuest()) { flash_error(lang('no access permissions')); ajx_current("empty"); return; } if (isset($_POST['trees_not_loaded']) && $_POST['trees_not_loaded'] > 0) return; $required_dimension_ids = array(); $dimension_object_types = $object->getDimensionObjectTypes(); foreach($dimension_object_types as $dot){ if ($dot->getIsRequired()){ $required_dimension_ids[] = $dot->getDimensionId(); } } $required_dimensions = Dimensions::findAll(array("conditions" => "id IN (".implode(",",$required_dimension_ids).") OR is_required=1")); // If not entered members if (count($member_ids) <= 0){ $throw_error = true; if (Plugins::instance()->isActivePlugin('core_dimensions')) { $personal_member = Members::findById($user->getPersonalMemberId()); if ($personal_member instanceof Member) { $member_ids[] = $user->getPersonalMemberId(); } } } if (count($member_ids) > 0) { $enteredMembers = Members::findAll(array('conditions' => 'id IN ('.implode(",", $member_ids).')')); } else { $enteredMembers = array(); } $object->removeFromMembers($user, $enteredMembers); /* @var $object ContentDataObject */ $validMembers = $check_allowed_members ? $object->getAllowedMembersToAdd($user,$enteredMembers) : $enteredMembers; foreach($required_dimensions as $rdim){ $exists = false; foreach ($validMembers as $m){ if ($m->getDimensionId() == $rdim->getId()) { $exists = true; break; } } if (!$exists){ throw new Exception(lang('must choose at least one member of',$rdim->getName())); } } $object->addToMembers($validMembers, true); Hook::fire ('after_add_to_members', $object, $validMembers); $object->addToSharingTable(); // add timeslots to members if ($object->allowsTimeslots()) { $timeslots = $object->getTimeslots(); foreach ($timeslots as $timeslot) { $ts_mids = ObjectMembers::getMemberIdsByObject($timeslot->getId()); // if classified then reclassify if (count($ts_mids) > 0) { ObjectMembers::delete('`object_id` = ' . $timeslot->getId()); if (count($validMembers) > 0) { $timeslot->addToMembers($validMembers); $timeslot->addToSharingTable(); } } } } return $validMembers; }
function classifyFile($classification_data, $email, $parsedEmail, $members, $remove_prev, $use_transaction) { if (!is_array($classification_data)) { $classification_data = array(); } if (!isset($parsedEmail["Attachments"])) { return; //throw new Exception(lang('no attachments found for email')); } $account_owner = logged_user() instanceof contact ? logged_user() : Contacts::findById($email->getAccount()->getContactId()); for ($c = 0; $c < count($classification_data); $c++) { if (isset($classification_data["att_" . $c]) && $classification_data["att_" . $c] && isset($parsedEmail["Attachments"][$c])) { // dont classify inline images if (array_var($parsedEmail["Attachments"][$c], 'FileDisposition') == 'attachment') { $att = $parsedEmail["Attachments"][$c]; $fName = str_starts_with($att["FileName"], "=?") ? iconv_mime_decode($att["FileName"], 0, "UTF-8") : utf8_safe($att["FileName"]); if (trim($fName) == "" && strlen($att["FileName"]) > 0) { $fName = utf8_encode($att["FileName"]); } $extension = get_file_extension(basename($fName)); $type_file_allow = FileTypes::getByExtension($extension); if (!$type_file_allow instanceof FileType || $type_file_allow->getIsAllow() == 1) { try { $remove_previous_members = $remove_prev; // check for file name and size, if there are some then compare the contents, if content is equal do not classify the attachment. $file_exists = 0; $possible_equal_file_rows = DB::executeAll("SELECT * FROM " . TABLE_PREFIX . "project_file_revisions r \r\n\t\t\t\t\t\t\t\tINNER JOIN " . TABLE_PREFIX . "objects o ON o.id=r.file_id \r\n\t\t\t\t\t\t\t\tINNER JOIN " . TABLE_PREFIX . "project_files f ON f.object_id=r.file_id\r\n\t\t\t\t\t\t\t\tWHERE o.name=" . DB::escape($fName) . " AND r.filesize='" . strlen($att["Data"]) . "' \r\n\t\t\t\t\t\t\t\tAND r.revision_number=(SELECT max(r2.revision_number) FROM " . TABLE_PREFIX . "project_file_revisions r2 WHERE r2.file_id=r.file_id)"); if (is_array($possible_equal_file_rows)) { foreach ($possible_equal_file_rows as $row) { $content = FileRepository::getFileContent($row['repository_id']); if ($content == $att['Data']) { // file already exists $file_exists = $row['file_id']; //Logger::log($email->getId()." - ".$row['mail_id']." - $fName"); if ($remove_previous_members && $row['mail_id'] != $email->getId()) { $remove_previous_members = false; } break; } } } if ($file_exists > 0) { $file = ProjectFiles::findById($file_exists); } else { $file = ProjectFiles::findOne(array('conditions' => "mail_id = " . $email->getId() . " AND o.name = " . DB::escape($fName) . "")); } if ($use_transaction) { DB::beginWork(); } if ($file == null) { $fileIsNew = true; $file = new ProjectFile(); $file->setFilename($fName); $file->setIsVisible(true); $file->setMailId($email->getId()); $file->setCreatedById($account_owner->getId()); $file->save(); } else { $fileIsNew = false; } if ($remove_previous_members) { $dim_ids = array(0); foreach ($members as $m) { $dim_ids[$m->getDimensionId()] = $m->getDimensionId(); } ObjectMembers::delete('`object_id` = ' . $file->getId() . ' AND `member_id` IN (SELECT `m`.`id` FROM `' . TABLE_PREFIX . 'members` `m` WHERE `m`.`dimension_id` IN (' . implode(',', $dim_ids) . '))'); } $file->addToMembers($members); // fill sharing table in background add_object_to_sharing_table($file, $account_owner); //$file->addToSharingTable(); $enc = array_var($parsedMail, 'Encoding', 'UTF-8'); $ext = utf8_substr($fName, strrpos($fName, '.') + 1, utf8_strlen($fName, $enc), $enc); $mime_type = ''; if (Mime_Types::instance()->has_type($att["content-type"])) { $mime_type = $att["content-type"]; //mime type is listed & valid } else { $mime_type = Mime_Types::instance()->get_type($ext); //Attempt to infer mime type } $userid = logged_user() ? logged_user()->getId() : "0"; $tempFileName = ROOT . "/tmp/" . $userid . "x" . gen_id(); $fh = fopen($tempFileName, 'w') or die("Can't open file"); fwrite($fh, $att["Data"]); fclose($fh); $fileToSave = array("name" => $fName, "type" => $mime_type, "tmp_name" => $tempFileName, "error" => 0, "size" => filesize($tempFileName)); if ($fileIsNew || !$file->getLastRevision() instanceof ProjectFileRevision) { $revision = $file->handleUploadedFile($fileToSave, true, lang('attachment from email', $email->getSubject())); // handle uploaded file $revision->setCreatedById($account_owner->getId()); $revision->save(); ApplicationLogs::createLog($file, ApplicationLogs::ACTION_ADD); /* }else{ $revision = $file->getLastRevision(); $new_hash = hash_file("sha256", $tempFileName); if ($revision->getHash() != $new_hash) { $revision = $file->handleUploadedFile($fileToSave, true, lang('attachment from email', $email->getSubject())); // handle uploaded file ApplicationLogs::createLog($file, ApplicationLogs::ACTION_ADD); }*/ } if ($use_transaction) { DB::commit(); } // Error... } catch (Exception $e) { if ($use_transaction) { DB::rollback(); } flash_error($e->getMessage()); ajx_current("empty"); } } else { flash_error(lang('file extension no allow classify', $fName)); } if (isset($tempFileName) && is_file($tempFileName)) { unlink($tempFileName); } } } } }
function core_dimensions_after_save_member_permissions($member, &$ignored) { if (!$member instanceof Member || !($member->getId()>0)) return; $permission_group_ids = array(); $cmp_rows = DB::executeAll("SELECT DISTINCT permission_group_id FROM ".TABLE_PREFIX."contact_member_permissions WHERE member_id = '".$member->getId()."' AND permission_group_id IN (SELECT id FROM ".TABLE_PREFIX."permission_groups WHERE type IN ('permission_groups','user_groups'))"); foreach ($cmp_rows as $row) { $permission_group_ids[$row['permission_group_id']] = $row['permission_group_id']; } $contacts = array(); // users if (count($permission_group_ids) > 0) { $contacts = Contacts::findAll(array('conditions' => 'user_type > 0 && permission_group_id IN ('.implode(',', $permission_group_ids).')')); } // contacts $contact_rows = DB::executeAll("SELECT DISTINCT om.object_id FROM ".TABLE_PREFIX."object_members om INNER JOIN ".TABLE_PREFIX."contacts c ON c.object_id=om.object_id WHERE om.member_id='".$member->getId()."' AND c.user_type=0"); $no_user_ids = array(); if (is_array($contact_rows)) { foreach ($contact_rows as $row) { $no_user_ids[] = $row['object_id']; } } $more_contacts = Contacts::findAll(array('conditions' => 'object_id IN ('.implode(',', $no_user_ids).')')); $contacts = array_merge($contacts, $more_contacts); $contact_ids = array(0); $persons_dim = Dimensions::findByCode("feng_persons"); core_dim_remove_contacts_member_associations($member); foreach ($contacts as $contact) { $contact_id = $contact->getId(); $contact_member = Members::findOneByObjectId($contact_id, $persons_dim->getId()); if ($contact_member instanceof Member) { core_dim_add_contact_member_associations($contact_member, $member); if ($contact instanceof Contact && $contact->isUser()) { $has_project_permissions = ContactMemberPermissions::instance()->count("permission_group_id = '".$contact->getPermissionGroupId()."' AND member_id = ".$member->getId()) > 0; if (!$has_project_permissions) { RoleObjectTypePermissions::createDefaultUserPermissions($contact, $member); } } } // add user content object to customer member ObjectMembers::addObjectToMembers($contact_id, array($member)); $contact->addToSharingTable(); $contact_ids[] = $contact_id; } // remove contacts whose members are no longer associated to the customer member $previous_users_in_member = Contacts::instance()->listing(array( 'member_ids' => array($member->getId()), 'ignore_context' => true, 'extra_conditions' => ' AND e.user_type > 0 AND e.object_id NOT IN ('.implode(',', $contact_ids).')', ))->objects; foreach ($previous_users_in_member as $prev_u) { ObjectMembers::removeObjectFromMembers($prev_u, logged_user(), array($member), array($member->getId())); } // refresh dimensions evt_add("reload dimension tree", array('dim_id' => $persons_dim->getId(), 'node' => null)); }
static function getArrayInfo($raw_data, $full = false) { $desc = ""; if ($full) { if (config_option("wysiwyg_tasks")) { if ($raw_data['type_content'] == "text") { $desc = nl2br(htmlspecialchars($raw_data['text'])); } else { $desc = purify_html(nl2br($raw_data['text'])); } } else { if ($raw_data['type_content'] == "text") { $desc = htmlspecialchars($raw_data['text']); } else { $desc = html_to_text(html_entity_decode(nl2br($raw_data['text']), null, "UTF-8")); } } } $member_ids = ObjectMembers::instance()->getCachedObjectMembers($raw_data['id']); $tmp_task = new ProjectTask(); $tmp_task->setObjectId($raw_data['id']); $tmp_task->setId($raw_data['id']); $tmp_task->setAssignedToContactId($raw_data['assigned_to_contact_id']); $result = array('id' => (int) $raw_data['id'], 'name' => $raw_data['name'], 'description' => $desc, 'members' => $member_ids, 'createdOn' => strtotime($raw_data['created_on']), 'createdById' => (int) $raw_data['created_by_id'], 'otype' => $raw_data['object_subtype'], 'percentCompleted' => (int) $raw_data['percent_completed'], 'memPath' => str_replace('"', "'", escape_character(json_encode($tmp_task->getMembersIdsToDisplayPath())))); if (isset($raw_data['isread'])) { $result['isread'] = $raw_data['isread']; } $result['multiAssignment'] = (int) array_var($raw_data, 'multi_assignment'); if ($raw_data['completed_by_id'] > 0) { $result['status'] = 1; } if ($raw_data['parent_id'] > 0) { $result['parentId'] = (int) $raw_data['parent_id']; } $result['subtasksIds'] = $tmp_task->getSubTasksIds(); //if ($this->getPriority() != 200) $result['priority'] = (int) $raw_data['priority']; if ($raw_data['milestone_id'] > 0) { $result['milestoneId'] = (int) $raw_data['milestone_id']; } if ($raw_data['assigned_by_id'] > 0) { $result['assignedById'] = (int) $raw_data['assigned_by_id']; } if ($raw_data['assigned_to_contact_id'] > 0) { $result['assignedToContactId'] = (int) $raw_data['assigned_to_contact_id']; } $result['atName'] = $tmp_task->getAssignedToName(); if ($raw_data['completed_by_id'] > 0) { $result['completedById'] = (int) $raw_data['completed_by_id']; $result['completedOn'] = strtotime($raw_data['completed_on']); } if ($raw_data['due_date'] != EMPTY_DATETIME) { $result['useDueTime'] = $raw_data['use_due_time'] ? 1 : 0; if ($result['useDueTime']) { $result['dueDate'] = strtotime($raw_data['due_date']) + logged_user()->getTimezone() * 3600; } else { $result['dueDate'] = strtotime($raw_data['due_date']); } } if ($raw_data['start_date'] != EMPTY_DATETIME) { $result['useStartTime'] = $raw_data['use_start_time'] ? 1 : 0; if ($result['useStartTime']) { $result['startDate'] = strtotime($raw_data['start_date']) + logged_user()->getTimezone() * 3600; } else { $result['startDate'] = strtotime($raw_data['start_date']); } } $time_estimate = $raw_data['time_estimate']; $result['timeEstimate'] = $raw_data['time_estimate']; if ($time_estimate > 0) { $result['timeEstimateString'] = str_replace(',', ',<br>', DateTimeValue::FormatTimeDiff(new DateTimeValue(0), new DateTimeValue($time_estimate * 60), 'hm', 60)); } $result['timeZone'] = logged_user()->getTimezone() * 3600; $ot = $tmp_task->getOpenTimeslots(); if ($ot) { $users = array(); $time = array(); $paused = array(); foreach ($ot as $t) { if (!$t instanceof Timeslot) { continue; } $time[] = $t->getSeconds(); $users[] = $t->getContactId(); $paused[] = $t->isPaused() ? 1 : 0; if ($t->isPaused() && $t->getContactId() == logged_user()->getId()) { $result['pauseTime'] = $t->getPausedOn()->getTimestamp(); } } $result['workingOnTimes'] = $time; $result['workingOnIds'] = $users; $result['workingOnPauses'] = $paused; } $total_minutes = $tmp_task->getTotalMinutes(); if ($total_minutes > 0) { $result['worked_time'] = $total_minutes; $result['worked_time_string'] = str_replace(',', ',<br>', DateTimeValue::FormatTimeDiff(new DateTimeValue(0), new DateTimeValue($total_minutes * 60), 'hm', 60)); } else { $result['worked_time'] = 0; } $pending_time = $time_estimate - $total_minutes; if ($pending_time > 0) { $result['pending_time'] = $pending_time; $result['pending_time_string'] = str_replace(',', ',<br>', DateTimeValue::FormatTimeDiff(new DateTimeValue(0), new DateTimeValue($pending_time * 60), 'hm', 60)); } else { $result['pending_time'] = 0; } if ($raw_data['repeat_forever'] > 0 || $raw_data['repeat_num'] > 0 || $raw_data['repeat_end'] != EMPTY_DATETIME && $raw_data['repeat_end'] != '') { $result['repetitive'] = 1; } $tmp_members = array(); if (count($member_ids) > 0) { $tmp_members = Members::findAll(array("conditions" => "id IN (" . implode(',', $member_ids) . ")")); } $result['can_add_timeslots'] = can_add_timeslots(logged_user(), $tmp_members); //tasks dependencies if (config_option('use tasks dependencies')) { //get all dependant tasks ids, not completed yet $pending_tasks_ids = ProjectTaskDependencies::getDependenciesForTaskOnlyPendingIds($tmp_task->getId()); //get the total of previous tasks $result['dependants'] = $pending_tasks_ids; $result['previous_tasks_total'] = ProjectTaskDependencies::countPendingPreviousTasks($tmp_task->getId()); } return $result; }
/** * Return manager instance * * @access protected * @param void * @return ObjectMembers */ function manager() { if (!$this->manager instanceof ObjectMembers) { $this->manager = ObjectMembers::instance(); } return $this->manager; }
/** * Execute the script * * @param void * @return boolean */ function execute() { // --------------------------------------------------- // Check MySQL version // --------------------------------------------------- $mysql_version = mysql_get_server_info($this->database_connection); if($mysql_version && version_compare($mysql_version, '4.1', '>=')) { $constants['DB_CHARSET'] = 'utf8'; @mysql_query("SET NAMES 'utf8'", $this->database_connection); tpl_assign('default_collation', $default_collation = 'collate utf8_unicode_ci'); tpl_assign('default_charset', $default_charset = 'DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci'); } else { tpl_assign('default_collation', $default_collation = ''); tpl_assign('default_charset', $default_charset = ''); } // if $installed_version = installed_version(); $t_prefix = TABLE_PREFIX; if (version_compare($installed_version, '1.7.5') <= 0 && TABLE_PREFIX != "fo_") $t_prefix = "fo_"; tpl_assign('table_prefix', $t_prefix); if (defined('DB_ENGINE')) tpl_assign('engine', DB_ENGINE); else tpl_assign('engine', 'InnoDB'); // --------------------------------------------------- // Execute migration // --------------------------------------------------- $additional_upgrade_steps = array(); // RUN QUERIES $total_queries = 0; $executed_queries = 0; $upgrade_script = ""; // upgrading from version 1.x if (version_compare($installed_version, '2.0.0.0-beta') < 0) { ini_set('memory_limit', '1024M'); @set_time_limit(0); $upgrade_script .= tpl_fetch(get_template_path('db_migration/2_0_asado')); if($this->executeMultipleQueries($upgrade_script, $total_queries, $executed_queries, $this->database_connection)) { $this->printMessage("Database schema transformations executed (total queries: $total_queries)"); } else { $this->printMessage('Failed to execute DB schema transformations. MySQL said: ' . mysql_error(), true); return false; } $_SESSION['from_feng1'] = true; $upgrade_script = ""; @unlink(ROOT . '/cache/autoloader.php'); include ROOT . '/environment/classes/AutoLoader.class.php'; include ROOT . '/environment/constants.php'; if (!$callbacks = spl_autoload_functions()) $callbacks = array(); foreach ($callbacks as $callback) { spl_autoload_unregister($callback); } spl_autoload_register('feng_upg_autoload'); foreach ($callbacks as $callback) { spl_autoload_register($callback); } @include ROOT . '/cache/autoloader.php'; define('DONT_LOG', true); define('FORCED_TABLE_PREFIX', 'fo_'); if (!defined('FILE_STORAGE_FILE_SYSTEM')) define('FILE_STORAGE_FILE_SYSTEM', 'fs'); if (!defined('FILE_STORAGE_MYSQL')) define('FILE_STORAGE_MYSQL', 'mysql'); if (!defined('MAX_SEARCHABLE_FILE_SIZE')) define('MAX_SEARCHABLE_FILE_SIZE', 1048576); try { DB::connect(DB_ADAPTER, array( 'host' => DB_HOST, 'user' => DB_USER, 'pass' => DB_PASS, 'name' => DB_NAME, 'persist' => DB_PERSIST )); if(defined('DB_CHARSET') && trim(DB_CHARSET)) { DB::execute("SET NAMES ?", DB_CHARSET); } } catch(Exception $e) { $this->printMessage("Error connecting to database: ".$e->getMessage()."\n".$e->getTraceAsString()); } try { $db_result = DB::execute("SELECT value FROM fo_config_options WHERE name = 'file_storage_adapter'"); $db_result_row = $db_result->fetchRow(); if($db_result_row['value'] == FILE_STORAGE_FILE_SYSTEM) { if (!defined('FILES_DIR')) define('FILES_DIR', ROOT . '/upload'); FileRepository::setBackend(new FileRepository_Backend_FileSystem(FILES_DIR, TABLE_PREFIX)); } else { FileRepository::setBackend(new FileRepository_Backend_DB(TABLE_PREFIX)); } PublicFiles::setRepositoryPath(ROOT . '/public/files'); if (!defined('PUBLIC_FOLDER')) define('PUBLIC_FOLDER', 'public'); if(trim(PUBLIC_FOLDER) == '') { PublicFiles::setRepositoryUrl(with_slash(ROOT_URL) . 'files'); } else { PublicFiles::setRepositoryUrl(with_slash(ROOT_URL) . 'public/files'); } $members = Members::findAll(array("conditions" => "`depth` > 1")); $sql = ""; $first_row = true; foreach ($members as $member) { $parents = $member->getAllParentMembersInHierarchy(false, false); $obj_members = ObjectMembers::findAll(array("conditions" => "`is_optimization` = 0 AND `member_id` = ".$member->getId())); $sql = ""; $first_row = true; foreach ($obj_members as $om) { foreach ($parents as $parent) { if ($sql == "") $sql = "INSERT INTO ".$t_prefix."object_members (`object_id`, `member_id`, `is_optimization`) VALUES "; $sql .= ($first_row ? "" : ", ") . "(".$om->getObjectId().", ".$parent->getId().", 1)"; $first_row = false; } } if ($sql != "") { $sql .= " ON DUPLICATE KEY UPDATE `object_id`=`object_id`"; DB::execute($sql); $sql = ""; } } $this->printMessage("Finished generating Object Members"); $members = Members::findAll(array("conditions" => "`depth` > 1", "order" => "depth ASC")); foreach ($members as $m) { if ($m->getParentMember() instanceof Member && $m->getDimensionId() != $m->getParentMember()->getDimensionId()) { $m->setDimensionId($m->getParentMember()->getDimensionId()); $m->save(); } } $app_move_logs = ApplicationLogs::findAll(array("conditions" => "action = 'move'")); foreach ($app_move_logs as &$app_log) {/* @var $app_log ApplicationLog */ $exp_log_data = explode(";", $app_log->getLogData()); if (count($exp_log_data) > 1) { $old_to = array_var($exp_log_data, 1); $old_from = array_var($exp_log_data, 0); } else { $old_to = array_var($exp_log_data, 0); $old_from = ""; } $to_id = str_replace("to:", "", $old_to); $new_to_id = Members::instance()->findOne(array("id" => true, "conditions" => "ws_id = '$to_id'")); if (count($new_to_id) > 0) $new_to_id = $new_to_id[0]; $new_from_ids = ""; $from_ids = str_replace("from:", "", $old_from); if ($from_ids != "") { $new_from_ids_array = Members::instance()->findAll(array("id" => true, "conditions" => "ws_id IN ($from_ids)")); $new_from_ids = implode(",", $new_from_ids_array); } if ($new_to_id) { if ($new_from_ids) { $log_data = "from:$new_from_ids;to:$new_to_id"; } else { $log_data = "to:$new_to_id"; } $app_log->setLogData($log_data); $app_log->save(); } } } catch (Exception $e) { die("\nError occurred:\n-----------------\n".$e->getMessage()."\n".$e->getTraceAsString()); } //tpl_assign('install_inv_dw', true); $additional_upgrade_steps[] = array( 'url' => 'complete_migration.php?out=file', 'name' => 'Fill searchable objects and sharing table', 'filename' => dirname(__FILE__)."/../complete_migration.php" ); } else { // upgrading from a pre-release of this version (beta, rc, etc) if (version_compare($installed_version, '2.0.0.4') <= 0) { if (!$this->checkTableExists($t_prefix.'role_object_type_permissions', $this->database_connection)) { $upgrade_script .= " CREATE TABLE `".$t_prefix."role_object_type_permissions` ( `role_id` INTEGER UNSIGNED NOT NULL, `object_type_id` INTEGER UNSIGNED NOT NULL, `can_delete` BOOLEAN NOT NULL, `can_write` BOOLEAN NOT NULL, PRIMARY KEY (`role_id`, `object_type_id`) ) ENGINE = InnoDB; INSERT INTO ".$t_prefix."role_object_type_permissions (role_id, object_type_id, can_delete, can_write) SELECT p.id, o.id, 1, 1 FROM `".$t_prefix."object_types` o JOIN `".$t_prefix."permission_groups` p WHERE o.`name` IN ('message','weblink','file','task','milestone','event','contact','mail','timeslot','report','comment') AND p.`name` IN ('Super Administrator','Administrator','Manager','Executive'); INSERT INTO ".$t_prefix."role_object_type_permissions (role_id, object_type_id, can_delete, can_write) SELECT p.id, o.id, 0, 1 FROM `".$t_prefix."object_types` o JOIN `".$t_prefix."permission_groups` p WHERE o.`name` IN ('message','weblink','file','task','milestone','event','contact','timeslot','report','comment') AND p.`name` IN ('Collaborator Customer'); INSERT INTO ".$t_prefix."role_object_type_permissions (role_id, object_type_id, can_delete, can_write) SELECT p.id, o.id, 0, 1 FROM `".$t_prefix."object_types` o JOIN `".$t_prefix."permission_groups` p WHERE o.`name` IN ('message','weblink','file','task','milestone','event','timeslot','comment') AND p.`name` IN ('Internal Collaborator','External Collaborator'); INSERT INTO ".$t_prefix."role_object_type_permissions (role_id, object_type_id, can_delete, can_write) SELECT p.id, o.id, 0, 0 FROM `".$t_prefix."object_types` o JOIN `".$t_prefix."permission_groups` p WHERE o.`name` IN ('message','weblink','file','event','comment') AND p.`name` IN ('Guest Customer'); INSERT INTO ".$t_prefix."role_object_type_permissions (role_id, object_type_id, can_delete, can_write) SELECT p.id, o.id, 0, 0 FROM `".$t_prefix."object_types` o JOIN `".$t_prefix."permission_groups` p WHERE o.`name` IN ('message','weblink','event','comment') AND p.`name` IN ('Guest'); INSERT INTO ".$t_prefix."role_object_type_permissions (role_id, object_type_id, can_delete, can_write) SELECT p.id, o.id, 0, 0 FROM `".$t_prefix."object_types` o JOIN `".$t_prefix."permission_groups` p WHERE o.`name` IN ('message','weblink','file','task','milestone','event','contact','timeslot','report','comment') AND p.`name` IN ('Non-Exec Director'); UPDATE ".$t_prefix."role_object_type_permissions SET can_write = 1 WHERE object_type_id = (SELECT id FROM ".$t_prefix."object_types WHERE name='comment'); "; } if (!$this->checkTableExists($t_prefix.'widgets', $this->database_connection)) { $upgrade_script .= " CREATE TABLE `".$t_prefix."widgets` ( `name` varchar(64) NOT NULL, `title` varchar(255) NOT NULL, `plugin_id` int(10) unsigned NOT NULL, `path` varchar(512) NOT NULL, `default_options` text NOT NULL, `default_section` varchar(64) NOT NULL, `default_order` int(10) NOT NULL, PRIMARY KEY (`name`) ) ENGINE = InnoDB; "; } if($this->executeMultipleQueries($upgrade_script, $total_queries, $executed_queries, $this->database_connection)) { $this->printMessage("Database schema transformations executed (total queries: $total_queries)"); } else { $this->printMessage('Failed to execute DB schema transformations. MySQL said: ' . mysql_error(), true); return false; } } if (version_compare($installed_version, '2.0.0.5') <= 0) { if (!$this->checkColumnExists($t_prefix.'contacts', 'default_billing_id', $this->database_connection)) { $upgrade_script = " ALTER TABLE `".$t_prefix."contacts` ADD COLUMN `default_billing_id` INTEGER NOT NULL DEFAULT 0; ALTER TABLE `".$t_prefix."project_tasks` ADD COLUMN `use_due_time` BOOLEAN DEFAULT 0, ADD COLUMN `use_start_time` BOOLEAN DEFAULT 0; UPDATE ".$t_prefix."project_tasks t SET t.due_date = ADDTIME(t.due_date, CONCAT(SUBSTRING_INDEX((SELECT c.timezone FROM ".$t_prefix."contacts c WHERE c.object_id=(SELECT o.updated_by_id FROM ".$t_prefix."objects o WHERE o.id=t.object_id)), '.', 1), ':', SUBSTRING_INDEX(abs((SELECT c.timezone FROM ".$t_prefix."contacts c WHERE c.object_id=(SELECT o.updated_by_id FROM ".$t_prefix."objects o WHERE o.id=t.object_id)) % 1)*60, '.', 1))) WHERE t.due_date > 0; UPDATE ".$t_prefix."project_tasks t SET t.start_date = ADDTIME(t.start_date, CONCAT(SUBSTRING_INDEX((SELECT c.timezone FROM ".$t_prefix."contacts c WHERE c.object_id=(SELECT o.updated_by_id FROM ".$t_prefix."objects o WHERE o.id=t.object_id)), '.', 1), ':', SUBSTRING_INDEX(abs((SELECT c.timezone FROM ".$t_prefix."contacts c WHERE c.object_id=(SELECT o.updated_by_id FROM ".$t_prefix."objects o WHERE o.id=t.object_id)) % 1)*60, '.', 1))) WHERE t.start_date > 0; INSERT INTO `".$t_prefix."contact_config_options` (`category_name`, `name`, `default_value`, `config_handler_class`, `is_system`, `option_order`, `dev_comment`) VALUES ('general', 'work_day_end_time', '18:00', 'TimeConfigHandler', 0, 410, 'Work day end time'); "; } if($this->executeMultipleQueries($upgrade_script, $total_queries, $executed_queries, $this->database_connection)) { $this->printMessage("Database schema transformations executed (total queries: $total_queries)"); } else { $this->printMessage('Failed to execute DB schema transformations. MySQL said: ' . mysql_error(), true); return false; } } if (version_compare($installed_version, '2.0.0.6') <= 0) { //WS Widgets $upgrade_script = " UPDATE `".$t_prefix."contact_config_options` SET `default_value` = '15' WHERE `".$t_prefix."contact_config_options`.`name` = 'noOfTasks' LIMIT 1 ; UPDATE ".$t_prefix."widgets SET default_section = 'none' WHERE name = 'people' AND NOT EXISTS (SELECT id from ".$t_prefix."plugins WHERE name = 'crpm'); UPDATE ".$t_prefix."dimensions SET options = '{\"defaultAjax\":{\"controller\":\"dashboard\", \"action\": \"main_dashboard\"}, \"quickAdd\":true,\"showInPaths\":true}' WHERE code='workspaces'; UPDATE `".$t_prefix."tab_panels` SET default_action = 'main_dashboard', initial_action = 'main_dashboard' WHERE id = 'overview-panel' ; UPDATE ".$t_prefix."object_types SET type = 'dimension_object', handler_class='Workspaces', table_name = 'workpaces' WHERE name = 'workspace' ; UPDATE ".$t_prefix."dimension_object_types SET OPTIONS = '{\"defaultAjax\":{\"controller\":\"dashboard\", \"action\": \"main_dashboard\"}}' WHERE dimension_id = (SELECT id FROM ".$t_prefix."dimensions WHERE code = 'workspaces'); CREATE TABLE IF NOT EXISTS `".$t_prefix."contact_widgets` ( `widget_name` varchar(40) NOT NULL, `contact_id` int(11) NOT NULL, `section` varchar(40) NOT NULL, `order` int(11) NOT NULL, `options` varchar(255) NOT NULL, PRIMARY KEY (`widget_name`,`contact_id`) USING BTREE ) ENGINE=InnoDB; INSERT INTO ".$t_prefix."widgets(name, title, plugin_id, default_section,default_order) VALUES ('messages','notes',0,'none',1000) ON DUPLICATE KEY update name = name; INSERT INTO ".$t_prefix."dimension_object_type_contents (dimension_id, dimension_object_type_id, content_object_type_id, is_required, is_multiple) SELECT d.id, ot.id, (SELECT tmp.id FROM ".$t_prefix."object_types tmp WHERE tmp.name='contact'), 0, 1 FROM ".$t_prefix."dimensions d JOIN ".$t_prefix."object_types ot WHERE d.code = 'customer_project' AND ot.name IN ('customer', 'project', 'folder', 'customer_folder', 'project_folder') ON DUPLICATE KEY UPDATE dimension_id=dimension_id; UPDATE ".$t_prefix."dimension_object_type_contents SET is_multiple = 1 WHERE content_object_type_id = (SELECT id FROM ".$t_prefix."object_types WHERE name='mail'); "; if (@mysql_fetch_row(@mysql_query(("SELECT id from ".$t_prefix."plugins WHERE name = 'workspaces'")))) { $upgrade_script.="INSERT INTO ".$t_prefix."widgets(name, title, plugin_id, default_section,default_order) VALUES ('ws_description', 'workspace description',(SELECT id from ".$t_prefix."plugins WHERE name = 'workspaces'), 'left',-100) ON DUPLICATE KEY update name = name ;"; } if($this->executeMultipleQueries($upgrade_script, $total_queries, $executed_queries, $this->database_connection)) { $this->printMessage("Database schema transformations executed (total queries: $total_queries)"); } else { $this->printMessage('Failed to execute DB schema transformations. MySQL said: ' . mysql_error(), true); return false; } if ($obj = @mysql_fetch_object(@mysql_query("SELECT id FROM ".$t_prefix."object_types WHERE name = 'workspace' " ))) { $wsTypeId = $obj->id ; $res = @mysql_query("SELECT * FROM ".$t_prefix."members WHERE dimension_id = (SELECT id FROM ".$t_prefix."dimensions WHERE code='workspaces')" ) ; while ( $m = @mysql_fetch_object($res) ) { @mysql_query("INSERT INTO ".$t_prefix."objects (object_type_id, name) VALUES ($wsTypeId, '".$m->name."' )" ); if ( $id = @mysql_insert_id()){ @mysql_query("INSERT INTO ".$t_prefix."workspaces (object_id) VALUES ($id)"); @mysql_query("UPDATE ".$t_prefix."members SET object_id=$id WHERE id = $m->id "); } } } } if (version_compare($installed_version, '2.0.0.7') <= 0) { $upgrade_script = ""; if (!$this->checkTableExists($t_prefix.'mail_spam_filters', $this->database_connection)) { $upgrade_script .= " CREATE TABLE IF NOT EXISTS `".$t_prefix."mail_spam_filters` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `account_id` int(10) unsigned NOT NULL, `text_type` enum('email_address','subject') COLLATE utf8_unicode_ci NOT NULL, `text` text COLLATE utf8_unicode_ci NOT NULL, `spam_state` enum('no spam','spam') COLLATE utf8_unicode_ci NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB; "; } $upgrade_script .= "INSERT INTO `".$t_prefix."config_options` (`category_name`, `name`, `value`, `config_handler_class`, `is_system`, `option_order`, `dev_comment`) VALUES ('general', 'untitled_notes', '0', 'BoolConfigHandler', '0', '0', NULL) ON DUPLICATE KEY UPDATE name=name;"; if($this->executeMultipleQueries($upgrade_script, $total_queries, $executed_queries, $this->database_connection)) { $this->printMessage("Database schema transformations executed (total queries: $total_queries)"); } else { $this->printMessage('Failed to execute DB schema transformations. MySQL said: ' . mysql_error(), true); return false; } } if (version_compare($installed_version, '2.0.0.8') < 0) { $upgrade_script = ""; if (!$this->checkTableExists($t_prefix.'external_calendar_users', $this->database_connection)) { $upgrade_script .= " CREATE TABLE IF NOT EXISTS `".$t_prefix."external_calendar_users` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `contact_id` int(10) unsigned NOT NULL, `auth_user` varchar(100) COLLATE utf8_unicode_ci NOT NULL, `auth_pass` varchar(100) COLLATE utf8_unicode_ci NOT NULL, `type` text COLLATE utf8_unicode_ci NOT NULL, `sync` TINYINT( 1 ) NULL DEFAULT '0', PRIMARY KEY (`id`) ) ENGINE = InnoDB; "; } if (!$this->checkTableExists($t_prefix.'external_calendars', $this->database_connection)) { $upgrade_script .= " CREATE TABLE IF NOT EXISTS `".$t_prefix."external_calendars` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `ext_cal_user_id` int(10) unsigned NOT NULL, `calendar_user` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `calendar_visibility` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `calendar_name` text COLLATE utf8_unicode_ci NOT NULL, `calendar_feng` TINYINT( 1 ) NOT NULL DEFAULT '0', PRIMARY KEY (`id`) ) ENGINE = InnoDB; "; } if (!$this->checkColumnExists($t_prefix.'project_events', 'ext_cal_id', $this->database_connection)) { $upgrade_script .= " ALTER TABLE `".$t_prefix."project_events` ADD `ext_cal_id` INT(10) UNSIGNED NOT NULL; "; } $upgrade_script .= " ALTER TABLE `".$t_prefix."project_events` CHANGE `special_id` `special_id` VARCHAR(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL; UPDATE `".$t_prefix."file_types` SET `is_searchable` = '1' WHERE `extension` = 'docx'; UPDATE `".$t_prefix."file_types` SET `is_searchable` = '1' WHERE `extension` = 'pdf'; INSERT INTO `".$t_prefix."config_options` (`category_name`, `name`, `value`, `config_handler_class`, `is_system`, `option_order`, `dev_comment`) VALUES ('general', 'repeating_task', '0', 'BoolConfigHandler', '0', '0', '') ON DUPLICATE KEY UPDATE name=name; INSERT INTO `".$t_prefix."contact_config_options` (`category_name`, `name`, `default_value`, `config_handler_class`, `is_system`, `option_order`, `dev_comment`) VALUES ('calendar panel', 'calendar task filter', 'pending', 'StringConfigHandler', '1', '0', NULL), ('task panel', 'close timeslot open', '1', 'BoolConfigHandler', '0', '0', NULL), ('calendar panel', 'reminders_events', 'reminder_email,1,60', 'StringConfigHandler', '0', '0', NULL) ON DUPLICATE KEY UPDATE name=name; INSERT INTO `".$t_prefix."cron_events` (`name`, `recursive`, `delay`, `is_system`, `enabled`, `date`) VALUES ('import_google_calendar', '1', '10', '0', '0', '0000-00-00 00:00:00'), ('export_google_calendar', '1', '10', '0', '0', '0000-00-00 00:00:00') ON DUPLICATE KEY UPDATE name=name; "; $upgrade_script .= " DELETE FROM `".$t_prefix."config_options` WHERE `name`='use_time_in_task_dates' AND NOT EXISTS (SELECT id FROM `".$t_prefix."plugins` WHERE `name`='crpm' AND is_activated=1); INSERT INTO ".$t_prefix."contact_config_options (category_name, name, default_value, config_handler_class, is_system, option_order) VALUES ('general','show_object_direct_url',0,'BoolConfigHandler',0,0), ('general','drag_drop_prompt','prompt','DragDropPromptConfigHandler',0,0) ON DUPLICATE KEY UPDATE name = name; "; $upgrade_script .= " INSERT INTO `".$t_prefix."tab_panels` (`id`,`title`,`icon_cls`,`refresh_on_context_change`,`default_controller`,`default_action`,`initial_controller`,`initial_action`,`enabled`,`type`,`ordering`,`plugin_id`,`object_type_id`) VALUES ('contacts-panel','contacts','ico-contacts',1,'contact','init','','',0,'system',7,0,16) ON DUPLICATE KEY UPDATE title=title; "; if($this->executeMultipleQueries($upgrade_script, $total_queries, $executed_queries, $this->database_connection)) { $this->printMessage("Database schema transformations executed (total queries: $total_queries)"); } else { $this->printMessage('Failed to execute DB schema transformations. MySQL said: ' . mysql_error(), true); return false; } } if (version_compare($installed_version, '2.0.1') < 0) { $upgrade_script = ""; $upgrade_script .= "INSERT INTO `".$t_prefix."config_options` (`category_name`, `name`, `value`, `config_handler_class`, `is_system`, `option_order`, `dev_comment`) VALUES ('general', 'working_days', '1,2,3,4,5,6,7', 'StringConfigHandler', '0', '0', NULL); ALTER TABLE `".$t_prefix."project_tasks` ADD `original_task_id` INT( 10 ) UNSIGNED NULL DEFAULT '0'; ALTER TABLE `".$t_prefix."project_tasks` ADD `type_content` ENUM( 'text', 'html' ) NOT NULL DEFAULT 'text'; ALTER TABLE `".$t_prefix."project_events` ADD `original_event_id` INT( 10 ) UNSIGNED NULL DEFAULT '0'; ALTER TABLE `".$t_prefix."project_messages` ADD `type_content` ENUM( 'text', 'html' ) NOT NULL DEFAULT 'text'; "; $upgrade_script .= "INSERT INTO `".$t_prefix."config_options` (`category_name`, `name`, `value`, `config_handler_class`, `is_system`, `option_order`, `dev_comment`) VALUES ('general', 'wysiwyg_tasks', '0', 'BoolConfigHandler', '0', '0', NULL), ('general', 'wysiwyg_messages', '0', 'BoolConfigHandler', '0', '0', NULL), ('task panel', 'tasksShowTimeEstimates', '1', 'BoolConfigHandler', '1', '0', NULL) ON DUPLICATE KEY UPDATE name=name; "; $upgrade_script .= "UPDATE `".$t_prefix."widgets` SET plugin_id = (SELECT id FROM `".$t_prefix."plugins` WHERE name='workspaces') WHERE name='workspaces'; "; // clean old users dimension $upgrade_script .= "DELETE FROM `".$t_prefix."object_members` WHERE member_id IN (SELECT `id` FROM `".$t_prefix."members` WHERE `dimension_id` IN (SELECT `id` FROM `".$t_prefix."dimensions` WHERE `code`='feng_users')); DELETE FROM `".$t_prefix."contact_dimension_permissions` WHERE dimension_id IN (SELECT `id` FROM `".$t_prefix."dimensions` WHERE `code`='feng_users'); DELETE FROM `".$t_prefix."members` WHERE dimension_id IN (SELECT `id` FROM `".$t_prefix."dimensions` WHERE `code`='feng_users'); DELETE FROM `".$t_prefix."dimension_object_type_contents` WHERE dimension_id IN (SELECT `id` FROM `".$t_prefix."dimensions` WHERE `code`='feng_users'); DELETE FROM `".$t_prefix."dimension_object_type_hierarchies` WHERE dimension_id IN (SELECT `id` FROM `".$t_prefix."dimensions` WHERE `code`='feng_users'); DELETE FROM `".$t_prefix."dimension_object_types` WHERE dimension_id IN (SELECT `id` FROM `".$t_prefix."dimensions` WHERE `code`='feng_users'); DELETE FROM `".$t_prefix."dimensions` WHERE code='feng_users'; DELETE FROM `".$t_prefix."object_types` WHERE name='user'; UPDATE ".$t_prefix."contacts c SET c.personal_member_id = 0 WHERE c.user_type>0 AND NOT (SELECT count(m2.id) FROM ".$t_prefix."members m2 WHERE m2.object_id=c.personal_member_id)=0; "; if($this->executeMultipleQueries($upgrade_script, $total_queries, $executed_queries, $this->database_connection)) { $this->printMessage("Database schema transformations executed (total queries: $total_queries)"); } else { $this->printMessage('Failed to execute DB schema transformations. MySQL said: ' . mysql_error(), true); return false; } } // Plugin Version Support $upgrade_script = ''; if(!$this->checkColumnExists($t_prefix."plugins", 'version', $this->database_connection)) { $upgrade_script = 'ALTER TABLE '.$t_prefix.'plugins ADD COLUMN `version` INTEGER NOT NULL DEFAULT 1 AFTER `name` '; if($this->executeMultipleQueries($upgrade_script, $total_queries, $executed_queries, $this->database_connection)) { $this->printMessage("Database schema transformations executed (total queries: $total_queries)"); } else { $this->printMessage('Failed to execute DB schema transformations. MySQL said: ' . mysql_error(), true); return false; } } } $this->printMessage('Feng Office has been upgraded. You are now running Feng Office '.$this->getVersionTo().' Enjoy!'); tpl_assign('additional_steps', $additional_upgrade_steps); } // execute
static function getArrayInfo($raw_data, $full = false){ if(config_option("wysiwyg_tasks")){ if($raw_data['type_content'] == "text"){ $desc = nl2br(htmlspecialchars($raw_data['text'])); }else{ $desc = purify_html(nl2br($raw_data['text'])); } }else{ if($raw_data['type_content'] == "text"){ $desc = htmlspecialchars($raw_data['text']); }else{ $desc = html_to_text(html_entity_decode(nl2br($raw_data['text']), null, "UTF-8")); } } $member_ids = ObjectMembers::instance()->getCachedObjectMembers($raw_data['id']); $tmp_task = new ProjectTask(); $tmp_task->setObjectId($raw_data['id']); $tmp_task->setId($raw_data['id']); $tmp_task->setAssignedToContactId($raw_data['assigned_to_contact_id']); $result = array( 'id' => $raw_data['id'], 't' => $raw_data['name'], 'desc' => $desc, 'members' => $member_ids, 'c' => strtotime($raw_data['created_on']), 'cid' => (int)$raw_data['created_by_id'], 'otype' => $raw_data['object_subtype'], 'pc' => (int)$raw_data['percent_completed'], 'memPath' => str_replace('"',"'", str_replace("'", "\'", json_encode($tmp_task->getMembersToDisplayPath($member_ids)))) ); if ($full) { $result['description'] = $raw_data['text']; } $result['mas'] = (int)array_var($raw_data, 'multi_assignment'); if ($raw_data['completed_by_id'] > 0) { $result['s'] = 1; } if ($raw_data['parent_id'] > 0) { $result['pid'] = (int)$raw_data['parent_id']; } //if ($this->getPriority() != 200) $result['pr'] = (int)$raw_data['priority']; if ($raw_data['milestone_id'] > 0) { $result['mid'] = (int)$raw_data['milestone_id']; } if ($raw_data['assigned_to_contact_id'] > 0) { $result['atid'] = (int)$raw_data['assigned_to_contact_id']; } $result['atName'] = $tmp_task->getAssignedToName(); if ($raw_data['completed_by_id'] > 0) { $result['cbid'] = (int)$raw_data['completed_by_id']; $result['con'] = strtotime($raw_data['completed_on']);; } if ($raw_data['due_date'] != EMPTY_DATETIME) { $result['dd'] = strtotime($raw_data['due_date']) + logged_user()->getTimezone() * 3600; $result['udt'] = $raw_data['use_due_time'] ? 1 : 0; } if ($raw_data['start_date'] != EMPTY_DATETIME) { $result['sd'] = strtotime($raw_data['start_date']) + logged_user()->getTimezone() * 3600; $result['ust'] = $raw_data['use_start_time'] ? 1 : 0; } $time_estimate = $raw_data['time_estimate']; $result['te'] = $raw_data['time_estimate']; if ($time_estimate > 0) $result['et'] = DateTimeValue::FormatTimeDiff(new DateTimeValue(0), new DateTimeValue($time_estimate * 60), 'hm', 60) ; $result['tz'] = logged_user()->getTimezone() * 3600; $ot = $tmp_task->getOpenTimeslots(); if ($ot){ $users = array(); $time = array(); $paused = array(); foreach ($ot as $t){ if (!$t instanceof Timeslot) continue; $time[] = $t->getSeconds(); $users[] = $t->getContactId(); $paused[] = $t->isPaused()?1:0; if ($t->isPaused() && $t->getContactId() == logged_user()->getId()) { $result['wpt'] = $t->getPausedOn()->getTimestamp(); } } $result['wt'] = $time; $result['wid'] = $users; $result['wp'] = $paused; } if ($raw_data['repeat_forever'] > 0 || $raw_data['repeat_num'] > 0 || $raw_data['repeat_end'] != EMPTY_DATETIME) { $result['rep'] = 1; } return $result; }
function canBeDeleted(&$error_message) { $childs = $this->getAllChildren(); if (MemberPropertyMembers::isMemberAssociated($this->getId())) { $error_message = lang("cannot delete member is associated"); return false; } $continue_check = false; if (count($childs) == 0) { $continue_check = true; } else { if ($this->getParentMemberId() > 0) { $child_ots = DimensionObjectTypeHierarchies::getAllChildrenObjectTypeIds($this->getDimensionId(), $this->getParentMember()->getObjectTypeId(), false); } foreach ($childs as $child) { // check if child can be put in the parent (or root) if ($this->getParentMemberId() == 0) { $dim_ot = DimensionObjectTypes::findOne(array("conditions" => array("`dimension_id` = ? AND `object_type_id` = ?", $this->getDimensionId(), $child->getObjectTypeId()))); if (!$dim_ot->getIsRoot()) { $error_message = lang("cannot delete member cannot be root"); return false; } } else { if (!in_array($child->getObjectTypeId(), $child_ots)) { $error_message = lang("cannot delete member childs cannot be moved to parent"); return false; } } } $continue_check = true; } if (!$continue_check) { return false; } else { $child_ids = $this->getAllChildrenIds(); $child_ids[] = $this->getId(); $child_ids_str = implode(",", $child_ids); $objects_in_member = ObjectMembers::instance()->findAll(array('conditions' => 'member_id = ' . $this->getId())); if (!$objects_in_member || count($objects_in_member) == 0) { return true; } else { $more_conditions = ""; if (Plugins::instance()->isActivePlugin('core_dimensions')) { $person_dim = Dimensions::findByCode('feng_persons')->getId(); $more_conditions = " AND member_id NOT IN (SELECT id FROM " . TABLE_PREFIX . "members WHERE dimension_id={$person_dim})"; } $object_id_condition = $this->getObjectId() > 0 ? " AND o.id <> " . $this->getObjectId() : ""; foreach ($objects_in_member as $om) { $obj_members = ObjectMembers::findAll(array("conditions" => array("`object_id` = ? AND `is_optimization` = 0 AND member_id IN ({$child_ids_str}) AND EXISTS (SELECT o.id FROM " . TABLE_PREFIX . "objects o WHERE o.id = ? AND o.trashed_by_id=0 {$object_id_condition})" . $more_conditions, $om->getObjectId(), $om->getObjectId()))); if (count($obj_members) >= 1) { $error_message = lang("cannot delete member has objects"); return false; } $db_res = DB::execute("SELECT object_type_id FROM " . TABLE_PREFIX . "objects WHERE id=" . $om->getObjectId()); $row = $db_res->fetchRow(); if ($row && array_var($row, 'object_type_id')) { $req_dim_ids = DimensionObjectTypeContents::getRequiredDimensions(array_var($row, 'object_type_id')); if (in_array($this->getDimensionId(), $req_dim_ids)) { $error_message = lang("cannot delete member is required for objects"); return false; } } } } } return true; }
/** * Return manager instance * * @access protected * @param void * @return ObjectMembers */ function manager() { if(!($this->manager instanceof ObjectMembers)) $this->manager = ObjectMembers::instance(); return $this->manager; } // manager
function create_user($user_data, $permissionsString) { // try to find contact by some properties $contact_id = array_var($user_data, "contact_id") ; $contact = Contacts::instance()->findById($contact_id) ; if (!is_valid_email(array_var($user_data, 'email'))) { throw new Exception(lang("email value is required")); } if (!$contact instanceof Contact) { // Create a new user $contact = new Contact(); $contact->setUsername(array_var($user_data, 'username')); $contact->setDisplayName(array_var($user_data, 'display_name')); $contact->setCompanyId(array_var($user_data, 'company_id')); $contact->setUserType(array_var($user_data, 'type')); $contact->setTimezone(array_var($user_data, 'timezone')); $contact->setFirstname($contact->getObjectName() != "" ? $contact->getObjectName() : $contact->getUsername()); $contact->setObjectName(); } else { // Create user from contact $contact->setUserType(array_var($user_data, 'type')); if (array_var($user_data, 'company_id')) { $contact->setCompanyId(array_var($user_data, 'company_id')); } $contact->setUsername(array_var($user_data, 'username')); $contact->setTimezone(array_var($user_data, 'timezone')); } $contact->save(); if (is_valid_email(array_var($user_data, 'email'))) { $contact->addEmail(array_var($user_data, 'email'), 'personal', true); } //permissions $permission_group = new PermissionGroup(); $permission_group->setName('User '.$contact->getId().' Personal'); $permission_group->setContactId($contact->getId()); $permission_group->setIsContext(false); $permission_group->setType("permission_groups"); $permission_group->save(); $contact->setPermissionGroupId($permission_group->getId()); $contact_pg = new ContactPermissionGroup(); $contact_pg->setContactId($contact->getId()); $contact_pg->setPermissionGroupId($permission_group->getId()); $contact_pg->save(); if ( can_manage_security(logged_user()) ) { $sp = new SystemPermission(); $rol_permissions=SystemPermissions::getRolePermissions(array_var($user_data, 'type')); foreach($rol_permissions as $pr){ $sp->setPermission($pr); } $sp->setPermissionGroupId($permission_group->getId()); $sp->setCanManageSecurity(array_var($user_data, 'can_manage_security')); $sp->setCanManageConfiguration(array_var($user_data, 'can_manage_configuration')); $sp->setCanManageTemplates(array_var($user_data, 'can_manage_templates')); $sp->setCanManageTime(array_var($user_data, 'can_manage_time')); $sp->setCanAddMailAccounts(array_var($user_data, 'can_add_mail_accounts')); $sp->setCanManageDimensions(array_var($user_data, 'can_manage_dimensions')); $sp->setCanManageDimensionMembers(array_var($user_data, 'can_manage_dimension_members')); $sp->setCanManageTasks(array_var($user_data, 'can_manage_tasks')); $sp->setCanTasksAssignee(array_var($user_data, 'can_task_assignee')); $sp->setCanManageBilling(array_var($user_data, 'can_manage_billing')); $sp->setCanViewBilling(array_var($user_data, 'can_view_billing')); Hook::fire('add_user_permissions', $sp, $other_permissions); if (!is_null($other_permissions) && is_array($other_permissions)) { foreach ($other_permissions as $k => $v) { $sp->setColumnValue($k, array_var($user_data, $k)); } } $sp->save(); if ($contact->isAdminGroup()) { // allow all un all dimensions if new user is admin $dimensions = Dimensions::findAll(); $permissions = array(); foreach ($dimensions as $dimension) { if ($dimension->getDefinesPermissions()) { $cdp = ContactDimensionPermissions::findOne(array("conditions" => "`permission_group_id` = ".$contact->getPermissionGroupId()." AND `dimension_id` = ".$dimension->getId())); if (!$cdp instanceof ContactDimensionPermission) { $cdp = new ContactDimensionPermission(); $cdp->setPermissionGroupId($contact->getPermissionGroupId()); $cdp->setContactDimensionId($dimension->getId()); } $cdp->setPermissionType('allow all'); $cdp->save(); // contact member permisssion entries $members = $dimension->getAllMembers(); foreach ($members as $member) { $ots = DimensionObjectTypeContents::getContentObjectTypeIds($dimension->getId(), $member->getObjectTypeId()); $ots[]=$member->getObjectId(); foreach ($ots as $ot) { $cmp = ContactMemberPermissions::findOne(array("conditions" => "`permission_group_id` = ".$contact->getPermissionGroupId()." AND `member_id` = ".$member->getId()." AND `object_type_id` = $ot")); if (!$cmp instanceof ContactMemberPermission) { $cmp = new ContactMemberPermission(); $cmp->setPermissionGroupId($contact->getPermissionGroupId()); $cmp->setMemberId($member->getId()); $cmp->setObjectTypeId($ot); } $cmp->setCanWrite(1); $cmp->setCanDelete(1); $cmp->save(); // Add persmissions to sharing table $perm = new stdClass(); $perm->m = $member->getId(); $perm->r= 1; $perm->w= 1; $perm->d= 1; $perm->o= $ot; $permissions[] = $perm ; } } } } if(count($permissions)){ $sharingTableController = new SharingTableController(); $sharingTableController->afterPermissionChanged($contact->getPermissionGroupId(), $permissions); } } } if(!isset($_POST['sys_perm'])){ $rol_permissions=SystemPermissions::getRolePermissions(array_var($user_data, 'type')); $_POST['sys_perm']=array(); foreach($rol_permissions as $pr){ $_POST['sys_perm'][$pr]=1; } } if(!isset($_POST['mod_perm'])){ $tabs_permissions=TabPanelPermissions::getRoleModules(array_var($user_data, 'type')); $_POST['mod_perm']=array(); foreach($tabs_permissions as $pr){ $_POST['mod_perm'][$pr]=1; } } $password = ''; if (array_var($user_data, 'password_generator') == 'specify') { $perform_password_validation = true; // Validate input $password = array_var($user_data, 'password'); if (trim($password) == '') { throw new Error(lang('password value required')); } // if if ($password <> array_var($user_data, 'password_a')) { throw new Error(lang('passwords dont match')); } // if } else { $user_data['password_generator'] = 'link'; $perform_password_validation = false; } $contact->setPassword($password); $contact->save(); $user_password = new ContactPassword(); $user_password->setContactId($contact->getId()); $user_password->setPasswordDate(DateTimeValueLib::now()); $user_password->setPassword(cp_encrypt($password, $user_password->getPasswordDate()->getTimestamp())); $user_password->password_temp = $password; $user_password->perform_validation = $perform_password_validation; $user_password->save(); if (array_var($user_data, 'autodetect_time_zone', 1) == 1) { set_user_config_option('autodetect_time_zone', 1, $contact->getId()); } /* create contact for this user*/ ApplicationLogs::createLog($contact, ApplicationLogs::ACTION_ADD); // Set role permissions for active members $active_context = active_context(); $sel_members = array(); foreach ($active_context as $selection) { if ($selection instanceof Member) { $sel_members[] = $selection; $has_project_permissions = ContactMemberPermissions::instance()->count("permission_group_id = '".$contact->getPermissionGroupId()."' AND member_id = ".$selection->getId()) > 0; if (!$has_project_permissions) { RoleObjectTypePermissions::createDefaultUserPermissions($contact, $selection); } } } save_permissions($contact->getPermissionGroupId(), $contact->isGuest()); Hook::fire('after_user_add', $contact, $null); // add user content object to associated members if (count($sel_members) > 0) { ObjectMembers::addObjectToMembers($contact->getId(), $sel_members); $contact->addToSharingTable(); } // Send notification try { if (array_var($user_data, 'send_email_notification') && $contact->getEmailAddress()) { if (array_var($user_data, 'password_generator', 'link') == 'link') { // Generate link password $user = Contacts::getByEmail(array_var($user_data, 'email')); $token = sha1(gen_id() . (defined('SEED') ? SEED : '')); $timestamp = time() + 60*60*24; set_user_config_option('reset_password', $token . ";" . $timestamp, $user->getId()); Notifier::newUserAccountLinkPassword($contact, $password, $token); } else { Notifier::newUserAccount($contact, $password); } } } catch(Exception $e) { Logger::log($e->getTraceAsString()); } // try return $contact; }
/** * Used for Drag & Drop, adds objects to a member * @author alvaro */ function add_objects_to_member() { $ids = json_decode(array_var($_POST, 'objects')); $mem_id = array_var($_POST, 'member'); if (!is_array($ids) || count($ids) == 0) { ajx_current("empty"); return; } $member = Members::findById($mem_id); try { DB::beginWork(); $objects = array(); $from = array(); foreach ($ids as $oid) { /* @var $obj ContentDataObject */ $obj = Objects::findObject($oid); $dim_obj_type_content = DimensionObjectTypeContents::findOne(array('conditions' => array('`dimension_id`=? AND `dimension_object_type_id`=? AND `content_object_type_id`=?', $member->getDimensionId(), $member->getObjectTypeId(), $obj->getObjectTypeId()))); if (!$dim_obj_type_content instanceof DimensionObjectTypeContent) { continue; } if (!$dim_obj_type_content->getIsMultiple() || array_var($_POST, 'remove_prev')) { $db_res = DB::execute("SELECT group_concat(om.member_id) as old_members FROM " . TABLE_PREFIX . "object_members om INNER JOIN " . TABLE_PREFIX . "members m ON om.member_id=m.id WHERE m.dimension_id=" . $member->getDimensionId() . " AND om.object_id=" . $obj->getId()); $row = $db_res->fetchRow(); if (array_var($row, 'old_members') != "") { $from[$obj->getId()] = $row['old_members']; } // remove from previous members ObjectMembers::delete('`object_id` = ' . $obj->getId() . ' AND `member_id` IN (SELECT `m`.`id` FROM `' . TABLE_PREFIX . 'members` `m` WHERE `m`.`dimension_id` = ' . $member->getDimensionId() . ')'); } $obj->addToMembers(array($member)); $obj->addToSharingTable(); $objects[] = $obj; } DB::commit(); // add to application logs foreach ($objects as $object) { $action = array_var($from, $obj->getId()) ? ApplicationLogs::ACTION_MOVE : ApplicationLogs::ACTION_COPY; $log_data = (array_var($from, $obj->getId()) ? "from:" . array_var($from, $obj->getId()) . ";" : "") . "to:" . $member->getId(); ApplicationLogs::instance()->createLog($object, $action, false, true, true, $log_data); } $lang_key = count($ids) > 1 ? 'objects moved to member success' : 'object moved to member success'; flash_success(lang($lang_key, $member->getName())); if (array_var($_POST, 'reload')) { ajx_current('reload'); } else { ajx_current('empty'); } } catch (Exception $e) { DB::rollback(); ajx_current("empty"); flash_error(lang('unable to move objects')); } }
/** * 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