/**
  * Return manager instance
  *
  * @access protected
  * @param void
  * @return Templates
  */
 function manager()
 {
     if (!$this->manager instanceof COTemplates) {
         $this->manager = COTemplates::instance();
     }
     return $this->manager;
 }
	/**
	 * Return manager instance
	 *
	 * @access protected
	 * @param void
	 * @return Templates
	 */
	function manager() {
		if(!($this->manager instanceof COTemplates)) $this->manager = COTemplates::instance();
		return $this->manager;
	} // manager
 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 'no_filter':
             $task_filter_condition = "";
             break;
         default:
             flash_error(lang('task filter criteria not recognised', $filter));
     }
     $task_status_condition = "";
     $now = DateTimeValueLib::now()->format('Y-m-j 00:00:00');
     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 `completed_on` = " . DB::escape(EMPTY_DATETIME) . " AND `start_date` <= '{$now}'";
             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}'";
             break;
         case 13:
             // Today + Overdue tasks
             $task_status_condition = " AND `completed_on` = " . DB::escape(EMPTY_DATETIME) . " AND `due_date` <= '{$now}'";
             break;
         case 14:
             // Today + Overdue tasks
             $task_status_condition = " AND `completed_on` = " . DB::escape(EMPTY_DATETIME) . " AND `due_date` <= '{$now}'";
             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');
     }
     $conditions = "AND {$template_condition} {$task_filter_condition} {$task_status_condition}";
     //Now get the tasks
     //$tasks = ProjectTasks::getContentObjects(active_context(), ObjectTypes::findById(ProjectTasks::instance()->getObjectTypeId()), null, null, $conditions,null)->objects;
     $tasks = ProjectTasks::instance()->listing(array("extra_conditions" => $conditions, "start" => 0, "limit" => 501, "count_results" => false))->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::getContentObjects(active_context(), ObjectTypes::findById(ProjectMilestones::instance()->getObjectTypeId()), null, null, $milestone_conditions,null)->objects;
     $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) {
         foreach ($tasks as $task) {
             if ($task->getMilestoneId() != 0) {
                 $milestone_ids[$task->getMilestoneId()] = $task->getMilestoneId();
             }
         }
     }
     $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 ($users 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 \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 (config_option('use tasks dependencies')) {
         $dependency_count = array();
         foreach ($tasks as $task) {
             $previous = 0;
             $ptasks = ProjectTaskDependencies::getDependenciesForTask($task->getId());
             foreach ($ptasks as $pdep) {
                 $ptask = ProjectTasks::findById($pdep->getPreviousTaskId());
                 if ($ptask instanceof ProjectTask && !$ptask->isCompleted()) {
                     $previous++;
                 }
             }
             $dependants = ProjectTaskDependencies::getDependantsForTask($task->getId());
             $dep_csv = "";
             foreach ($dependants as $dep) {
                 $dep_csv .= ($dep_csv == "" ? "" : ",") . $dep->getTaskId();
             }
             $dependency_count[] = array('id' => $task->getId(), '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', 'milestone'), 'orderBy' => user_config_option('tasksOrderBy', 'priority'), '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);
     }
 }
 function assign_to_ws()
 {
     if (!can_manage_templates(logged_user())) {
         flash_error(lang("no access permissions"));
         ajx_current("empty");
         return;
     }
     $template_id = get_id();
     $cotemplate = COTemplates::findById($template_id);
     if (!$cotemplate instanceof COTemplate) {
         flash_error(lang("template dnx"));
         ajx_current("empty");
         return;
     }
     $selected = WorkspaceTemplates::getWorkspacesByTemplate($template_id);
     tpl_assign('workspaces', logged_user()->getWorkspaces());
     tpl_assign('selected', $selected);
     tpl_assign('cotemplate', $cotemplate);
     $checked = array_var($_POST, 'ws_ids');
     if ($checked != null) {
         try {
             DB::beginWork();
             WorkspaceTemplates::deleteByTemplate($template_id);
             $wss = Projects::findByCSVIds($checked);
             foreach ($wss as $ws) {
                 $obj = new WorkspaceTemplate();
                 $obj->setWorkspaceId($ws->getId());
                 $obj->setTemplateId($template_id);
                 $obj->setInludeSubWs(false);
                 $obj->save();
             }
             DB::commit();
             flash_success(lang('success assign workspaces'));
             ajx_current("back");
         } catch (Exception $exc) {
             DB::rollback();
             flash_error(lang('error assign workspace') . $exc->getMessage());
             ajx_current("empty");
         }
     }
 }
 /**
  * @deprecated
  * @author Ignacio Vazquez - elpepe.uy@gmail.com
  */
 static function _findAllowed()
 {
     //1.  Find members where user can add tasks
     //$sqlMembers = "
     $sql = "\n\t\t\tSELECT distinct(id) AS id\n\t\t\tFROM " . TABLE_PREFIX . "object_members om\n\t\t\tINNER JOIN " . TABLE_PREFIX . "templates t ON t.object_id = om.object_id\n\t\t\tINNER JOIN " . TABLE_PREFIX . "objects o ON om.object_id = o.id\n\t\t\tWHERE\n\t\t\t    member_id IN (  \n\t\t\t    \tSELECT distinct(member_id) \n\t\t\t\t\tFROM " . TABLE_PREFIX . "contact_member_permissions o \n\t\t\t\t\tWHERE object_type_id = " . ProjectTasks::instance()->getObjectTypeId() . " \n\t\t\t\t\tAND permission_group_id IN ( " . ContactPermissionGroups::getPermissionGroupIdsByContactCSV(logged_user()->getId()) . " ) AND can_write= 1 \n\t\t\t\t)\n\t\t\t\tAND is_optimization = 0\n\t\t\tGROUP BY om.object_id\t\t\n\t\t";
     $res = DB::execute($sql);
     $tpls = array();
     // Iterate on the results and make som filtering
     while ($row = $res->fetchRow()) {
         $tpl = COTemplates::instance()->findById($row['id']);
         $tpls[] = $tpl;
     }
     return $tpls;
 }
 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', 'assigned_to');
     $filter = array_var($_GET, 'filter');
     if (is_null($filter) || $filter == '') {
         $filter = user_config_option('task panel filter', 'assigned_to');
     } else {
         if (user_config_option('task panel 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', logged_user()->getCompanyId() . ':' . 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");
     }
     $project = active_project();
     $tag = active_tag();
     $template_condition = "`is_template` = 0 ";
     //Get the task query conditions
     $task_filter_condition = "";
     switch ($filter) {
         case 'assigned_to':
             $assigned_to = explode(':', $filter_value);
             $assigned_to_user = array_var($assigned_to, 1, 0);
             $assigned_to_company = array_var($assigned_to, 0, 0);
             if ($assigned_to_user > 0) {
                 $task_filter_condition = " AND (`assigned_to_user_id` = " . $assigned_to_user . " OR (`assigned_to_company_id` = " . $assigned_to_company . " AND `assigned_to_user_id` = 0)) ";
             } else {
                 if ($assigned_to_company > 0) {
                     $task_filter_condition = " AND  `assigned_to_company_id` = " . $assigned_to_company . " AND `assigned_to_user_id` = 0";
                 } else {
                     if ($assigned_to_company == -1 && $assigned_to_user == -1) {
                         $task_filter_condition = "  AND `assigned_to_company_id` = 0 AND `assigned_to_user_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 'no_filter':
             $task_filter_condition = "";
             break;
         default:
             flash_error(lang('task filter criteria not recognised', $filter));
     }
     if ($project instanceof Project) {
         $pids = $project->getAllSubWorkspacesQuery(true);
         $projectstr = " AND " . ProjectTasks::getWorkspaceString($pids);
     } else {
         $pids = "";
         $projectstr = "";
     }
     $permissions = " AND " . permissions_sql_for_listings(ProjectTasks::instance(), ACCESS_LEVEL_READ, logged_user());
     $task_status_condition = "";
     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
             $now = date('Y-m-j 00:00:00');
             $task_status_condition = " AND `completed_on` = " . DB::escape(EMPTY_DATETIME) . " AND `start_date` <= '{$now}'";
             break;
         case 11:
             // Overdue tasks
             $now = date('Y-m-j 00:00:00');
             $task_status_condition = " AND `completed_on` = " . DB::escape(EMPTY_DATETIME) . " AND `due_date` < '{$now}'";
             break;
         case 12:
             // Today tasks
             $now = date('Y-m-j 00:00:00');
             $task_status_condition = " AND `completed_on` = " . DB::escape(EMPTY_DATETIME) . " AND `due_date` = '{$now}'";
             break;
         case 13:
             // Today + Overdue tasks
             $now = date('Y-m-j 00:00:00');
             $task_status_condition = " AND `completed_on` = " . DB::escape(EMPTY_DATETIME) . " AND `due_date` <= '{$now}'";
             break;
         case 14:
             // Today + Overdue tasks
             $now = date('Y-m-j 00:00:00');
             $task_status_condition = " AND `completed_on` = " . DB::escape(EMPTY_DATETIME) . " AND `due_date` <= '{$now}'";
             break;
         case 20:
             // Actives task by current user
             $now = date('Y-m-j 00:00:00');
             $task_status_condition = " AND `completed_on` = " . DB::escape(EMPTY_DATETIME) . " AND `start_date` <= '{$now}' AND `assigned_to_user_id` = " . logged_user()->getId();
             break;
         case 21:
             // Subscribed tasks by current user
             $res20 = DB::execute("SELECT object_id FROM " . TABLE_PREFIX . "object_subscriptions WHERE `object_manager` LIKE 'ProjectTasks' AND `user_id` = " . logged_user()->getId());
             $subs_rows = $res20->fetchAll($res20);
             foreach ($subs_rows as $row) {
                 $subs[] = $row['object_id'];
             }
             unset($res20, $subs_rows, $row);
             $now = date('Y-m-j 00:00:00');
             $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');
     }
     if (!$tag) {
         $tagstr = "";
     } else {
         $tagstr = " AND (select count(*) from " . TABLE_PREFIX . "tags where " . TABLE_PREFIX . "project_tasks.id = " . TABLE_PREFIX . "tags.rel_object_id and " . TABLE_PREFIX . "tags.tag = " . DB::escape($tag) . " and " . TABLE_PREFIX . "tags.rel_object_manager ='ProjectTasks' ) > 0 ";
     }
     $conditions = $template_condition . $task_filter_condition . $task_status_condition . $permissions . $tagstr . $projectstr . " AND `trashed_by_id` = 0 AND `archived_by_id` = 0";
     //Now get the tasks
     $tasks = ProjectTasks::findAll(array('conditions' => $conditions, 'order' => 'created_on DESC', 'limit' => user_config_option('task_display_limit') > 0 ? user_config_option('task_display_limit') + 1 : null));
     ProjectTasks::populateData($tasks);
     //Find all internal milestones for these tasks
     $internalMilestones = ProjectMilestones::getProjectMilestones(active_or_personal_project(), null, 'DESC', "", null, null, null, $status == 0, false);
     ProjectMilestones::populateData($internalMilestones);
     //Find all external milestones for these tasks
     $milestone_ids = array();
     if ($tasks) {
         foreach ($tasks as $task) {
             if ($task->getMilestoneId() != 0) {
                 $milestone_ids[$task->getMilestoneId()] = $task->getMilestoneId();
             }
         }
     }
     $milestone_ids_condition = '';
     if (count($milestone_ids) > 0) {
         $milestone_ids_condition = ' OR id in (' . implode(',', $milestone_ids) . ')';
     }
     if ($status == 0) {
         $pendingstr = " AND `completed_on` = " . DB::escape(EMPTY_DATETIME) . " ";
     } else {
         $pendingstr = "";
     }
     if (!$tag) {
         $tagstr = "";
     } else {
         $tagstr = " AND (select count(*) from " . TABLE_PREFIX . "tags where " . TABLE_PREFIX . "project_milestones.id = " . TABLE_PREFIX . "tags.rel_object_id and " . TABLE_PREFIX . "tags.tag = " . DB::escape($tag) . " and " . TABLE_PREFIX . "tags.rel_object_manager ='ProjectMilestones' ) > 0 ";
     }
     $projectstr = " AND (" . ProjectMilestones::getWorkspaceString($pids) . $milestone_ids_condition . ")";
     $archivedstr = " AND `archived_by_id` = 0 ";
     $milestone_conditions = " `is_template` = false " . $archivedstr . $projectstr . $pendingstr;
     $externalMilestonesTemp = ProjectMilestones::findAll(array('conditions' => $milestone_conditions));
     $externalMilestones = array();
     if ($externalMilestonesTemp) {
         foreach ($externalMilestonesTemp as $em) {
             $found = false;
             if ($internalMilestones) {
                 foreach ($internalMilestones as $im) {
                     if ($im->getId() == $em->getId()) {
                         $found = true;
                         break;
                     }
                 }
             }
             if (!$found) {
                 $externalMilestones[] = $em;
             }
         }
     }
     ProjectMilestones::populateData($externalMilestones);
     //Get Users Info
     if (logged_user()->isMemberOfOwnerCompany()) {
         $users = Users::getAll();
         $allUsers = array();
     } else {
         $users = logged_user()->getAssignableUsers();
         $allUsers = Users::getAll();
     }
     //Get Companies Info
     if (logged_user()->isMemberOfOwnerCompany()) {
         $companies = Companies::getCompaniesWithUsers();
     } else {
         $companies = logged_user()->getAssignableCompanies();
     }
     if (!$isJson) {
         if (active_project() instanceof Project) {
             $task_templates = WorkspaceTemplates::getTemplatesByWorkspace(active_project()->getId());
         } else {
             $task_templates = array();
         }
         tpl_assign('project_templates', $task_templates);
         tpl_assign('all_templates', COTemplates::findAll());
         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('tasks', $tasks);
         tpl_assign('object_subtypes', ProjectCoTypes::getObjectTypesByManager('ProjectTasks'));
         tpl_assign('internalMilestones', $internalMilestones);
         tpl_assign('externalMilestones', $externalMilestones);
         tpl_assign('users', $users);
         tpl_assign('allUsers', $allUsers);
         tpl_assign('companies', $companies);
         tpl_assign('userPreferences', array('filterValue' => isset($filter_value) ? $filter_value : '', 'filter' => $filter, 'status' => $status, 'showWorkspaces' => user_config_option('tasksShowWorkspaces', 1), 'showTime' => user_config_option('tasksShowTime', 0), 'showDates' => user_config_option('tasksShowDates', 0), 'showTags' => user_config_option('tasksShowTags', 0), 'showEmptyMilestones' => user_config_option('tasksShowEmptyMilestones', 0), 'groupBy' => user_config_option('tasksGroupBy', 'milestone'), 'orderBy' => user_config_option('tasksOrderBy', 'priority'), 'defaultNotifyValue' => user_config_option('can notify from quick add')));
         ajx_set_no_toolbar(true);
     }
 }
 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);
     }
 }
 /**
  * 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, 'COTemplates')) {
         return parent::paginate($arguments, $items_per_page, $current_page);
     } else {
         return COTemplates::instance()->paginate($arguments, $items_per_page, $current_page);
         //$instance =& COTemplates::instance();
         //return $instance->paginate($arguments, $items_per_page, $current_page);
     }
     // if
 }
 function getTemplate()
 {
     return COTemplates::findById($this->getTemplateId());
 }