Ejemplo n.º 1
0
 /**
  * Edit task
  *
  * @access public
  * @param void
  * @return null
  */
 function edit_task()
 {
     $isTemplateTask = false;
     if (array_var($_REQUEST, 'template_task') == true) {
         $isTemplateTask = true;
     }
     if (logged_user()->isGuest()) {
         flash_error(lang('no access permissions'));
         ajx_current("empty");
         return;
     }
     $this->setTemplate('add_task');
     if (array_var($_REQUEST, "template_task")) {
         $task = TemplateTasks::findById(array_var($_REQUEST, "template_task_id", get_id()));
         $this->setTemplate(get_template_path('add_template_task', 'template_task'));
         if (array_var($_REQUEST, 'template_id')) {
             $template_id = array_var($_REQUEST, 'template_id');
         } else {
             $template_id = $task->getTemplateId();
         }
         tpl_assign('additional_tt_params', array_var($_REQUEST, 'additional_tt_params'));
         tpl_assign('template_id', $template_id);
         if (!$task instanceof TemplateTask) {
             flash_error(lang('task list dnx'));
             ajx_current("empty");
             return;
         }
         // if
     } else {
         $task = ProjectTasks::findById(get_id());
         if (!$task instanceof ProjectTask) {
             flash_error(lang('task list dnx'));
             ajx_current("empty");
             return;
         }
         // if
         if (!$task->canEdit(logged_user())) {
             flash_error(lang('no access permissions'));
             ajx_current("empty");
             return;
         }
         // if
     }
     if (array_var($_GET, 'replace')) {
         ajx_replace(true);
     }
     $task_data = array_var($_POST, 'task');
     $time_estimate = array_var($_POST, 'hours', 0) * 60 + array_var($_POST, 'minutes', 0);
     if ($time_estimate > 0) {
         $estimatedTime = $time_estimate;
     } else {
         $estimatedTime = $task->getTimeEstimate();
     }
     if (!is_array($task_data)) {
         // set layout for modal form
         if (array_var($_REQUEST, 'modal')) {
             $this->setLayout("json");
             tpl_assign('modal', true);
         }
         $this->getRepeatOptions($task, $occ, $rsel1, $rsel2, $rsel3, $rnum, $rend, $rjump);
         $dd = $task->getDueDate() instanceof DateTimeValue ? $task->getDueDate() : null;
         if ($dd instanceof DateTimeValue && $task->getUseDueTime()) {
             $dd->advance(logged_user()->getTimezone() * 3600);
         }
         $sd = $task->getStartDate() instanceof DateTimeValue ? $task->getStartDate() : null;
         if ($sd instanceof DateTimeValue && $task->getUseStartTime()) {
             $sd->advance(logged_user()->getTimezone() * 3600);
         }
         $post_dd = null;
         if (array_var($_POST, 'task_due_date')) {
             $post_dd = getDateValue(array_var($_POST, 'task_due_date'));
             if ($post_dd instanceof DateTimeValue) {
                 $duetime = getTimeValue(array_var($_POST, 'task_due_time'));
                 if (is_array($duetime)) {
                     $post_dd->setHour(array_var($duetime, 'hours'));
                     $post_dd->setMinute(array_var($duetime, 'mins'));
                     $post_dd->advance(logged_user()->getTimezone() * 3600);
                 }
             }
         }
         $post_st = null;
         if (array_var($_POST, 'task_start_date')) {
             $post_st = getDateValue(array_var($_POST, 'task_start_date'));
             if ($post_st instanceof DateTimeValue) {
                 $starttime = getTimeValue(array_var($_POST, 'task_start_time'));
                 if (is_array($starttime)) {
                     $post_st->setHour(array_var($starttime, 'hours'));
                     $post_st->setMinute(array_var($starttime, 'mins'));
                     $post_st->advance(logged_user()->getTimezone() * 3600);
                 }
             }
         }
         if (config_option("wysiwyg_tasks")) {
             $text_post = preg_replace("/[\n|\r|\n\r]/", '', array_var($_POST, 'text', $task->getText()));
         } else {
             $text_post = array_var($_POST, 'text', $task->getText());
         }
         $task_data = array('name' => array_var($_POST, 'name', $task->getObjectName()), 'text' => $text_post, 'milestone_id' => array_var($_POST, 'milestone_id', $task->getMilestoneId()), 'due_date' => getDateValue($post_dd, $dd), 'start_date' => getDateValue($post_st, $sd), 'parent_id' => $task->getParentId(), 'assigned_to_contact_id' => array_var($_POST, 'assigned_to_contact_id', $task->getAssignedToContactId()), 'selected_members_ids' => json_decode(array_var($_POST, 'members', null)), 'priority' => array_var($_POST, 'priority', $task->getPriority()), 'time_estimate' => $estimatedTime, 'percent_completed' => $task->getPercentCompleted(), 'forever' => $task->getRepeatForever(), 'rend' => $rend, 'rnum' => $rnum, 'rjump' => $rjump, 'rsel1' => $rsel1, 'rsel2' => $rsel2, 'rsel3' => $rsel3, 'occ' => $occ, 'repeat_by' => $task->getRepeatBy(), 'object_subtype' => array_var($_POST, "object_subtype", $task->getObjectSubtype() != 0 ? $task->getObjectSubtype() : config_option('default task co type')), 'type_content' => $task->getTypeContent(), 'multi_assignment' => $task->getColumnValue('multi_assignment', 0), 'send_notification_subscribers' => user_config_option("can notify subscribers"));
         // array
         //control dates of parent and subtasks
         $task_data['type_control'] = "";
         $parent_data = $task->getParent();
         if ($parent_data) {
             $task_data['type_control'] = "child";
             $task_data['control_title'] = $parent_data->getObjectName();
             $task_data['control_due_date'] = $parent_data->getDueDate() instanceof DateTimeValue ? $parent_data->getDueDate()->getTimestamp() + logged_user()->getTimezone() * 3600 : null;
             $task_data['control_start_date'] = $parent_data->getStartDate() instanceof DateTimeValue ? $parent_data->getStartDate()->getTimestamp() + logged_user()->getTimezone() * 3600 : null;
         }
         $subtask_data = $task->getAllSubTasks();
         if ($subtask_data) {
             $task_data['type_control'] = "father";
             $task_data['control_title'] = $task->getObjectName();
             $task_data['control_due_date'] = getDateValue($post_dd, $dd) instanceof DateTimeValue ? getDateValue($post_dd, $dd)->getTimestamp() : null;
             $task_data['control_start_date'] = getDateValue($post_st, $sd) instanceof DateTimeValue ? getDateValue($post_st, $sd)->getTimestamp() : null;
         }
     }
     // if
     //I find all those related to the task to find out if the original
     $task_related = ProjectTasks::findByRelated($task->getObjectId());
     if (!$task_related) {
         //is not the original as the original look plus other related
         if ($task->getOriginalTaskId() != "0") {
             $task_related = ProjectTasks::findByTaskAndRelated($task->getObjectId(), $task->getOriginalTaskId());
         }
     }
     if ($task_related) {
         $pending_id = 0;
         foreach ($task_related as $t_rel) {
             if ($task->getStartDate() <= $t_rel->getStartDate() && $task->getDueDate() <= $t_rel->getDueDate() && !$t_rel->isCompleted()) {
                 $pending_id = $t_rel->getId();
                 break;
             }
         }
         tpl_assign('pending_task_id', $pending_id);
         tpl_assign('task_related', true);
     } else {
         tpl_assign('pending_task_id', 0);
         tpl_assign('task_related', false);
     }
     tpl_assign('task', $task);
     tpl_assign('task_data', $task_data);
     if (is_array(array_var($_POST, 'task'))) {
         foreach ($task_data as $k => &$v) {
             $v = remove_scripts($v);
         }
         $send_edit = false;
         if ($task->getAssignedToContactId() == array_var($task_data, 'assigned_to_contact_id')) {
             $send_edit = true;
         }
         $old_owner = $task->getAssignedTo();
         if (array_var($task_data, 'parent_id') == $task->getId()) {
             flash_error(lang("task own parent error"));
             ajx_current("empty");
             return;
         }
         try {
             try {
                 $task_data['due_date'] = getDateValue(array_var($_POST, 'task_due_date'));
                 $task_data['start_date'] = getDateValue(array_var($_POST, 'task_start_date'));
             } catch (Exception $e) {
                 throw new Exception(lang('date format error', date_format_tip(user_config_option('date_format'))));
             }
             if ($task_data['due_date'] instanceof DateTimeValue) {
                 $duetime = getTimeValue(array_var($_POST, 'task_due_time'));
                 if (is_array($duetime)) {
                     $task_data['due_date']->setHour(array_var($duetime, 'hours'));
                     $task_data['due_date']->setMinute(array_var($duetime, 'mins'));
                     $task_data['due_date']->advance(logged_user()->getTimezone() * -3600);
                 }
                 $task_data['use_due_time'] = is_array($duetime);
             }
             if ($task_data['start_date'] instanceof DateTimeValue) {
                 $starttime = getTimeValue(array_var($_POST, 'task_start_time'));
                 if (is_array($starttime)) {
                     $task_data['start_date']->setHour(array_var($starttime, 'hours'));
                     $task_data['start_date']->setMinute(array_var($starttime, 'mins'));
                     $task_data['start_date']->advance(logged_user()->getTimezone() * -3600);
                 }
                 $task_data['use_start_time'] = is_array($starttime);
             }
             //control date subtask whit parent
             if (array_var($_POST, 'control_dates') == "child") {
                 $parent = $task->getParent();
                 if ($parent->getStartDate() instanceof DateTimeValue && $task_data['start_date'] instanceof DateTimeValue) {
                     if ($task_data['start_date']->getTimestamp() < $parent->getStartDate()->getTimestamp()) {
                         $parent->setStartDate($task_data['start_date']);
                         $parent->setUseStartTime($task_data['use_start_time']);
                     }
                 } else {
                     $parent->setStartDate($task_data['start_date']);
                     $parent->setUseStartTime(array_var($task_data, 'use_start_time', 0));
                 }
                 if ($parent->getDueDate() instanceof DateTimeValue && $task_data['due_date'] instanceof DateTimeValue) {
                     if ($task_data['due_date']->getTimestamp() > $parent->getDueDate()->getTimestamp()) {
                         $parent->setDueDate($task_data['due_date']);
                         $parent->setUseDueTime($task_data['use_due_time']);
                     }
                 } else {
                     $parent->setDueDate($task_data['due_date']);
                     $parent->setUseDueTime(array_var($task_data, 'use_due_time', 0));
                 }
                 // calculate and set estimated time
                 $totalMinutes = array_var($task_data, 'time_estimate_hours') * 60 + array_var($task_data, 'time_estimate_minutes');
                 $parent->setTimeEstimate($totalMinutes);
                 $parent->save();
             }
             $err_msg = $this->setRepeatOptions($task_data);
             if ($err_msg) {
                 throw new Exception($err_msg);
             }
             if (!isset($task_data['parent_id'])) {
                 $task_data['parent_id'] = 0;
             }
             $member_ids = json_decode(array_var($_POST, 'members'));
             // keep old dates to check for subtasks
             $old_start_date = $task->getStartDate();
             $old_due_date = $task->getDueDate();
             if (config_option("wysiwyg_tasks")) {
                 $task_data['type_content'] = "html";
                 $task_data['text'] = str_replace(array("\r", "\n", "\r\n"), array('', '', ''), array_var($task_data, 'text'));
             } else {
                 $task_data['type_content'] = "text";
             }
             $task->setFromAttributes($task_data);
             $totalMinutes = array_var($task_data, 'time_estimate_hours') * 60 + array_var($task_data, 'time_estimate_minutes');
             $task->setTimeEstimate($totalMinutes);
             if ($task->getParentId() > 0 && $task->hasChild($task->getParentId())) {
                 flash_error(lang('task child of child error'));
                 ajx_current("empty");
                 return;
             }
             if (isset($task_data['percent_completed']) && $task_data['percent_completed'] >= 0 && $task_data['percent_completed'] <= 100) {
                 $task->setPercentCompleted($task_data['percent_completed']);
             }
             DB::beginWork();
             $task->save();
             if (!isset($task_data['percent_completed'])) {
                 $task->calculatePercentComplete();
             }
             // dependencies
             if (config_option('use tasks dependencies')) {
                 $previous_tasks = array_var($task_data, 'previous');
                 if (is_array($previous_tasks)) {
                     foreach ($previous_tasks as $ptask) {
                         if ($ptask == $task->getId()) {
                             continue;
                         }
                         $dep = ProjectTaskDependencies::findById(array('previous_task_id' => $ptask, 'task_id' => $task->getId()));
                         if (!$dep instanceof ProjectTaskDependency) {
                             $dep = new ProjectTaskDependency();
                             $dep->setPreviousTaskId($ptask);
                             $dep->setTaskId($task->getId());
                             $dep->save();
                         }
                     }
                     $saved_ptasks = ProjectTaskDependencies::findAll(array('conditions' => 'task_id = ' . $task->getId()));
                     foreach ($saved_ptasks as $pdep) {
                         if (!in_array($pdep->getPreviousTaskId(), $previous_tasks)) {
                             $pdep->delete();
                         }
                     }
                 } else {
                     ProjectTaskDependencies::delete('task_id = ' . $task->getId());
                 }
             }
             // Add assigned user to the subscibers list
             if ($task->getAssignedToContactId() > 0 && Contacts::instance()->findById($task->getAssignedToContactId())) {
                 if (!isset($_POST['subscribers'])) {
                     $_POST['subscribers'] = array();
                 }
                 $_POST['subscribers']['user_' . $task->getAssignedToContactId()] = '1';
             }
             $object_controller = new ObjectController();
             if ($isTemplateTask) {
                 $object_controller->add_to_members($task, $member_ids, null, false);
             } else {
                 $object_controller->add_to_members($task, $member_ids);
             }
             $is_template = $task instanceof TemplateTask;
             $object_controller->add_subscribers($task, null, !$is_template);
             $object_controller->link_to_new_object($task);
             $object_controller->add_custom_properties($task);
             if (!$task->isCompleted()) {
                 //to make sure the task it is not completed yet, and that it has subscribed people
                 $old_reminders = ObjectReminders::getByObject($task);
                 $object_controller->add_reminders($task);
                 //adding the new reminders, if any
                 $object_controller->update_reminders($task, $old_reminders);
                 //updating the old ones
                 if (logged_user() instanceof Contact && (!is_array($old_reminders) || count($old_reminders) == 0) && (user_config_option("add_task_autoreminder") && logged_user()->getId() != $task->getAssignedToContactId() || user_config_option("add_self_task_autoreminder") && logged_user()->getId() == $task->getAssignedToContactId())) {
                     //if there is no asignee, but it still has subscribers
                     $reminder = new ObjectReminder();
                     $def = explode(",", user_config_option("reminders_tasks"));
                     $minutes = $def[2] * $def[1];
                     $reminder->setMinutesBefore($minutes);
                     $reminder->setType($def[0]);
                     $reminder->setContext("due_date");
                     $reminder->setObject($task);
                     $reminder->setUserId(0);
                     $date = $task->getDueDate();
                     if ($date instanceof DateTimeValue) {
                         $rdate = new DateTimeValue($date->getTimestamp() - $minutes * 60);
                         $reminder->setDate($rdate);
                     }
                     $reminder->save();
                 }
             }
             if (!is_array($member_ids) || count($member_ids) == 0) {
                 $member_ids = array(0);
             }
             $members = Members::findAll(array('conditions' => "id IN (" . implode(',', $member_ids) . ")"));
             $task->apply_members_to_subtasks($members, true);
             // apply values to subtasks
             $assigned_to = $task->getAssignedToContactId();
             $subtasks = $task->getAllSubTasks();
             $milestone_id = $task->getMilestoneId();
             $apply_ms = array_var($task_data, 'apply_milestone_subtasks');
             $apply_at = array_var($task_data, 'apply_assignee_subtasks', '');
             foreach ($subtasks as $sub) {
                 $modified = false;
                 //if ($apply_at || !($sub->getAssignedToContactId() > 0)) {
                 if ($apply_at) {
                     $sub->setAssignedToContactId($assigned_to);
                     $modified = true;
                 }
                 if ($apply_ms) {
                     $sub->setMilestoneId($milestone_id);
                     $modified = true;
                 }
                 if ($modified) {
                     $sub->save();
                 }
                 //control date parent whit subtask
                 if ($_POST['control_dates'] == "father") {
                     if ($sub->getStartDate() instanceof DateTimeValue) {
                         if ($task->getStartDate() instanceof DateTimeValue) {
                             if ($task->getStartDate()->getTimestamp() > $sub->getStartDate()->getTimestamp()) {
                                 $sub->setStartDate($task->getStartDate());
                             }
                         }
                     } else {
                         if ($task->getStartDate() instanceof DateTimeValue) {
                             $sub->setStartDate($task->getStartDate());
                         }
                     }
                     $sub->setUseStartTime($task->getUseStartTime());
                     if ($sub->getDueDate() instanceof DateTimeValue) {
                         if ($task->getDueDate() instanceof DateTimeValue) {
                             if ($task->getDueDate()->getTimestamp() < $sub->getDueDate()->getTimestamp()) {
                                 $sub->setDueDate($task->getDueDate());
                             }
                         }
                     } else {
                         if ($task->getDueDate() instanceof DateTimeValue) {
                             $sub->setDueDate($task->getDueDate());
                         }
                     }
                     $sub->setUseDueTime($task->getUseDueTime());
                     $sub->save();
                 }
             }
             $task->resetIsRead();
             $log_info = '';
             if ($send_edit == true) {
                 $log_info = $task->getAssignedToContactId();
             } else {
                 if ($send_edit == false) {
                     $task->setAssignedBy(logged_user());
                     $task->save();
                 }
             }
             if (config_option('repeating_task') == 1) {
                 $opt_rep_day['saturday'] = false;
                 $opt_rep_day['sunday'] = false;
                 if (array_var($task_data, 'repeat_saturdays', false)) {
                     $opt_rep_day['saturday'] = true;
                 }
                 if (array_var($task_data, 'repeat_sundays', false)) {
                     $opt_rep_day['sunday'] = true;
                 }
                 $this->repetitive_task($task, $opt_rep_day);
             }
             if (isset($_POST['type_related'])) {
                 if ($_POST['type_related'] == "all" || $_POST['type_related'] == "news") {
                     $task_data['members'] = json_decode(array_var($_POST, 'members'));
                     unset($task_data['due_date']);
                     unset($task_data['use_due_time']);
                     unset($task_data['start_date']);
                     unset($task_data['use_start_time']);
                     $this->repetitive_tasks_related($task, "edit", $_POST['type_related'], $task_data);
                 }
             }
             if (config_option('multi_assignment') && Plugins::instance()->isActivePlugin('crpm')) {
                 if (array_var($task_data, 'multi_assignment_aplly_change') == 'subtask') {
                     $null = null;
                     Hook::fire('edit_subtasks', $task, $null);
                 }
             }
             //for calculate member status we save de task again after the object have the members
             $task->save();
             // save subtasks added in 'subtasks' tab
             $sub_tasks_to_log = $this->saveSubtasks($task, array_var($task_data, 'subtasks'), $member_ids);
             DB::commit();
             foreach ($sub_tasks_to_log['add'] as $st_to_log) {
                 ApplicationLogs::createLog($st_to_log, ApplicationLogs::ACTION_ADD);
             }
             foreach ($sub_tasks_to_log['edit'] as $st_to_log) {
                 ApplicationLogs::createLog($st_to_log, ApplicationLogs::ACTION_EDIT);
             }
             foreach ($sub_tasks_to_log['trash'] as $st_to_log) {
                 ApplicationLogs::createLog($st_to_log, ApplicationLogs::ACTION_TRASH);
             }
             //Send Template task to view
             if ($task instanceof TemplateTask) {
                 $objectId = $task->getObjectId();
                 $id = $task->getId();
                 $objectTypeName = $task->getObjectTypeName();
                 $objectName = $task->getObjectName();
                 $manager = get_class($task->manager());
                 $milestoneId = $task instanceof TemplateTask ? $task->getMilestoneId() : '0';
                 $subTasks = $task->getSubTasks();
                 $parentId = $task->getParentId();
                 $ico = "ico-task";
                 $action = "edit";
                 $object = TemplateController::prepareObject($objectId, $id, $objectName, $objectTypeName, $manager, $action, $milestoneId, $subTasks, $parentId, $ico);
                 $template_task_data = array('object' => $object);
                 if (array_var($_REQUEST, 'additional_tt_params')) {
                     $additional_tt_params = json_decode(str_replace("'", '"', array_var($_REQUEST, 'additional_tt_params')), true);
                     foreach ($additional_tt_params as $k => $v) {
                         $template_task_data[$k] = $v;
                     }
                 }
                 if (!array_var($_REQUEST, 'modal')) {
                     evt_add("template object added", $template_task_data);
                 }
             }
             try {
                 // notify asignee
                 if (array_var($task_data, 'send_notification') && $task->getAssignedToContactId() != $task->getAssignedById()) {
                     $new_owner = $task->getAssignedTo();
                     if ($new_owner instanceof Contact) {
                         Notifier::taskAssigned($task);
                     }
                     // if
                 }
                 // if
                 if (array_var($task_data, 'send_notification')) {
                     foreach ($sub_tasks_to_log['assigned'] as $st_to_log) {
                         Notifier::taskAssigned($st_to_log);
                     }
                 }
             } catch (Exception $e) {
             }
             // try
             //notify subscribers
             $isSilent = true;
             if (array_var($task_data, 'send_notification_subscribers')) {
                 $isSilent = false;
             }
             ApplicationLogs::createLog($task, ApplicationLogs::ACTION_EDIT, false, false, true, $log_info);
             //flash_success(lang('success edit task list', $task->getObjectName()));
             if (array_var($_REQUEST, 'modal')) {
                 if (array_var($_REQUEST, 'reload')) {
                     evt_add("reload current panel");
                 } else {
                     ajx_current("empty");
                     $this->setLayout("json");
                     $this->setTemplate(get_template_path("empty"));
                     // reload task info because plugins may have updated some task info (for example: name prefix)
                     if ($is_template) {
                         $task = TemplateTasks::findById($task->getId());
                     } else {
                         $task = ProjectTasks::findById($task->getId());
                     }
                     $params = array('msg' => lang('success edit task list', $task->getObjectName()), 'task' => $task->getArrayInfo(), 'reload' => array_var($_REQUEST, 'reload'));
                     if ($task instanceof TemplateTask) {
                         //$params['msg'] = lang('success edit template', $task->getObjectName());
                         $params['object'] = $template_task_data['object'];
                     }
                     //print_modal_json_response($params, true, array_var($_REQUEST, 'use_ajx'));
                     ajx_extra_data($params);
                 }
             } else {
                 ajx_current("back");
             }
             // if has subtasks and dates were changed, ask the user if the subtasks dates should also be changed
             if ($task instanceof ProjectTask && $task->countOpenSubTasks() > 0) {
                 // check if there was any due date changes
                 $dd_advance_info = null;
                 if ($task->getDueDate() instanceof DateTimeValue && $old_due_date instanceof DateTimeValue && $old_due_date->getTimestamp() != $task->getDueDate()->getTimestamp()) {
                     $dd_to_advance_ts = $task->getDueDate()->getTimestamp() - $old_due_date->getTimestamp();
                     if ($dd_to_advance_ts != 0) {
                         $dd_advance_info = get_time_info($dd_to_advance_ts);
                     }
                 }
                 // check if there was any start date changes
                 $sd_advance_info = null;
                 if ($task->getStartDate() instanceof DateTimeValue && $old_start_date instanceof DateTimeValue && $old_start_date->getTimestamp() != $task->getStartDate()->getTimestamp()) {
                     $sd_to_advance_ts = $task->getStartDate()->getTimestamp() - $old_start_date->getTimestamp();
                     if ($sd_to_advance_ts != 0) {
                         $sd_advance_info = get_time_info($sd_to_advance_ts);
                     }
                 }
                 if ($dd_advance_info != null || $sd_advance_info != null) {
                     evt_add('ask to change subtasks dates', array('dd_diff' => $dd_advance_info, 'sd_diff' => $sd_advance_info, 'task_id' => $task->getId()));
                 }
             }
         } catch (Exception $e) {
             DB::rollback();
             if (array_var($_REQUEST, 'modal')) {
                 $this->setLayout("json");
                 $this->setTemplate(get_template_path("empty"));
                 print_modal_json_response(array('errorCode' => 1, 'errorMessage' => $e->getMessage(), 'showMessage' => 1), true, array_var($_REQUEST, 'use_ajx'));
             } else {
                 flash_error($e->getMessage());
             }
             ajx_current("empty");
         }
         // try
     }
     // if
 }
Ejemplo n.º 2
0
 function findByTaskAndRelated($task_id, $original_task_id)
 {
     return TemplateTasks::findAll(array('conditions' => array('(`original_task_id` = ? OR `object_id` = ?) AND `object_id` <> ?', $original_task_id, $original_task_id, $task_id)));
 }
 /**
  * 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, 'TemplateTasks')) {
         return parent::paginate($arguments, $items_per_page, $current_page);
     } else {
         return TemplateTasks::instance()->paginate($arguments, $items_per_page, $current_page);
     }
     // if
 }
 function get_template_tasks_data()
 {
     ajx_current("empty");
     $ids = explode(',', array_var($_REQUEST, 'ids'));
     foreach ($ids as $k => &$id) {
         if (!is_numeric($id)) {
             unset($ids[$k]);
         }
     }
     $objects = array();
     if (count($ids) > 0) {
         $tasks = TemplateTasks::findAll(array('conditions' => 'id IN (' . implode(',', $ids) . ')'));
         $ot = ObjectTypes::findByName('template_task');
         foreach ($tasks as $task) {
             $objects[] = $this->prepareObject($task->getId(), $task->getId(), $task->getObjectName(), $ot->getName(), $task->manager(), "", $task->getMilestoneId(), array(), $task->getParentId(), 'ico-task');
         }
     }
     ajx_extra_data(array('tasks' => $objects));
 }
			<?php 
    } else {
        $k = 0;
        ?>
				<script>
					og.previousTasks=[];
					og.previousTasksIdx = '<?php 
        echo count($previous_tasks);
        ?>
';
				</script>
				<input type="hidden" name="task[clean_dep]" value="1" />
				
				<?php 
        foreach ($previous_tasks as $task_dep) {
            $task = TemplateTasks::findById($task_dep->getPreviousTaskId());
            ?>
					<div class="og-add-template-object previous-task">
						<input type="hidden" name="task[previous]['<?php 
            echo $k;
            ?>
']" value="<?php 
            echo $task->getId();
            ?>
" />
						<div class="previous-task-name action-ico ico-task"><?php 
            echo clean($task->getTitle());
            ?>
</div>
						<a href="#" onclick="og.removePreviousTask(this.parentNode, '<?php 
            echo $genid;
 /**
  * Drop all tasks that are in this list
  *
  * @access public
  * @param void
  * @return boolean
  */
 function deleteSubTasks()
 {
     return TemplateTasks::delete(DB::escapeField('parent_id') . ' = ' . DB::escape($this->getId()));
 }
Ejemplo n.º 7
0
 function list_objects()
 {
     /* get query parameters */
     $filesPerPage = config_option('files_per_page');
     $start = array_var($_GET, 'start') ? (int) array_var($_GET, 'start') : 0;
     $limit = array_var($_GET, 'limit') ? array_var($_GET, 'limit') : $filesPerPage;
     $order = array_var($_GET, 'sort');
     $id_no_select = array_var($_GET, 'id_no_select', "undefined");
     $ignore_context = (bool) array_var($_GET, 'ignore_context');
     $member_ids = json_decode(array_var($_GET, 'member_ids'));
     $extra_member_ids = json_decode(array_var($_GET, 'extra_member_ids'));
     $orderdir = array_var($_GET, 'dir');
     if (!in_array(strtoupper($orderdir), array('ASC', 'DESC'))) {
         $orderdir = 'ASC';
     }
     if ($order == "dateUpdated") {
         $order = "updated_on";
     } elseif ($order == "dateArchived") {
         $order = "archived_on";
     } elseif ($order == "dateDeleted") {
         $order = "trashed_on";
     } elseif ($order == "name") {
         $order = "name";
     } else {
         $order = "";
         $orderdir = "";
     }
     $extra_list_params = array_var($_GET, 'extra_list_params');
     $extra_list_params = json_decode($extra_list_params);
     $page = (int) ($start / $limit) + 1;
     $hide_private = !logged_user()->isMemberOfOwnerCompany();
     $typeCSV = array_var($_GET, 'type');
     $types = null;
     if ($typeCSV) {
         $types = explode(",", $typeCSV);
     }
     $name_filter = mysql_real_escape_string(array_var($_GET, 'name'));
     $linked_obj_filter = array_var($_GET, 'linkedobject');
     $object_ids_filter = '';
     $show_all_linked_objects = false;
     if (!is_null($linked_obj_filter)) {
         $show_all_linked_objects = true;
         $linkedObject = Objects::findObject($linked_obj_filter);
         $objs = $linkedObject->getLinkedObjects();
         foreach ($objs as $obj) {
             $object_ids_filter .= ($object_ids_filter == '' ? '' : ',') . $obj->getId();
         }
     }
     $filters = array();
     if (!is_null($types)) {
         $filters['types'] = $types;
     }
     if (!is_null($name_filter)) {
         $filters['name'] = $name_filter;
     }
     if ($object_ids_filter != '') {
         $filters['object_ids'] = $object_ids_filter;
     }
     $user = array_var($_GET, 'user');
     $trashed = array_var($_GET, 'trashed', false);
     $archived = array_var($_GET, 'archived', false);
     /* if there's an action to execute, do so */
     if (!$show_all_linked_objects) {
         $this->processListActions();
     }
     $filterName = array_var($_GET, 'name');
     $template_object_names = "";
     $template_extra_condition = "true";
     $template_objects = false;
     if (in_array("template_task", array_var($filters, 'types', array())) || in_array("template_milestone", array_var($filters, 'types', array()))) {
         $template_id = 0;
         $template_objects = true;
         if (isset($extra_list_params->template_id)) {
             $template_id = $extra_list_params->template_id;
         }
         $tmpl_task = TemplateTasks::findById(intval($id_no_select));
         if ($tmpl_task instanceof TemplateTask) {
             $template_extra_condition = "o.id IN (SELECT object_id from " . TABLE_PREFIX . "template_tasks WHERE `template_id`=" . $tmpl_task->getTemplateId() . " OR `template_id`=0 AND `session_id`=" . logged_user()->getId() . " )";
         } else {
             $template_extra_condition = "o.id IN (SELECT object_id from " . TABLE_PREFIX . "template_tasks WHERE `template_id`=" . intval($template_id) . " OR `template_id`=0 AND `session_id`=" . logged_user()->getId() . " )";
         }
     } else {
         $template_object_names = "AND name <> 'template_task' AND name <> 'template_milestone'";
     }
     $result = null;
     $context = active_context();
     $obj_type_types = array('content_object', 'dimension_object');
     if (array_var($_GET, 'include_comments')) {
         $obj_type_types[] = 'comment';
     }
     $type_condition = "";
     if ($types) {
         $type_condition = " AND name IN ('" . implode("','", $types) . "')";
     }
     $extra_conditions = array();
     // user filter
     if (in_array("contact", array_var($filters, 'types', array())) && isset($extra_list_params->is_user)) {
         $joins[] = "\r\n\t\t\t\tLEFT JOIN " . TABLE_PREFIX . "contacts c on c.object_id=o.id";
         $extra_conditions[] = "\r\n\t\t\t\tc.user_type " . ($extra_list_params->is_user == 1 ? ">" : "=") . " 0";
         if (isset($extra_list_params->has_permissions) && $extra_list_params->has_permissions > 0) {
             $mem_id = $extra_list_params->has_permissions;
             $extra_conditions[] = " EXISTS (\r\n\t\t\t\t\tSELECT cmp.permission_group_id FROM " . TABLE_PREFIX . "contact_member_permissions cmp\r\n\t\t\t\t\tWHERE cmp.permission_group_id IN (SELECT x.permission_group_id FROM " . TABLE_PREFIX . "contact_permission_groups x WHERE x.contact_id=o.id)\r\n\t\t\t\t\tAND cmp.member_id='{$mem_id}' \r\n\t\t\t\t\tAND cmp.object_type_id NOT IN (SELECT tp.object_type_id FROM " . TABLE_PREFIX . "tab_panels tp WHERE tp.enabled=0)\r\n\t\t\t\t\tAND cmp.object_type_id NOT IN (SELECT oott.id FROM " . TABLE_PREFIX . "object_types oott WHERE oott.name IN ('comment','template'))\r\n\t\t\t\t\tAND cmp.object_type_id IN (SELECT oott2.id FROM " . TABLE_PREFIX . "object_types oott2 WHERE oott2.type IN ('content_object','dimension_object'))\r\n\t\t\t\t)";
         }
     }
     // Object type filter - exclude template types (if not template picker), filter by required type names (if specified) and match value with objects table
     $extra_object_type_conditions = "\r\n\t\t\tAND name <> 'file revision' {$template_object_names} {$type_condition} AND o.object_type_id = ot.id";
     $extra_conditions[] = ObjectTypes::getListableObjectsSqlCondition($extra_object_type_conditions);
     // --
     // logged user permission group ids
     $logged_user_pg_ids = implode(',', logged_user()->getPermissionGroupIds());
     // used in template object picker
     $extra_conditions[] = $template_extra_condition;
     // when filtering by name
     if ($name_filter) {
         $extra_conditions[] = "\r\n\t\t\t\tname LIKE '%{$name_filter}%'";
     }
     // when excluding some object in particular
     if ($id_no_select != "undefined") {
         $extra_conditions[] = "\r\n\t\t\t\tid <> '{$id_no_select}'";
     }
     // when filtering by some group of objects, for example in the linked objects view
     if ($object_ids_filter != "") {
         $extra_conditions[] = "\r\n\t\t\t\tid in ({$object_ids_filter})";
     }
     $joins[] = "\r\n\t\t\tLEFT JOIN " . TABLE_PREFIX . "project_tasks pt on pt.object_id=o.id";
     if (!SystemPermissions::userHasSystemPermission(logged_user(), 'can_see_assigned_to_other_tasks')) {
         // exclude other users' tasks if cannot see them
         $extra_conditions[] = "\r\n\t\t\t\t( pt.assigned_to_contact_id IS NULL OR pt.assigned_to_contact_id= " . logged_user()->getId() . ")";
     }
     // don't include tasks which have is_template=1
     $extra_conditions[] = "\r\n\t\t\t( pt.is_template IS NULL OR pt.is_template=0)";
     // trashed conditions
     $extra_conditions[] = "\r\n\t\t\to.trashed_on" . ($trashed ? "<>" : "=") . "0";
     // archived conditions
     $extra_conditions[] = "\r\n\t\t\to.archived_on" . ($archived ? "<>" : "=") . "0";
     // don't include unclassified mails from other accounts
     if (Plugins::instance()->isActivePlugin('mail')) {
         $accounts_of_loggued_user = MailAccountContacts::getByContact(logged_user());
         $account_ids = array(0);
         foreach ($accounts_of_loggued_user as $acc) {
             $account_ids[] = $acc->getAccountId();
         }
         $joins[] = "\r\n\t\t\t\tLEFT JOIN " . TABLE_PREFIX . "mail_contents mc on mc.object_id=o.id\r\n\t\t\t";
         $extra_conditions[] = "\r\n\t\t\t\tIF( mc.account_id IS NULL, true, mc.account_id IN (" . implode(',', $account_ids) . ") OR EXISTS (\r\n\t\t\t\t\tSELECT om1.object_id FROM " . TABLE_PREFIX . "object_members om1 \r\n\t\t\t\t\t\tINNER JOIN " . TABLE_PREFIX . "members m1 ON m1.id=om1.member_id \r\n\t\t\t\t\t\tINNER JOIN " . TABLE_PREFIX . "dimensions d1 ON d1.id=m1.dimension_id \r\n\t\t\t\t\tWHERE om1.object_id=o.id AND d1.is_manageable=1)\r\n\t\t\t\t)";
     }
     // don't show attached files of emails that cannot be viewed
     if (logged_user()->isAdministrator() && Plugins::instance()->isActivePlugin('mail')) {
         $joins[] = "LEFT JOIN " . TABLE_PREFIX . "project_files pf on pf.object_id=o.id";
         $extra_conditions[] = "IF(pf.mail_id IS NULL OR pf.mail_id = 0, true, \r\n\t\t\t\tpf.mail_id IN (SELECT sh.object_id FROM " . TABLE_PREFIX . "sharing_table sh WHERE pf.mail_id = sh.object_id AND sh.group_id  IN ({$logged_user_pg_ids})))";
     }
     $only_count_result = array_var($_GET, 'only_result', false);
     $count_results = array_var($_GET, 'count_results', false);
     // Members filter
     $sql_members = "";
     if (!$ignore_context && !$member_ids) {
         $members = active_context_members(false);
         // Context Members Ids
     } elseif (count($member_ids)) {
         $members = $member_ids;
     } else {
         // get members from context
         if (!$ignore_context) {
             $members = active_context_members(false);
         }
     }
     if (is_array($extra_member_ids)) {
         if (isset($members)) {
             $members = array_merge($members, $extra_member_ids);
         } else {
             $members = $extra_member_ids;
         }
     }
     if (isset($members) && is_array($members) && count($members) > 0 && !(isset($template_id) && $template_id > 0)) {
         $sql_members = "\r\n\t\t\t\tAND (EXISTS (SELECT om.object_id\r\n\t\t\t\t\tFROM  " . TABLE_PREFIX . "object_members om\r\n\t\t\t\t\tWHERE om.member_id IN (" . implode(',', $members) . ") AND o.id = om.object_id \r\n\t\t\t\t\tGROUP BY object_id\r\n\t\t\t\t\tHAVING count(member_id) = " . count($members) . "\r\n\t\t\t\t))\r\n\t\t\t";
     }
     // --
     // Permissions filter
     if (isset($template_id) && $template_id > 0) {
         // editing template items do not check permissions
         $sql_permissions = "";
     } else {
         $sql_permissions = "\r\n\t\t\t\tAND EXISTS (SELECT sh.object_id FROM " . TABLE_PREFIX . "sharing_table sh WHERE sh.object_id=o.id AND sh.group_id IN ({$logged_user_pg_ids}))\r\n\t\t\t";
     }
     // Main select
     $sql_select = "SELECT * FROM " . TABLE_PREFIX . "objects o ";
     // Joins
     $sql_joins = implode(" ", $joins);
     // Where
     $sql_where = "\r\n\t\t\tWHERE " . implode(" AND ", $extra_conditions) . $sql_permissions . $sql_members;
     // Order
     $sql_order = "";
     if ($order) {
         $sql_order = "\r\n\t\t\t\tORDER BY {$order} {$orderdir}\r\n\t\t\t";
     }
     // Limit
     $sql_limit = "";
     if ($start >= 0 && $limit > 0) {
         $sql_limit = " LIMIT {$start}, {$limit}";
     }
     // Full SQL
     $sql = "{$sql_select} {$sql_joins} {$sql_where} {$sql_order} {$sql_limit}";
     // Execute query
     if (!$only_count_result) {
         $rows = DB::executeAll($sql);
     }
     // get total items
     if ($count_results) {
         $sql_count = "SELECT count(o.id) as total_items FROM " . TABLE_PREFIX . "objects o {$sql_joins} {$sql_where}";
         $rows_count = DB::executeAll($sql_count);
         $total_items = $rows_count[0]['total_items'];
     } else {
         if (isset($rows) && is_array($rows)) {
             $total_items = count($rows) < $filesPerPage ? count($rows) : 1000000;
         } else {
             $total_items = 0;
         }
     }
     // prepare response object
     $info = array();
     // get objects
     if (isset($rows) && is_array($rows)) {
         foreach ($rows as $row) {
             $instance = Objects::findObject($row['id']);
             if (!$instance instanceof ContentDataObject) {
                 continue;
             }
             $info_elem = $instance->getObject()->getArrayInfo();
             $info_elem['url'] = $instance->getViewUrl();
             $info_elem['isRead'] = $instance->getIsRead(logged_user()->getId());
             $info_elem['manager'] = get_class($instance->manager());
             $info_elem['memPath'] = json_encode($instance->getMembersIdsToDisplayPath());
             if ($instance instanceof Contact) {
                 if ($instance->isCompany()) {
                     $info_elem['icon'] = 'ico-company';
                     $info_elem['type'] = 'company';
                 } else {
                     $info_elem['memPath'] = json_encode($instance->getUserType() ? "" : $instance->getMembersIdsToDisplayPath());
                 }
             } else {
                 if ($instance instanceof ProjectFile) {
                     $info_elem['mimeType'] = $instance->getTypeString();
                 }
             }
             $info[] = $info_elem;
         }
     }
     $listing = array("totalCount" => $total_items, "start" => $start, "objects" => $info);
     ajx_extra_data($listing);
     tpl_assign("listing", $listing);
     if (isset($reload) && $reload) {
         ajx_current("reload");
     } else {
         ajx_current("empty");
     }
 }
 /**
  * Copies tasks from milestoneFrom to milestoneTo.
  *
  * @param TemplateMilestone $milestoneFrom
  * @param TemplateMilestone $milestoneTo
  */
 function copyTasks(TemplateMilestone $milestoneFrom, TemplateMilestone $milestoneTo, $as_template = false)
 {
     //FIXME
     foreach ($milestoneFrom->getTasks($as_template) as $sub) {
         if ($sub->getParentId() != 0) {
             continue;
         }
         $new = TemplateTasks::createTaskCopy($sub);
         $new->setMilestoneId($milestoneTo->getId());
         $new->save();
         $object_controller = new ObjectController();
         $members = $milestoneFrom->getMemberIds();
         if (count($members)) {
             $object_controller->add_to_members($new, $members);
         }
         /*
         			foreach ($sub->getWorkspaces() as $workspace) {
         				if (TemplateTask::canAdd(logged_user(), $workspace)) {
         					$new->addToWorkspace($workspace);
         				}
         			}
         
         			if (!$as_template && active_project() instanceof Project && TemplateTask::canAdd(logged_user(), active_project())) {
         				$new->removeFromAllWorkspaces();
         				$new->addToWorkspace(active_project());
         			}
         */
         $new->copyCustomPropertiesFrom($sub);
         $new->copyLinkedObjectsFrom($sub);
         TemplateTasks::copySubTasks($sub, $new, $as_template);
     }
 }
Ejemplo n.º 9
0
/**
 * Return true if $user can add an object of type $object_type_id in $member. False otherwise.
 *
 * @param Contact $user
 * @param Member $member
 * @param array $context_members
 * @param $object_type_id
 * @return boolean
 */
function can_add_to_member(Contact $user, $member, $context_members, $object_type_id, $check_dimension = true)
{
    if (TemplateTasks::instance()->getObjectTypeId() == $object_type_id) {
        $object_type_id = ProjectTasks::instance()->getObjectTypeId();
    }
    if (TemplateMilestones::instance()->getObjectTypeId() == $object_type_id) {
        $object_type_id = ProjectMilestones::instance()->getObjectTypeId();
    }
    if (!$member instanceof Member && is_array($member) && isset($member['id'])) {
        $member = Members::findById($member['id']);
    }
    if ($user->isGuest() || !$member || !$member->canContainObject($object_type_id)) {
        return false;
    }
    try {
        $contact_pg_ids = ContactPermissionGroups::getPermissionGroupIdsByContactCSV($user->getId(), false);
        if ($check_dimension) {
            $dimension = $member->getDimension();
        }
        //dimension does not define permissions - user can freely add in all members
        if ($check_dimension && !$dimension->getDefinesPermissions()) {
            return true;
        }
        //dimension defines permissions and user has maximum level of permissions so can freely in all members
        if ($check_dimension && $dimension->hasAllowAllForContact($contact_pg_ids)) {
            return true;
        }
        //check
        if (ContactMemberPermissions::contactCanReadObjectTypeinMember($contact_pg_ids, $member->getId(), $object_type_id, true, false, $user)) {
            $max_role_ot_perm = MaxRoleObjectTypePermissions::instance()->findOne(array('conditions' => "object_type_id='{$object_type_id}' AND role_id = '" . $user->getUserType() . "'"));
            // if user max permission cannot write this object type then return false
            if ($max_role_ot_perm && $max_role_ot_perm->getCanWrite()) {
                return true;
            } else {
                return false;
            }
        }
        //check for context permissions that allow user to add in this member
        if ($context_members) {
            $member_ids = array();
            foreach ($context_members as $member_obj) {
                $member_ids[] = $member_obj->getId();
            }
            $allowed_members = ContactMemberPermissions::getActiveContextPermissions($user, $object_type_id, $context_members, $member_ids, true);
            if (in_array($member, $allowed_members)) {
                return true;
            }
        }
    } catch (Exception $e) {
        tpl_assign('error', $e);
        return false;
    }
    return false;
}
 /**
  * Return manager instance
  *
  * @access protected
  * @param void
  * @return TemplateTasks
  */
 function manager()
 {
     if (!$this->manager instanceof TemplateTasks) {
         $this->manager = TemplateTasks::instance();
     }
     return $this->manager;
 }
    $row_cls = "dashAltRow";
    foreach ($previous_tasks as $pt) {
        $all_dep_completed = true;
        if ($object instanceof ProjectTask) {
            $ptask = ProjectTasks::findById($pt->getPreviousTaskId());
            $task_link = get_url('task', 'view', array('id' => $ptask->getId()));
            $ptask_deps = ProjectTaskDependencies::getDependenciesForTask($ptask->getId());
            foreach ($ptask_deps as $pt_dep) {
                $pptask = ProjectTasks::findById($pt_dep->getPreviousTaskId());
                if (!$pptask->isCompleted()) {
                    $all_dep_completed = false;
                    break;
                }
            }
        } elseif ($object instanceof TemplateTask) {
            $ptask = TemplateTasks::findById($pt->getPreviousTaskId());
            $task_link = get_url('task', 'view', array('id' => $ptask->getId(), 'template_task' => 1));
        }
        if (!$ptask instanceof ProjectTask && !$ptask instanceof TemplateTask) {
            $pt->delete();
            continue;
        }
        $status_cls = $ptask->isCompleted() ? "og-wsname-color-24" : "og-wsname-color-18";
        $incomplete_previous += $ptask->isCompleted() ? 0 : 1;
        if (!$all_dep_completed) {
            $status_cls = "og-wsname-color-19";
        }
        $row_cls = $row_cls == "" ? "dashAltRow" : "";
        ?>
	<tr class="<?php 
        echo $row_cls;