/** * Daily update of repositories * * @param null * @return void */ function source_handle_on_frequently() { require_once ANGIE_PATH . '/classes/xml/xml2array.php'; $results = 'Repositories updated: '; $repositories = Repositories::findByUpdateType(REPOSITORY_UPDATE_FREQUENTLY); foreach ($repositories as $repository) { // don't update projects other than active ones $project = Projects::findById($repository->getProjectId()); if ($project->getStatus() !== PROJECT_STATUS_ACTIVE) { continue; } // if $repository->loadEngine(); $repository_engine = new RepositoryEngine($repository, true); $last_commit = $repository->getLastCommit(); $revision_to = is_null($last_commit) ? 1 : $last_commit->getRevision() + 1; $logs = $repository_engine->getLogs($revision_to); if (!$repository_engine->has_errors) { $repository->update($logs['data']); $total_commits = $logs['total']; $results .= $repository->getName() . ' (' . $total_commits . ' new commits); '; if ($total_commits > 0) { $repository->sendToSubscribers($total_commits, $repository_engine); $repository->createActivityLog($total_commits); } // if } // if } // foreach return is_foreachable($repositories) && count($repositories) > 0 ? $results : 'No repositories for frequently update'; }
/** * Return project instance * * @param void * @return Project */ function getProject() { if ($this->project === false) { $this->project = Projects::findById($this->getProjectId()); } // if return $this->project; }
/** * Return project part of the relationship * * @param void * @return Project */ function getProject() { if (is_null($this->project)) { $this->project = Projects::findById($this->getProjectId()); } // if return $this->project; }
/** * Show reporting index page * * @param void * @return null */ function add_chart() { if (logged_user()->isGuest()) { flash_error(lang('no access permissions')); ajx_current("empty"); return; } $factory = new ProjectChartFactory(); $types = $factory->getChartTypes(); $chart_data = array_var($_POST, 'chart'); if(!is_array($chart_data)) { $chart_data = array( 'type_id' => 1, 'display_id' => 20, 'show_in_project' => 1, 'show_in_parents' => 0 ); // array } // if tpl_assign('chart_data', $chart_data); if (is_array(array_var($_POST, 'chart'))) { $project = Projects::findById(array_var($chart_data, 'project_id')); if (!$project instanceof Project) { flash_error(lang('project dnx')); ajx_current("empty"); return; } $chart = $factory->getChart(array_var($chart_data, 'type_id')); $chart->setDisplayId(array_var($chart_data, 'display_id')); $chart->setTitle(array_var($chart_data, 'title')); if (array_var($chart_data, 'save') == 1){ $chart->setFromAttributes($chart_data); try { DB::beginWork(); $chart->save(); $chart->setProject($project); DB::commit(); flash_success(lang('success add chart', $chart->getTitle())); ajx_current('back'); } catch(Exception $e) { DB::rollback(); flash_error($e->getMessage()); ajx_current("empty"); } return; } $chart->ExecuteQuery(); tpl_assign('chart', $chart); ajx_replace(true); } tpl_assign('chart_displays', $factory->getChartDisplays()); tpl_assign('chart_list', $factory->getChartTypes()); }
/** * This function will return application data object that matches action and in object ID * * @param void * @return ApplicationDataObject */ function getInObject() { if(is_null($this->in_object)) { if($this->getAction() == self::ADD_COMMENT_ACTION) { $this->in_object = ProjectMessages::findById($this->getInObjectId()); } elseif($this->getAction() == self::ADD_TASK_ACTION) { $this->in_object = Projects::findById($this->getInObjectId()); } // if } // if return $this->in_object; } // getInObject
/** * Construct PublicSubmitAdminController * * @param string $request * @return PublicSubmitAdminController * */ function __construct($request) { parent::__construct($request); $this->smarty->assign(array("public_submit_settings_url" => assemble_url('admin_settings_public_submit'))); if (!(extension_loaded('gd') || extension_loaded('gd2')) || !function_exists('imagefttext')) { $this->gd_loaded = false; } // if $this->smarty->assign(array('public_submit_url' => assemble_url('public_submit'), 'public_submit_enabled' => ConfigOptions::getValue('public_submit_enabled'), 'public_submit_captcha_enabled' => ConfigOptions::getValue('public_submit_enable_captcha'), 'public_submit_project' => Projects::findById(ConfigOptions::getValue('public_submit_default_project')), 'gd_loaded' => $this->gd_loaded)); return $this; }
/** * Init active project, if we have active_project $_GET var * * @access public * @param void * @return null * @throws Error */ private function initActiveProject() { $project_id = array_var($_GET, 'active_project'); if (!empty($project_id)) { $project = Projects::findById($project_id); if (!$project instanceof Project) { throw new Error(lang('failed to load project')); } // if $this->setProject($project); } // if }
/** * Constructor * * @param Request $request * @return MobileAccessController extends ApplicationController */ function __construct($request) { parent::__construct($request); $this->disableCategories(); $project_id = $this->request->get('project_id'); if ($project_id) { $this->active_project = Projects::findById($project_id); } // if if (!instance_of($this->active_project, 'Project')) { $this->httpError(HTTP_ERR_NOT_FOUND); } // if if (!$this->logged_user->isProjectMember($this->active_project)) { $this->httpError(HTTP_ERR_FORBIDDEN); } // if if ($this->active_project->getType() == PROJECT_TYPE_SYSTEM) { $this->httpError(HTTP_ERR_NOT_FOUND); } // if $this->project_sections = array(); $this->project_sections[] = array("name" => "overview", "full_name" => lang("Overview"), "url" => assemble_url('mobile_access_view_project', array('project_id' => $this->active_project->getId()))); if (module_loaded('discussions') && $this->logged_user->getProjectPermission('discussion', $this->active_project)) { $this->project_sections[] = array("name" => "discussions", "full_name" => lang("Discussions"), "url" => assemble_url('mobile_access_view_discussions', array('project_id' => $this->active_project->getId()))); } if (module_loaded('milestones') && $this->logged_user->getProjectPermission('milestone', $this->active_project)) { $this->project_sections[] = array("name" => "milestones", "full_name" => lang("Milestones"), "url" => assemble_url('mobile_access_view_milestones', array('project_id' => $this->active_project->getId()))); } if (module_loaded('files') && $this->logged_user->getProjectPermission('file', $this->active_project)) { $this->project_sections[] = array("name" => "files", "full_name" => lang("Files"), "url" => assemble_url('mobile_access_view_files', array('project_id' => $this->active_project->getId()))); } if (module_loaded('checklists') && $this->logged_user->getProjectPermission('checklist', $this->active_project)) { $this->project_sections[] = array("name" => "checklists", "full_name" => lang("Checklists"), "url" => assemble_url('mobile_access_view_checklists', array('project_id' => $this->active_project->getId()))); } if (module_loaded('pages') && $this->logged_user->getProjectPermission('page', $this->active_project)) { $this->project_sections[] = array("name" => "pages", "full_name" => lang("Pages"), "url" => assemble_url('mobile_access_view_pages', array('project_id' => $this->active_project->getId()))); } if (module_loaded('tickets') && $this->logged_user->getProjectPermission('ticket', $this->active_project)) { $this->project_sections[] = array("name" => "tickets", "full_name" => lang("Tickets"), "url" => assemble_url('mobile_access_view_tickets', array('project_id' => $this->active_project->getId()))); } if (module_loaded('timetracking') && $this->logged_user->getProjectPermission('timerecord', $this->active_project)) { $this->project_sections[] = array("name" => "timetracking", "full_name" => lang("Time"), "url" => assemble_url('mobile_access_view_timerecords', array('project_id' => $this->active_project->getId()))); } if (module_loaded('source') && $this->logged_user->getProjectPermission('repository', $this->active_project)) { $this->project_sections[] = array("name" => "source", "full_name" => lang("Repositories"), "url" => assemble_url('mobile_access_view_repositories', array('project_id' => $this->active_project->getId()))); } //if($this->active_project->isLoaded() && $this->enable_categories) { $this->addBreadcrumb(lang('Project'), assemble_url('mobile_access_view_project', array("project_id" => $this->active_project->getId()))); $this->smarty->assign(array("page_title" => $this->active_project->getName(), "active_project" => $this->active_project, "project_sections" => $this->project_sections, "page_breadcrumbs" => $this->breadcrumbs, "active_project_section" => 'overview', "active_category" => $this->active_category)); }
function set_responsible_status() { $project_id = $this->request->getId('project_id'); if ($project_id) { $project = Projects::findById($project_id); } $ticket_id = $this->request->getId('ticket_id'); if ($ticket_id) { $ticket = Tickets::findByTicketId($project, $ticket_id); } $owner = Assignments::findOwnerByObject($ticket); $users = Assignments::findAssigneesByObject($ticket); $this->smarty->assign(array('project' => $project, 'ticket' => $ticket, 'users' => $users, 'owner' => $owner, 'ticket_url' => assemble_url('project_ticket', array('project_id' => $project_id, 'ticket_id' => $ticket_id)))); }
/** * Class constructor * */ function __construct($repository, $triggered_by_handler = false) { parent::__construct(); // check if we have neccessary resources if (instance_of($repository, 'Repository')) { $this->active_repository = $repository; $this->active_project = Projects::findById($repository->getProjectId()); } // if $this->executable_path = with_slash(ConfigOptions::getValue('source_svn_path')); $config_dir = ConfigOptions::getValue('source_svn_config_dir'); $this->config_dir = is_null($config_dir) ? '' : '--config-dir ' . $config_dir; $this->stderr2stdout = ConfigOptions::getValue('source_svn_use_output_redirect') == true ? "2>&1" : ""; $this->trust_server_certificate = ConfigOptions::getValue('source_svn_trust_server_cert') == true ? '--trust-server-cert' : ''; $this->triggerred_by_handler = $triggered_by_handler; }
function getGroupTitle($field, $tsRow) { $ts = $tsRow["ts"]; switch ($field) { case 'id': if ($ts->getObjectManager() == 'Projects') { return $ts->getObject()->getName(); } else { return $ts->getObject()->getTitle(); } case 'user_id': return Users::getUserDisplayName($ts->getUserId()); case 'project_id_0': return $tsRow["wsId0"] != 0 ? Projects::findById($tsRow["wsId0"])->getName() : ''; case 'project_id_1': return $tsRow["wsId1"] != 0 ? Projects::findById($tsRow["wsId1"])->getName() : ''; case 'project_id_2': return $tsRow["wsId2"] != 0 ? Projects::findById($tsRow["wsId2"])->getName() : ''; case 'priority': if ($ts->getObjectManager() == 'ProjectTasks') { switch ($ts->getObject()->getPriority()) { case 100: return lang('low priority'); case 200: return lang('normal priority'); case 300: return lang('high priority'); case 400: return lang('urgent priority'); default: return $ts->getObject()->getPriority(); } } else { return lang('not applicable'); } case 'milestone_id': if ($ts->getObjectManager() == 'ProjectTasks') { return $ts->getObject()->getMilestoneId() != 0 ? $ts->getObject()->getMilestone()->getTitle() : ''; } else { return ''; } } return ''; }
function form_run() { if ($this->request->isAsyncCall()) { $project = $this->request->get('project_id') ? Projects::findById($this->request->get('project_id')) : null; if ($project instanceof Project) { // TODO: eliminare group_by $report = new MilestoneETAReport($project); $this->response->assign('rendered_report_result', $report->render($this->logged_user)); $this->response->assign('milestones', $report->getMilestones()); $this->response->assign('detailed_report', true); } else { $this->response->notFound(); } // if } else { $this->response->badRequest(); } //if }
/** * Construct method * * @param string $request * @return PublicSubmitController */ function __construct($request) { parent::__construct($request); if (!ConfigOptions::getValue('public_submit_enabled')) { $this->httpError(HTTP_ERR_NOT_FOUND); } // if $this->setLayout(array("module" => PUBLIC_SUBMIT_MODULE, "layout" => 'wireframe')); $this->active_project = Projects::findById(ConfigOptions::getValue('public_submit_default_project')); if (!instance_of($this->active_project, 'Project')) { $this->httpError(HTTP_ERR_NOT_FOUND); } // if // check if captcha is enabled, and if it is, check that GD library is loaded $this->captcha_enabled = (bool) ConfigOptions::getValue('public_submit_enable_captcha'); if ($this->captcha_enabled) { if (!(extension_loaded('gd') || extension_loaded('gd2')) || !function_exists('imagefttext')) { $this->captcha_enabled = false; } // if } // if $this->smarty->assign(array("active_project" => $this->active_project, "submit_ticket_url" => assemble_url('public_submit'), 'captcha_enabled' => $this->captcha_enabled)); }
function total_task_times_vs_estimate_comparison($report_data = null, $task = null) { $this->setTemplate('report_wrapper'); if (!$report_data) { $report_data = array_var($_POST, 'report'); } $workspace = Projects::findById(array_var($report_data, 'project_id')); if ($workspace instanceof Project) { if (array_var($report_data, 'include_subworkspaces')) { $workspacesCSV = $workspace->getAllSubWorkspacesQuery(false); } else { $workspacesCSV = $workspace->getId(); } } else { $workspacesCSV = null; } $start = getDateValue(array_var($report_data, 'start_value')); $end = getDateValue(array_var($report_data, 'end_value')); $st = $start->beginningOfDay(); $et = $end->endOfDay(); $st = new DateTimeValue($st->getTimestamp() - logged_user()->getTimezone() * 3600); $et = new DateTimeValue($et->getTimestamp() - logged_user()->getTimezone() * 3600); $timeslots = Timeslots::getTimeslotsByUserWorkspacesAndDate($st, $et, 'ProjectTasks', null, $workspacesCSV, array_var($report_data, 'task_id', 0)); tpl_assign('timeslots', $timeslots); tpl_assign('workspace', $workspace); tpl_assign('start_time', $st); tpl_assign('end_time', $et); tpl_assign('user', $user); tpl_assign('post', $report_data); tpl_assign('template_name', 'total_task_times'); tpl_assign('title', lang('task time report')); }
/** * List all time total for a project (both billed and unbilled) * * @access public * @param void * @return null */ function byproject() { $this->setLayout('administration'); if (!logged_user()->isAdministrator(owner_company())) { flash_error(lang('no access permissions')); $this->redirectTo('dashboard'); } // if $project_id = (int) array_var($_GET, 'id', 0); if ($project_id < 0) { $project_id = 0; } $redirect_to = array_var($_GET, 'redirect_to'); if ($redirect_to == '') { $redirect_to = get_url('time', 'byproject', array('id' => $project_id)); $redirect_to = str_replace('&', '&', trim($redirect_to)); } // if $unbilled = ProjectTimes::getTimeByProjectStatus(Projects::findById($project_id)); $billed = ProjectTimes::getTimeByProjectStatus(Projects::findById($project_id), 1); tpl_assign('unbilled', $unbilled); tpl_assign('billed', $billed); tpl_assign('project', Projects::findById($project_id)); tpl_assign('redirect_to', $redirect_to); $this->setSidebar(get_template_path('index_sidebar', 'time')); }
/** * Returns additional fields for import for, dependable of provided project id * * this is ajax request * */ function conflict_form_additional_fields() { if (!$this->request->isAsyncCall()) { $this->httpError(HTTP_ERR_BAD_REQUEST); } // if $project = Projects::findById($this->request->get('project_id')); if (!instance_of($project, 'Project')) { echo lang('Project does not exists'); die; } // if $form_data = array('user_id' => $this->request->get('user_id'), 'object_type' => $this->request->get('object_type')); $this->smarty->assign(array('object_type' => $this->request->get('object_type'), 'project' => $project, 'form_data' => $form_data)); }
function ical_export() { $this->setLayout('ical'); require_once ROOT . '/environment/classes/event/CalFormatUtilities.php'; if (!isset($_GET['t']) || !isset($_GET['cal'])) { header('HTTP/1.0 404 Not Found'); die; } $token = $_GET['t']; $cal = $_GET['cal']; $inc_sub = isset($_GET['isw']) && $_GET['isw'] == 1; if (Users::tokenExists($token)) { $user = Users::getByToken($token); if ($cal == 0) { $project = null; } else { $project = Projects::findById($cal); } $events = ProjectEvents::getAllEventsByProject($project, false, $inc_sub, $user); $calendar_name = isset($_GET['n']) ? $_GET['n'] : $user->getDisplayName(); tpl_assign('content', CalFormatUtilities::generateICalInfo($events, $calendar_name, $user)); } else { header('HTTP/1.0 404 Not Found'); die; } }
/** * Process add project form * * @param void * @return null */ function add() { $this->wireframe->print_button = false; if ($this->request->isApiCall() && !$this->request->isSubmitted()) { $this->httpError(HTTP_ERR_BAD_REQUEST); } // if if (!Project::canAdd($this->logged_user)) { $this->httpError(HTTP_ERR_FORBIDDEN); } // if $project_data = $this->request->post('project'); if (!is_array($project_data)) { $project_data = array('leader_id' => $this->logged_user->getId(), 'default_visibility' => VISIBILITY_PRIVATE); } // if $this->smarty->assign('project_data', $project_data); if ($this->request->isSubmitted()) { db_begin_work(); $this->active_project = new Project(); // just in case $this->active_project->setAttributes($project_data); $this->active_project->setType(PROJECT_TYPE_NORMAL); $this->active_project->setStatus(PROJECT_STATUS_ACTIVE); $leader = null; if ($this->active_project->getLeaderId()) { $leader = Users::findById($this->active_project->getLeaderId()); if (instance_of($leader, 'User')) { $this->active_project->setLeader($leader); } // if } // if $project_template = null; $project_template_id = array_var($project_data, 'project_template_id'); if ($project_template_id) { $project_template = Projects::findById($project_template_id); } // if $save = $this->active_project->save($project_template); if ($save && !is_error($save)) { // Add user who created a project and leader $this->active_project->addUser($this->logged_user, null, null); if (instance_of($leader, 'User')) { $this->active_project->addUser($leader, null, null); } // if // Clone project template if (instance_of($project_template, 'Project')) { $project_template->copyItems($this->active_project); } else { // Auto assign users... $users = Users::findAutoAssignUsers(); if (is_foreachable($users)) { foreach ($users as $user) { $this->active_project->addUser($user, $user->getAutoAssignRole(), $user->getAutoAssignPermissions()); } // foreach } // if // Create default categories $category_definitions = array(); event_trigger('on_master_categories', array(&$category_definitions)); if (is_foreachable($category_definitions)) { foreach ($category_definitions as $category_definition) { $default_categories = $category_definition['value']; if (!is_foreachable($default_categories)) { $default_categories = array('General'); } // if foreach ($default_categories as $category_name) { if (trim($category_name) != '') { $category = new Category(); $category->log_activities = false; // don't log stuff in DB $category->setName($category_name); $category->setProjectId($this->active_project->getId()); $category->setCreatedBy($this->logged_user); $category->setState(STATE_VISIBLE); $category->setVisibility(VISIBILITY_NORMAL); $category->setModule($category_definition['module']); $category->setController($category_definition['controller']); $category->save(); } // if } // foreach } // foreach } // if } // if db_commit(); if ($this->request->isApiCall()) { $this->serveData($this->active_project, 'project'); } else { flash_success('Project ":name" has been created. Use this page to add more people to the project...', array('name' => $this->active_project->getName())); $this->redirectToUrl($this->active_project->getPeopleUrl()); } // if } else { db_rollback(); if ($this->request->isApiCall()) { $this->serveData($save); } else { $this->smarty->assign('errors', $save); } // if } // if } // if }
/** * Return project * * @access public * @param void * @return Project */ function getProject() { return Projects::findById($this->getProjectId()); }
function uploadDocument($doc_name, $ws_id, $path) { if (str_starts_with($doc_name, "~")) { return; } try { DB::beginWork(); $project = Projects::findById($ws_id); //$file = ProjectFiles::findOne(array("conditions" => "`filename` = '$doc_name'")); $files = ProjectFiles::getAllByFilename($doc_name, $ws_id); if (is_array($files) && count($files) > 0) { $file = $files[0]; } else { $file = null; } if (!$file instanceof ProjectFile) { $file = new ProjectFile(); $file->setFilename($doc_name); $file->setIsVisible(true); $file->setIsPrivate(false); $file->setIsImportant(false); $file->setCommentsEnabled(true); $file->setAnonymousCommentsEnabled(false); //$file->setCreatedOn(new DateTimeValue(time()) ); } $sourcePath = $path . $doc_name; $handle = fopen($sourcePath, "r"); $size = filesize($sourcePath); $file_content = fread($handle, $size); fclose($handle); $file_dt['name'] = $file->getFilename(); $file_dt['size'] = strlen($file_content); $file_dt['tmp_name'] = $sourcePath; //TEMP_PATH . DIRECTORY_SEPARATOR . rand() ; $extension = trim(get_file_extension($sourcePath)); $file_dt['type'] = Mime_Types::instance()->get_type($extension); if (!trim($file_dt['type'])) { $file_dt['type'] = 'text/html'; } $file->save(); $file->removeFromAllWorkspaces(); $file->addToWorkspace($project); $old_revs = $file->getRevisions(); foreach ($old_revs as $rev) { $rev->delete(); } $revision = $file->handleUploadedFile($file_dt, true, ''); $file_date = new DateTimeValue(filemtime($sourcePath)); $revision->setCreatedOn($file_date); $revision->setUpdatedOn($file_date); $revision->save(); $file->setCreatedOn($file_date); $file->setUpdatedOn($file_date); $file->save(); $ws = $file->getWorkspaces(); ApplicationLogs::createLog($file, $ws, ApplicationLogs::ACTION_ADD); ImportLogger::instance()->log(" File: {$doc_name} [{$ws_id}]"); print " File: {$doc_name} [{$ws_id}]\r\n"; DB::commit(); } catch (Exception $e) { DB::rollback(); ImportLogger::instance()->logError("{$e}\r\n**************************************************"); print "\r\n\r\nERROR: {$e}\r\n"; } }
function list_files() { ajx_current("empty"); /* get query parameters */ $start = (int) array_var($_GET, 'start'); $limit = (int) array_var($_GET, 'limit'); if (!$start) { $start = 0; } if (!$limit) { $limit = config_option('files_per_page'); } $order = array_var($_GET, 'sort'); $orderdir = array_var($_GET, 'dir'); $page = (int) ($start / $limit) + 1; $hide_private = !logged_user()->isMemberOfOwnerCompany(); $tag = array_var($_GET, 'tag'); $type = array_var($_GET, 'type'); $user = array_var($_GET, 'user'); /* if there's an action to execute, do so */ if (array_var($_GET, 'action') == 'delete') { $ids = explode(',', array_var($_GET, 'objects')); $succ = 0; $err = 0; foreach ($ids as $id) { $file = ProjectFiles::findById($id); if (isset($file) && $file->canDelete(logged_user())) { try { DB::beginWork(); $file->trash(); ApplicationLogs::createLog($file, $file->getWorkspaces(), ApplicationLogs::ACTION_TRASH); DB::commit(); $succ++; } catch (Exception $e) { DB::rollback(); $err++; } } else { $err++; } } if ($succ > 0) { flash_success(lang("success delete files", $succ)); } else { flash_error(lang("error delete files", $err)); } } else { if (array_var($_GET, 'action') == 'tag') { $ids = explode(',', array_var($_GET, 'objects')); $tagTag = array_var($_GET, 'tagTag'); $tagged = 0; $not_tagged = 0; foreach ($ids as $id) { $file = ProjectFiles::findById($id); if (isset($file) && $file->canEdit(logged_user())) { $arr_tags = $file->getTags(); if (!array_search($tagTag, $arr_tags)) { $arr_tags[] = $tagTag; $file->setTagsFromCSV(implode(',', $arr_tags)); $tagged++; } } else { $not_tagged++; } } if ($tagged > 0) { flash_success(lang("success tag objects", $tagged)); } else { flash_error(lang("error tag objects", $not_tagged)); } } else { if (array_var($_GET, 'action') == 'untag') { $ids = explode(',', array_var($_GET, 'objects')); $tagTag = array_var($_GET, 'tagTag'); $untagged = 0; $not_untagged = 0; foreach ($ids as $id) { $file = ProjectFiles::findById($id); if (isset($file) && $file->canEdit(logged_user())) { if ($tagTag != '') { $file->deleteTag($tagTag); } else { $file->clearTags(); } $untagged++; } else { flash_error(lang('no access permissions')); $not_untagged++; } } if ($untagged > 0) { flash_success(lang("success untag objects", $untagged)); } else { flash_error(lang("error untag objects", $not_untagged)); } } else { if (array_var($_GET, 'action') == 'markasread') { $ids = explode(',', array_var($_GET, 'objects')); $succ = 0; $err = 0; foreach ($ids as $id) { $file = ProjectFiles::findById($id); try { $file->setIsRead(logged_user()->getId(), true); $succ++; } catch (Exception $e) { $err++; } // try } //for if ($succ <= 0) { flash_error(lang("error markasread files", $err)); } } else { if (array_var($_GET, 'action') == 'markasunread') { $ids = explode(',', array_var($_GET, 'objects')); $succ = 0; $err = 0; foreach ($ids as $id) { $file = ProjectFiles::findById($id); try { $file->setIsRead(logged_user()->getId(), false); $succ++; } catch (Exception $e) { $err++; } // try } //for if ($succ <= 0) { flash_error(lang("error markasunread files", $err)); } } else { if (array_var($_GET, 'action') == 'zip_add') { $this->zip_add(); } else { if (array_var($_GET, 'action') == 'move') { $wsid = array_var($_GET, "moveTo"); $destination = Projects::findById($wsid); if (!$destination instanceof Project) { $resultMessage = lang('project dnx'); $resultCode = 1; } else { if (!can_add(logged_user(), $destination, 'ProjectFiles')) { $resultMessage = lang('no access permissions'); $resultCode = 1; } else { $count = 0; $ids = explode(',', array_var($_GET, 'ids', '')); for ($i = 0; $i < count($ids); $i++) { $id = $ids[$i]; $file = ProjectFiles::findById($id); if ($file instanceof ProjectFile && $file->canEdit(logged_user())) { if (!array_var($_GET, "mantainWs")) { $removed = ""; $ws = $file->getWorkspaces(null); foreach ($ws as $w) { if (can_add(logged_user(), $w, 'ProjectFiles')) { $file->removeFromWorkspace($w); $removed .= $w->getId() . ","; } } $removed = substr($removed, 0, -1); $log_action = ApplicationLogs::ACTION_MOVE; $log_data = ($removed == "" ? "" : "from:{$removed};") . "to:{$wsid}"; } else { $log_action = ApplicationLogs::ACTION_COPY; $log_data = "to:{$wsid}"; } $file->addToWorkspace($destination); ApplicationLogs::createLog($file, $file->getWorkspaces(), $log_action, false, null, true, $log_data); $count++; } } // for $resultMessage = lang("success move objects", $count); $resultCode = 0; } } } else { if (array_var($_GET, 'action') == 'archive') { $ids = explode(',', array_var($_GET, 'ids')); $succ = 0; $err = 0; foreach ($ids as $id) { $file = ProjectFiles::findById($id); if (isset($file) && $file->canEdit(logged_user())) { try { DB::beginWork(); $file->archive(); ApplicationLogs::createLog($file, $file->getWorkspaces(), ApplicationLogs::ACTION_ARCHIVE); DB::commit(); $succ++; } catch (Exception $e) { DB::rollback(); //Logger::log($e->getMessage()); $err++; } } else { $err++; } } if ($succ > 0) { flash_success(lang("success archive objects", $succ)); } else { flash_error(lang("error archive objects", $err)); } } } } } } } } } Hook::fire('classify_action', null, $ret); $project = active_project(); /* perform query */ $result = ProjectFiles::getProjectFiles($project, null, $hide_private, $order, $orderdir, $page, $limit, false, $tag, $type, $user); ProjectFiles::populateData($result[0]); $objects = null; $pagination = null; if (is_array($result)) { list($objects, $pagination) = $result; if ($pagination->getTotalItems() < ($page - 1) * $limit) { // if we are past the last page show the first page $start = 0; $page = 1; $result = ProjectFiles::getProjectFiles($project, null, $hide_private, $order, $orderdir, $page, $limit, false, $tag, $type, $user); if (is_array($result)) { list($objects, $pagination) = $result; } } } /* prepare response object */ $listing = array("totalCount" => $pagination ? $pagination->getTotalItems() : 0, "start" => $start, "files" => array()); if ($objects) { $index = 0; foreach ($objects as $o) { $coName = ""; $coId = $o->getCheckedOutById(); if ($coId != 0) { if ($coId == logged_user()->getId()) { $coName = "self"; } else { $coUser = Users::findById($coId); if ($coUser instanceof User) { $coName = $coUser->getUsername(); } else { $coName = ""; } } } if ($o->isMP3()) { $songname = $o->getProperty("songname"); $artist = $o->getProperty("songartist"); $album = $o->getProperty("songalbum"); $track = $o->getProperty("songtrack"); $year = $o->getProperty("songyear"); $duration = $o->getProperty("songduration"); $songInfo = json_encode(array($songname, $artist, $album, $track, $year, $duration, $o->getDownloadUrl(), $o->getFilename(), $o->getId())); } else { $songInfo = array(); } $values = array("id" => $o->getId(), "ix" => $index++, "object_id" => $o->getId(), "name" => $o->getFilename(), "type" => $o->getTypeString(), "mimeType" => $o->getTypeString(), "tags" => project_object_tags($o), "createdBy" => $o->getCreatedByDisplayName(), "createdById" => $o->getCreatedById(), "dateCreated" => $o->getCreatedOn() instanceof DateTimeValue ? $o->getCreatedOn()->isToday() ? format_time($o->getCreatedOn()) : format_datetime($o->getCreatedOn()) : '', "dateCreated_today" => $o->getCreatedOn() instanceof DateTimeValue ? $o->getCreatedOn()->isToday() : 0, "updatedBy" => $o->getUpdatedByDisplayName(), "updatedById" => $o->getUpdatedById(), "dateUpdated" => $o->getUpdatedOn() instanceof DateTimeValue ? $o->getUpdatedOn()->isToday() ? format_time($o->getUpdatedOn()) : format_datetime($o->getUpdatedOn()) : '', "dateUpdated_today" => $o->getUpdatedOn() instanceof DateTimeValue ? $o->getUpdatedOn()->isToday() : 0, "icon" => $o->getTypeIconUrl(), "size" => $o->getFileSize(), "wsIds" => $o->getUserWorkspacesIdsCSV(logged_user(), ProjectUsers::instance()->getTableName(true) . ".`can_read_files` = 1"), "url" => $o->getOpenUrl(), "manager" => get_class($o->manager()), "checkedOutByName" => $coName, "checkedOutById" => $coId, "isModifiable" => $o->isModifiable() && $o->canEdit(logged_user()), "modifyUrl" => $o->getModifyUrl(), "songInfo" => $songInfo, "ftype" => $o->getType(), "url" => $o->getUrl(), "isRead" => $o->getIsRead(logged_user()->getId())); if ($o->isMP3()) { $values['isMP3'] = true; } Hook::fire('add_classification_value', $o, $values); $listing["files"][] = $values; } } ajx_extra_data($listing); tpl_assign("listing", $listing); }
/** * Resolve action to perform * * @param string $action * @param array $attributes * @return string $message */ private function resolveAction($action, $attributes) { $resultMessage = ""; $resultCode = 0; switch ($action) { case "delete": $err = 0; $succ = 0; for ($i = 0; $i < count($attributes["ids"]); $i++) { $id = $attributes["ids"][$i]; $type = $attributes["types"][$i]; switch ($type) { case "email": $email = MailContents::findById($id); if (isset($email) && $email->canDelete(logged_user())) { if ($email->getState() == 2) { // we are deleting a draft email $emails_in_conversation = array($email); } else { if (user_config_option('show_emails_as_conversations', true, logged_user()->getId())) { $emails_in_conversation = MailContents::getMailsFromConversation($email); } else { $emails_in_conversation = array($email); } } foreach ($emails_in_conversation as $email) { if ($email->canDelete(logged_user())) { try { $email->trash(); ApplicationLogs::createLog($email, $email->getWorkspaces(), ApplicationLogs::ACTION_TRASH); $succ++; } catch (Exception $e) { $err++; } } else { $err++; } } } else { $err++; } break; default: $err++; break; } // switch } // for if ($err > 0) { $resultCode = 2; $resultMessage = lang("error delete objects", $err) . "<br />" . ($succ > 0 ? lang("success delete objects", $succ) : ""); } else { $resultMessage = lang("success delete objects", $succ); } ajx_add("overview-panel", "reload"); break; case "tag": $tag = $attributes["tag"]; if (!trim($tag)) { break; } for ($i = 0; $i < count($attributes["ids"]); $i++) { $id = $attributes["ids"][$i]; $type = $attributes["types"][$i]; switch ($type) { case "email": $email = MailContents::findById($id); if (isset($email)) { if (user_config_option('show_emails_as_conversations', true, logged_user()->getId())) { $emails_in_conversation = MailContents::getMailsFromConversation($email); } else { $emails_in_conversation = array($email); } foreach ($emails_in_conversation as $email) { if ($email->canEdit(logged_user())) { Tags::addObjectTag($tag, $email); ApplicationLogs::createLog($email, $email->getWorkspaces(), ApplicationLogs::ACTION_TAG, false, null, true, $tag); } } $resultMessage = lang("success tag objects", ''); } break; default: $resultMessage = lang("Unimplemented type: '" . $type . "'"); // if $resultCode = 2; break; } // switch } // for break; case "untag": $tag = $attributes["tag"]; for ($i = 0; $i < count($attributes["ids"]); $i++) { $id = $attributes["ids"][$i]; $type = $attributes["types"][$i]; switch ($type) { case "email": $email = MailContents::findById($id); if (isset($email)) { if (user_config_option('show_emails_as_conversations', true, logged_user()->getId())) { $emails_in_conversation = MailContents::getMailsFromConversation($email); } else { $emails_in_conversation = array($email); } foreach ($emails_in_conversation as $email) { if ($email->canEdit(logged_user())) { if ($tag != '') { $email->deleteTag($tag); } else { $email->clearTags(); } } } //ApplicationLogs::createLog($email, $email->getWorkspaces(), ApplicationLogs::ACTION_TAG,false,null,true,$tag); $resultMessage = lang("success untag objects", ''); } break; default: $resultMessage = lang("Unimplemented type: '" . $type . "'"); // if $resultCode = 2; break; } // switch } // for break; case "unclassify": for ($i = 0; $i < count($attributes["ids"]); $i++) { $id = $attributes["ids"][$i]; $type = $attributes["types"][$i]; switch ($type) { case "email": $email = MailContents::findById($id); if (isset($email) && !$email->isDeleted() && $email->canEdit(logged_user())) { $this->do_unclassify($email); ApplicationLogs::createLog($email, $email->getWorkspaces(), ApplicationLogs::ACTION_TAG, false, null, true, $tag); $resultMessage = lang("success unclassify emails", count($attributes["ids"])); } break; default: $resultMessage = lang("Unimplemented type: '" . $type . "'"); // if $resultCode = 2; break; } // switch } // for break; case "move": $wsid = $attributes["moveTo"]; $destination = Projects::findById($wsid); if (!$destination instanceof Project) { $resultMessage = lang('project dnx'); $resultCode = 1; } else { if (!can_add(logged_user(), $destination, 'MailContents')) { $resultMessage = lang('no access permissions'); $resultCode = 1; } else { $count = 0; for ($i = 0; $i < count($attributes["ids"]); $i++) { $id = $attributes["ids"][$i]; $type = $attributes["types"][$i]; switch ($type) { case "email": $email = MailContents::findById($id); if (user_config_option('show_emails_as_conversations', true, logged_user()->getId())) { $conversation = MailContents::getMailsFromConversation($email); } else { $conversation = array($email); } foreach ($conversation as $conv_email) { $this->addEmailToWorkspace($conv_email->getId(), $destination, array_var($attributes, "mantainWs", true)); if (array_var($attributes, 'classify_atts') && $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; } $tags = implode(",", $conv_email->getTagNames()); $this->classifyFile($classification_data, $conv_email, $parsedEmail, array($destination), array_var($attributes, "mantainWs", true), $tags); } } $count++; break; default: $resultMessage = lang("Unimplemented type: '" . $type . "'"); // if $resultCode = 2; break; } // switch } // for $resultMessage = lang("success move objects", $count); $resultCode = 0; } } break; case "checkmail": $resultCheck = MailController::checkmail(); $resultMessage = $resultCheck[1]; // if $resultCode = $resultCheck[0]; ajx_add("overview-panel", "reload"); break; case "markAsRead": case "markAsUnRead": for ($i = 0; $i < count($attributes["ids"]); $i++) { $id = $attributes["ids"][$i]; $type = $attributes["types"][$i]; switch ($type) { case "email": $email = MailContents::findById($id); if (isset($email)) { if (user_config_option('show_emails_as_conversations', true, logged_user()->getId())) { $emails_in_conversation = MailContents::getMailsFromConversation($email); } else { $emails_in_conversation = array($email); } foreach ($emails_in_conversation as $email) { if ($email->canEdit(logged_user())) { $email->setIsRead(logged_user()->getId(), $action == 'markAsRead'); } } } break; default: $resultMessage = lang("Unimplemented type: '" . $type . "'"); // if $resultCode = 2; break; } // switch } // for ajx_add("overview-panel", "reload"); break; case "archive": $err = 0; $succ = 0; for ($i = 0; $i < count($attributes["ids"]); $i++) { $id = $attributes["ids"][$i]; $type = $attributes["types"][$i]; switch ($type) { case "email": $email = MailContents::findById($id); if (isset($email)) { if (user_config_option('show_emails_as_conversations', true, logged_user()->getId())) { $emails_in_conversation = MailContents::getMailsFromConversation($email); } else { $emails_in_conversation = array($email); } foreach ($emails_in_conversation as $email) { if ($email->canEdit(logged_user())) { try { $email->archive(null); ApplicationLogs::createLog($email, $email->getWorkspaces(), ApplicationLogs::ACTION_ARCHIVE); $succ++; } catch (Exception $e) { $err++; } } } } else { $err++; } break; default: $err++; break; } // switch } // for if ($err > 0) { $resultCode = 2; $resultMessage = lang("error archive objects", $err) . "<br />" . ($succ > 0 ? lang("success archive objects", $succ) : ""); } else { $resultMessage = lang("success archive objects", $succ); } ajx_add("overview-panel", "reload"); break; default: if ($action) { $resultMessage = lang("Unimplemented action: '" . $action . "'"); // if $resultCode = 2; } break; } // switch return array("errorMessage" => $resultMessage, "errorCode" => $resultCode); }
/** * Returns the milestones included in the present workspace and all of its parents. This is because tasks from a particular workspace * can only be assigned to milestones from that workspace and from any of its parents. */ function get_workspace_milestones() { ajx_current("empty"); $ws_id = array_var($_GET, 'ws_id'); $workspace = Projects::findById($ws_id); if ($workspace instanceof Project) { $milestones = $workspace->getOpenMilestones(); $ms = array(); foreach ($milestones as $milestone) { $ms[] = array('id' => $milestone->getId(), 'name' => $milestone->getName()); } ajx_extra_data(array('milestones' => $ms)); } else { ajx_extra_data(array('milestones' => array())); } }
static function canAdd() { self::includeBasic(); $workspace_id = self::ogWorkspaceId(); if ($workspace_id == null) { return false; } $workspace = Projects::findById($workspace_id); if (!$workspace instanceof Project) { return false; } return can_add(self::getCompanyWebsite()->getLoggedUser(), $workspace, 'ProjectFiles'); }
/** * Edit task * * @access public * @param void * @return null */ function edit_task() { if (logged_user()->isGuest()) { flash_error(lang('no access permissions')); ajx_current("empty"); return; } $this->setTemplate('add_task'); $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 $task_data = array_var($_POST, 'task'); if (!is_array($task_data)) { $this->getRepeatOptions($task, $occ, $rsel1, $rsel2, $rsel3, $rnum, $rend, $rjump); $tag_names = $task->getTagNames(); $task_data = array('title' => array_var($_POST, 'title', $task->getTitle()), 'text' => $task->getText(), 'milestone_id' => array_var($_POST, 'milestone_id', $task->getMilestoneId()), 'due_date' => getDateValue(array_var($_POST, 'task_due_date'), $task->getDueDate()), 'start_date' => getDateValue(array_var($_POST, 'task_start_date', $task->getStartDate())), 'parent_id' => $task->getParentId(), 'project_id' => array_var($_POST, 'project_id', $task->getProjectId()), 'tags' => is_array($tag_names) && count($tag_names) ? implode(', ', $tag_names) : '', 'is_private' => $task->isPrivate(), 'assigned_to' => array_var($_POST, 'assigned_to', $task->getAssignedToCompanyId() . ':' . $task->getAssignedToUserId()), 'priority' => array_var($_POST, 'priority', $task->getPriority()), 'send_notification' => array_var($_POST, 'notify') == 'true', 'time_estimate' => $task->getTimeEstimate(), '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'))); // array $handins = ObjectHandins::getAllHandinsByObject($task); $id = 0; if ($handins) { foreach ($handins as $handin) { $task_data['handin' . $id] = array('title' => $handin->getTitle(), 'assigned_to' => $handin->getResponsibleCompanyId() . ':' . $handin->getResponsibleUserId()); // array $id = $id + 1; if ($id > 3) { break; } } // foreach } // if } // if tpl_assign('task', $task); tpl_assign('task_data', $task_data); if (is_array(array_var($_POST, 'task'))) { //MANAGE CONCURRENCE WHILE EDITING $upd = array_var($_POST, 'updatedon'); if ($upd && $task->getUpdatedOn()->getTimestamp() > $upd && !array_var($_POST, 'merge-changes') == 'true') { ajx_current('empty'); evt_add("handle edit concurrence", array("updatedon" => $task->getUpdatedOn()->getTimestamp(), "genid" => array_var($_POST, 'genid'))); return; } if (array_var($_POST, 'merge-changes') == 'true') { $this->setTemplate('view_list'); $edited_task = ProjectTasks::findById($task->getId()); ajx_set_no_toolbar(true); ajx_set_panel(lang('tab name', array('name' => $edited_task->getTitle()))); tpl_assign('task_list', $edited_task); ajx_extra_data(array("title" => $edited_task->getTitle(), 'icon' => 'ico-task')); return; } $old_owner = $task->getAssignedTo(); if (array_var($task_data, 'parent_id') == $task->getId()) { flash_error(lang("task own parent error")); ajx_current("empty"); return; } $old_is_private = $task->isPrivate(); $old_project_id = $task->getProjectId(); $project_id = array_var($_POST, 'ws_ids', 0); if ($old_project_id != $project_id) { $newProject = Projects::findById($project_id); if (!$newProject instanceof Project || !$task->canAdd(logged_user(), $newProject)) { flash_error(lang('no access permissions')); ajx_current("empty"); return; } } $task_data['due_date'] = getDateValue(array_var($_POST, 'task_due_date')); $task_data['start_date'] = getDateValue(array_var($_POST, 'task_start_date')); try { $err_msg = $this->setRepeatOptions($task_data); if ($err_msg) { flash_error($err_msg); ajx_current("empty"); return; } if (!isset($task_data['parent_id'])) { $task_data['parent_id'] = 0; } $was_template = $task->getIsTemplate(); $task->setFromAttributes($task_data); $task->setIsTemplate($was_template); // is_template value must not be changed from ui // Set assigned to $assigned_to = explode(':', array_var($task_data, 'assigned_to', '')); $company_id = array_var($assigned_to, 0, 0); $user_id = array_var($assigned_to, 1, 0); $can_assign = can_assign_task_to_company_user(logged_user(), $task, $company_id, $user_id); if ($can_assign !== true) { flash_error($can_assign); return; } $task->setAssignedToCompanyId($company_id); $task->setAssignedToUserId($user_id); if (!logged_user()->isMemberOfOwnerCompany()) { $task->setIsPrivate($old_is_private); } $totalMinutes = array_var($task_data, 'time_estimate_hours') * 60 + array_var($task_data, 'time_estimate_minutes'); $task->setTimeEstimate($totalMinutes); //Add handins $handins = array(); for ($i = 0; $i < 4; $i++) { if (isset($task_data["handin{$i}"]) && is_array($task_data["handin{$i}"]) && trim(array_var($task_data["handin{$i}"], 'title')) != '') { $assigned_to = explode(':', array_var($task_data["handin{$i}"], 'assigned_to', '')); $handins[] = array('title' => array_var($task_data["handin{$i}"], 'title'), 'responsible_company_id' => array_var($assigned_to, 0, 0), 'responsible_user_id' => array_var($assigned_to, 1, 0)); // array } // if } // for if ($task->getParentId() > 0 && $task->hasChild($task->getParentId())) { flash_error(lang('task child of child error')); ajx_current("empty"); return; } DB::beginWork(); $task->save(); $task->setTagsFromCSV(array_var($task_data, 'tags')); $object_controller = new ObjectController(); $object_controller->add_to_workspaces($task, !$task->getIsTemplate()); $object_controller->link_to_new_object($task); $object_controller->add_subscribers($task); $object_controller->add_custom_properties($task); $object_controller->add_reminders($task); // apply values to subtasks $subtasks = $task->getAllSubTasks(); $project = $task->getProject(); $milestone_id = $task->getMilestoneId(); $apply_ws = array_var($task_data, 'apply_ws_subtasks') == "checked"; $apply_ms = array_var($task_data, 'apply_milestone_subtasks') == "checked"; $apply_at = array_var($task_data, 'apply_assignee_subtasks', '') == "checked"; foreach ($subtasks as $sub) { $modified = false; if ($apply_at || !$sub->getAssignedTo() instanceof ApplicationDataObject) { $sub->setAssignedToCompanyId($company_id); $sub->setAssignedToUserId($user_id); $modified = true; } if ($apply_ws) { $sub->setProject($project); $modified = true; } if ($apply_ms) { $sub->setMilestoneId($milestone_id); $modified = true; } if ($modified) { $sub->save(); } } $task->resetIsRead(); ApplicationLogs::createLog($task, $task->getWorkspaces(), ApplicationLogs::ACTION_EDIT); DB::commit(); try { if (array_var($task_data, 'send_notification') == 'checked') { $new_owner = $task->getAssignedTo(); if ($new_owner instanceof User) { Notifier::taskAssigned($task); } // if } // if } catch (Exception $e) { } // try flash_success(lang('success edit task list', $task->getTitle())); ajx_current("back"); } catch (Exception $e) { DB::rollback(); flash_error($e->getMessage()); ajx_current("empty"); } // try } // if }
function move() { if (logged_user()->isGuest()) { flash_error(lang('no access permissions')); ajx_current("empty"); return; } ajx_current("empty"); $id = get_id(); $to = array_var($_GET, 'to', 0); // TODO: check permissions $ws = Projects::findById($id); $parent = Projects::findById($to); if (isset($ws)) { if ($to == 0 || isset($parent)) { $ws->setParentId($to); $ws->save(); evt_add('workspace_edited', array("is" => $ws->getId(), "name" => $ws->getId(), "color" => $ws->getId(), "parent" => $ws->getParentId())); } } }
/** * Return associative array of changes that is easy to display * * @param void * @return array */ function getVerboseChanges() { $result = array(); if (is_foreachable($this->getChanges())) { foreach ($this->getChanges() as $field => $change_data) { list($old_value, $new_value) = $change_data; $log_fields = array('project_id', 'milestone_id', 'parent_id', 'name', 'body', 'priority', 'due_on'); switch ($field) { case 'project_id': $old_project = Projects::findById($old_value); $new_project = Projects::findById($new_value); $old_project_name = instance_of($old_project, 'Project') ? $old_project->getName() : lang('unknown project'); $new_project_name = instance_of($new_project, 'Project') ? $new_project->getName() : lang('unknown project'); $result[] = lang('Moved from <span>:from</span> to <span>:to</span>', array('from' => $old_project_name, 'to' => $new_project_name)); break; case 'milestone_id': $old_milestone = Milestones::findById($old_value); $new_milestone = Milestones::findById($new_value); $old_milestone_name = instance_of($old_milestone, 'Milestone') ? $old_milestone->getName() : lang('-- none --'); $new_milestone_name = instance_of($new_milestone, 'Milestone') ? $new_milestone->getName() : lang('-- none --'); $result[] = lang('Moved from <span>:from</span> to <span>:to</span> milestone', array('from' => $old_milestone_name, 'to' => $new_milestone_name)); break; case 'parent_id': $old_parent = ProjectObjects::findById($old_value); $new_parent = ProjectObjects::findById($new_value); $old_parent_name = instance_of($old_parent, 'Category') ? $old_parent->getName() : lang('-- none --'); $new_parent_name = instance_of($new_parent, 'Category') ? $new_parent->getName() : lang('-- none --'); $result[] = lang('Moved from <span>:from</span> to <span>:to</span> category', array('from' => $old_parent_name, 'to' => $new_parent_name)); break; case 'name': $result[] = lang('Summary is changed from <span>:from</span> to <span>:to</span>', array('from' => $old_value, 'to' => $new_value)); break; case 'body': $result[] = lang('Long description is changed'); break; case 'priority': switch ($old_value) { case PRIORITY_HIGHEST: $old_priority = lang('Highest'); break; case PRIORITY_HIGH: $old_priority = lang('High'); break; case PRIORITY_NORMAL: $old_priority = lang('Normal'); break; case PRIORITY_LOW: $old_priority = lang('Low'); break; case PRIORITY_LOWEST: $old_priority = lang('Lowest'); break; case PRIORITY_ONGOING: $old_priority = lang('Ongoing'); break; case PRIORITY_HOLD: $old_priority = lang('Hold'); break; } // switch switch ($new_value) { case PRIORITY_HIGHEST: $new_priority = lang('Highest'); break; case PRIORITY_HIGH: $new_priority = lang('High'); break; case PRIORITY_NORMAL: $new_priority = lang('Normal'); break; case PRIORITY_LOW: $new_priority = lang('Low'); break; case PRIORITY_LOWEST: $new_priority = lang('Lowest'); break; case PRIORITY_ONGOING: $new_priority = lang('Ongoing'); break; case PRIORITY_HOLD: $new_priority = lang('Hold'); break; } // switch $result[] = lang('Priority is changed from <span>:from</span> to <span>:to</span>', array('from' => $old_priority, 'to' => $new_priority)); break; case 'due_on': require_once SMARTY_PATH . '/plugins/modifier.date.php'; $old_due_on = instance_of($old_value, 'DateValue') ? smarty_modifier_date($old_value, 0) : lang('-- none --'); $new_due_on = instance_of($new_value, 'DateValue') ? smarty_modifier_date($new_value, 0) : lang('-- none --'); $result[] = lang('Due date is changed from <span>:from</span> to <span>:to</span>', array('from' => $old_due_on, 'to' => $new_due_on)); break; case 'completed_on': if (instance_of($old_value, 'DateValue') && $new_value === null) { $result[] = lang('Status changed to: Open'); } elseif ($old_value === null && instance_of($new_value, 'DateValue')) { $result[] = lang('Status changed to: Completed'); } // if break; case 'owner': if ($new_value) { $new_owner = Users::findById($new_value); if (instance_of($new_owner, 'User')) { $result[] = lang(':user is responsible', array('user' => $new_owner->getDisplayName())); } else { $result[] = lang('Owner changed (unknown user or deleted in the meantime)'); } // if } else { $result[] = lang('Anyone can pick up and work on this ticket'); } // if break; case 'assignees': $old_assignees = array(); if (is_foreachable($old_value)) { $old_assignees_users = Users::findByIds($old_value); if (is_foreachable($old_assignees_users)) { foreach ($old_assignees_users as $user) { $old_assignees[$user->getId()] = $user->getDisplayName(); } // foreach } // if } // if $new_assignees = array(); if (is_foreachable($new_value)) { $new_assignees_users = Users::findByIds($new_value); if (is_foreachable($new_assignees_users)) { foreach ($new_assignees_users as $user) { $new_assignees[$user->getId()] = $user->getDisplayName(); } // foreach } // if } // if foreach ($new_assignees as $new_assignee_id => $new_assignee) { if (!array_key_exists($new_assignee_id, $old_assignees)) { $result[] = lang(':user has been assigned to this ticket', array('user' => $new_assignee)); } // if } // foreach foreach ($old_assignees as $old_assignee_id => $old_assignee) { if (!array_key_exists($old_assignee_id, $new_assignees)) { $result[] = lang(':user has been removed from this ticket', array('user' => $old_assignee)); } // if } // foreach break; } // switch } // foreach } // if return $result; }
function SaveMail(&$content, MailAccount $account, $uidl, $state = 0, $imap_folder_name = '') { if (defined('DEBUG_EMAIL_RETRIEVAL') && DEBUG_EMAIL_RETRIEVAL) { self::log_connection_status(); Logger::log("UID: {$uidl}"); } if (!mysql_ping(DB::connection()->getLink())) { DB::connection()->reconnect(); Logger::log("*** Connection Lost -> Reconnected ***"); } if (defined('DEBUG_EMAIL_RETRIEVAL') && DEBUG_EMAIL_RETRIEVAL) { Logger::log("mem 1) " . format_filesize(memory_get_usage())); } if (strpos($content, '+OK ') > 0) { $content = substr($content, strpos($content, '+OK ')); } if (defined('DEBUG_EMAIL_RETRIEVAL') && DEBUG_EMAIL_RETRIEVAL) { Logger::log("mem 2) " . format_filesize(memory_get_usage())); } self::parseMail($content, $decoded, $parsedMail, $warnings); if (defined('DEBUG_EMAIL_RETRIEVAL') && DEBUG_EMAIL_RETRIEVAL) { Logger::log("mem 3) " . format_filesize(memory_get_usage())); } $encoding = array_var($parsedMail, 'Encoding', 'UTF-8'); $enc_conv = EncodingConverter::instance(); $to_addresses = self::getAddresses(array_var($parsedMail, "To")); $from = self::getAddresses(array_var($parsedMail, "From")); $message_id = self::getHeaderValueFromContent($content, "Message-ID"); $in_reply_to_id = self::getHeaderValueFromContent($content, "In-Reply-To"); if (defined('DEBUG_EMAIL_RETRIEVAL') && DEBUG_EMAIL_RETRIEVAL) { Logger::log("mem 4) " . format_filesize(memory_get_usage())); } $uid = trim($uidl); if (str_starts_with($uid, '<') && str_ends_with($uid, '>')) { $uid = utf8_substr($uid, 1, utf8_strlen($uid, $encoding) - 2, $encoding); } if ($uid == '') { $uid = trim($message_id); if ($uid == '') { $uid = array_var($parsedMail, 'Subject', 'MISSING UID'); } if (str_starts_with($uid, '<') && str_ends_with($uid, '>')) { $uid = utf8_substr($uid, 1, utf8_strlen($uid, $encoding) - 2, $encoding); } if (MailContents::mailRecordExists($account->getId(), $uid, $imap_folder_name == '' ? null : $imap_folder_name)) { return; } } if (!$from) { $parsedMail["From"] = self::getFromAddressFromContent($content); $from = array_var($parsedMail["From"][0], 'address', ''); if (defined('DEBUG_EMAIL_RETRIEVAL') && DEBUG_EMAIL_RETRIEVAL) { Logger::log("mem 4.1) " . format_filesize(memory_get_usage())); } } if (defined('DEBUG_EMAIL_RETRIEVAL') && DEBUG_EMAIL_RETRIEVAL) { Logger::log("mem 5) " . format_filesize(memory_get_usage())); } if (defined('EMAIL_MESSAGEID_CONTROL') && EMAIL_MESSAGEID_CONTROL) { if (trim($message_id) != "") { $id_condition = " AND `message_id`='" . trim($message_id) . "'"; } else { $id_condition = " AND `subject`='" . trim(array_var($parsedMail, 'Subject')) . "' AND `from`='{$from}'"; if (array_var($parsedMail, 'Date')) { $sent_date_dt = new DateTimeValue(strtotime(array_var($parsedMail, 'Date'))); $sent_date_str = $sent_date_dt->toMySQL(); $id_condition .= " AND `sent_date`='" . $sent_date_str . "'"; } } $same = MailContents::findOne(array('conditions' => "`account_id`=" . $account->getId() . $id_condition, 'include_trashed' => true)); if ($same instanceof MailContent) { return; } } if ($state == 0) { if ($from == $account->getEmailAddress()) { if (strpos($to_addresses, $from) !== FALSE) { $state = 5; } else { $state = 1; } //Show only in sent folder } } if (defined('DEBUG_EMAIL_RETRIEVAL') && DEBUG_EMAIL_RETRIEVAL) { Logger::log("mem 6) " . format_filesize(memory_get_usage())); self::log_connection_status(); } $from_spam_junk_folder = strpos(strtolower($imap_folder_name), 'spam') !== FALSE || strpos(strtolower($imap_folder_name), 'junk') !== FALSE || strpos(strtolower($imap_folder_name), 'trash') !== FALSE; $user_id = logged_user() instanceof User ? logged_user()->getId() : $account->getUserId(); if (defined('DEBUG_EMAIL_RETRIEVAL') && DEBUG_EMAIL_RETRIEVAL) { self::log_connection_status(); } $max_spam_level = user_config_option('max_spam_level', null, $user_id); if ($max_spam_level < 0) { $max_spam_level = 0; } $mail_spam_level = strlen(trim(array_var($decoded[0]['Headers'], 'x-spam-level:', ''))); // if max_spam_level >= 10 then nothing goes to junk folder $spam_in_subject = false; if (config_option('check_spam_in_subject')) { $spam_in_subject = strpos_utf(strtoupper(array_var($parsedMail, 'Subject')), "**SPAM**") !== false; } if ($max_spam_level < 10 && ($mail_spam_level > $max_spam_level || $from_spam_junk_folder) || $spam_in_subject) { $state = 4; // send to Junk folder } if (defined('DEBUG_EMAIL_RETRIEVAL') && DEBUG_EMAIL_RETRIEVAL) { Logger::log("mem 7) " . format_filesize(memory_get_usage())); self::log_connection_status(); } if (!isset($parsedMail['Subject'])) { $parsedMail['Subject'] = ''; } $mail = new MailContent(); $mail->setAccountId($account->getId()); $mail->setState($state); $mail->setImapFolderName($imap_folder_name); $mail->setFrom($from); $cc = trim(self::getAddresses(array_var($parsedMail, "Cc"))); if ($cc == '' && array_var($decoded, 0) && array_var($decoded[0], 'Headers')) { $cc = array_var($decoded[0]['Headers'], 'cc:', ''); } if (defined('DEBUG_EMAIL_RETRIEVAL') && DEBUG_EMAIL_RETRIEVAL) { self::log_connection_status(); Logger::log("mem 8) " . format_filesize(memory_get_usage())); } $mail->setCc($cc); $from_name = trim(array_var(array_var(array_var($parsedMail, 'From'), 0), 'name')); $from_encoding = detect_encoding($from_name); if ($from_name == '') { $from_name = $from; } else { if (strtoupper($encoding) == 'KOI8-R' || strtoupper($encoding) == 'CP866' || $from_encoding != 'UTF-8' || !$enc_conv->isUtf8RegExp($from_name)) { //KOI8-R and CP866 are Russian encodings which PHP does not detect $utf8_from = $enc_conv->convert($encoding, 'UTF-8', $from_name); if ($enc_conv->hasError()) { $utf8_from = utf8_encode($from_name); } $utf8_from = utf8_safe($utf8_from); $mail->setFromName($utf8_from); } else { $mail->setFromName($from_name); } } $subject_aux = $parsedMail['Subject']; $subject_encoding = detect_encoding($subject_aux); if (strtoupper($encoding) == 'KOI8-R' || strtoupper($encoding) == 'CP866' || $subject_encoding != 'UTF-8' || !$enc_conv->isUtf8RegExp($subject_aux)) { //KOI8-R and CP866 are Russian encodings which PHP does not detect $utf8_subject = $enc_conv->convert($encoding, 'UTF-8', $subject_aux); if ($enc_conv->hasError()) { $utf8_subject = utf8_encode($subject_aux); } $utf8_subject = utf8_safe($utf8_subject); $mail->setSubject($utf8_subject); } else { $utf8_subject = utf8_safe($subject_aux); $mail->setSubject($utf8_subject); } if (defined('DEBUG_EMAIL_RETRIEVAL') && DEBUG_EMAIL_RETRIEVAL) { self::log_connection_status(); Logger::log("mem 9) " . format_filesize(memory_get_usage())); } $mail->setTo($to_addresses); $sent_timestamp = false; if (array_key_exists("Date", $parsedMail)) { $sent_timestamp = strtotime($parsedMail["Date"]); } if ($sent_timestamp === false || $sent_timestamp === -1 || $sent_timestamp === 0) { $mail->setSentDate(DateTimeValueLib::now()); } else { $mail->setSentDate(new DateTimeValue($sent_timestamp)); } // if this constant is defined, mails older than this date will not be fetched if (defined('FIRST_MAIL_DATE')) { $first_mail_date = DateTimeValueLib::makeFromString(FIRST_MAIL_DATE); if ($mail->getSentDate()->getTimestamp() < $first_mail_date->getTimestamp()) { // return true to stop getting older mails from the server return true; } } $received_timestamp = false; if (array_key_exists("Received", $parsedMail) && $parsedMail["Received"]) { $received_timestamp = strtotime($parsedMail["Received"]); } if ($received_timestamp === false || $received_timestamp === -1 || $received_timestamp === 0) { $mail->setReceivedDate($mail->getSentDate()); } else { $mail->setReceivedDate(new DateTimeValue($received_timestamp)); if ($state == 5 && $mail->getSentDate()->getTimestamp() > $received_timestamp) { $mail->setReceivedDate($mail->getSentDate()); } } if (defined('DEBUG_EMAIL_RETRIEVAL') && DEBUG_EMAIL_RETRIEVAL) { self::log_connection_status(); Logger::log("mem 10) " . format_filesize(memory_get_usage())); } $mail->setSize(strlen($content)); $mail->setHasAttachments(!empty($parsedMail["Attachments"])); $mail->setCreatedOn(new DateTimeValue(time())); $mail->setCreatedById($account->getUserId()); $mail->setAccountEmail($account->getEmail()); $mail->setMessageId($message_id); $mail->setInReplyToId($in_reply_to_id); $mail->setUid($uid); $type = array_var($parsedMail, 'Type', 'text'); switch ($type) { case 'html': $utf8_body = $enc_conv->convert($encoding, 'UTF-8', array_var($parsedMail, 'Data', '')); if ($enc_conv->hasError()) { $utf8_body = utf8_encode(array_var($parsedMail, 'Data', '')); } $utf8_body = utf8_safe($utf8_body); $mail->setBodyHtml($utf8_body); break; case 'text': $utf8_body = $enc_conv->convert($encoding, 'UTF-8', array_var($parsedMail, 'Data', '')); if ($enc_conv->hasError()) { $utf8_body = utf8_encode(array_var($parsedMail, 'Data', '')); } $utf8_body = utf8_safe($utf8_body); $mail->setBodyPlain($utf8_body); break; case 'delivery-status': $utf8_body = $enc_conv->convert($encoding, 'UTF-8', array_var($parsedMail, 'Response', '')); if ($enc_conv->hasError()) { $utf8_body = utf8_encode(array_var($parsedMail, 'Response', '')); } $utf8_body = utf8_safe($utf8_body); $mail->setBodyPlain($utf8_body); break; default: break; } if (isset($parsedMail['Alternative'])) { foreach ($parsedMail['Alternative'] as $alt) { if ($alt['Type'] == 'html' || $alt['Type'] == 'text') { $body = $enc_conv->convert(array_var($alt, 'Encoding', 'UTF-8'), 'UTF-8', array_var($alt, 'Data', '')); if ($enc_conv->hasError()) { $body = utf8_encode(array_var($alt, 'Data', '')); } // remove large white spaces $exploded = preg_split("/[\\s]+/", $body, -1, PREG_SPLIT_NO_EMPTY); $body = implode(" ", $exploded); // remove html comments $body = preg_replace('/<!--.*-->/i', '', $body); } $body = utf8_safe($body); if ($alt['Type'] == 'html') { $mail->setBodyHtml($body); } else { if ($alt['Type'] == 'text') { $plain = html_to_text(html_entity_decode($utf8_body, null, "UTF-8")); $mail->setBodyPlain($plain); } } // other alternative parts (like images) are not saved in database. } } $repository_id = self::SaveContentToFilesystem($mail->getUid(), $content); $mail->setContentFileId($repository_id); if (defined('DEBUG_EMAIL_RETRIEVAL') && DEBUG_EMAIL_RETRIEVAL) { self::log_connection_status(); Logger::log("mem 11) " . format_filesize(memory_get_usage())); } try { if ($in_reply_to_id != "") { if ($message_id != "") { $conv_mail = MailContents::findOne(array("conditions" => "`account_id`=" . $account->getId() . " AND `in_reply_to_id` = '{$message_id}'")); if (!$conv_mail) { $conv_mail = MailContents::findOne(array("conditions" => "`account_id`=" . $account->getId() . " AND `message_id` = '{$in_reply_to_id}'")); } else { // Search for other discontinued conversation part to link it $other_conv_emails = MailContents::findAll(array("conditions" => "`account_id`=" . $account->getId() . " AND `message_id` = '{$in_reply_to_id}' AND `conversation_id`<>" . $conv_mail->getConversationId())); } } else { $conv_mail = MailContents::findOne(array("conditions" => "`account_id`=" . $account->getId() . " AND `message_id` = '{$in_reply_to_id}'")); } if ($conv_mail instanceof MailContent) { // Remove "Re: ", "Fwd: ", etc to compare the subjects $conv_original_subject = strtolower($conv_mail->getSubject()); if (($pos = strrpos($conv_original_subject, ":")) !== false) { $conv_original_subject = trim(substr($conv_original_subject, $pos + 1)); } } if ($conv_mail instanceof MailContent && strpos(strtolower($mail->getSubject()), strtolower($conv_original_subject)) !== false) { $mail->setConversationId($conv_mail->getConversationId()); if (isset($other_conv_emails) && is_array($other_conv_emails)) { foreach ($other_conv_emails as $ocm) { $ocm->setConversationId($conv_mail->getConversationId()); $ocm->save(); } } } else { $conv_id = MailContents::getNextConversationId($account->getId()); $mail->setConversationId($conv_id); } } else { $conv_id = MailContents::getNextConversationId($account->getId()); $mail->setConversationId($conv_id); } if (defined('DEBUG_EMAIL_RETRIEVAL') && DEBUG_EMAIL_RETRIEVAL) { self::log_connection_status(); Logger::log("mem 12) " . format_filesize(memory_get_usage())); } $mail->save(); if (defined('DEBUG_EMAIL_RETRIEVAL') && DEBUG_EMAIL_RETRIEVAL) { self::log_connection_status(); Logger::log("mem 13) " . format_filesize(memory_get_usage())); } // CLASSIFY RECEIVED MAIL WITH THE CONVERSATION if (user_config_option('classify_mail_with_conversation', null, $account->getUserId()) && isset($conv_mail) && $conv_mail instanceof MailContent) { $wss = $conv_mail->getWorkspaces(); foreach ($wss as $ws) { $acc_user = Users::findById($account->getUserId()); if ($acc_user instanceof User && $acc_user->hasProjectPermission($ws, ProjectUsers::CAN_READ_MAILS)) { $mail->addToWorkspace($ws); } } } // CLASSIFY MAILS IF THE ACCOUNT HAS A WORKSPACE if ($account->getColumnValue('workspace', 0) != 0) { $workspace = Projects::findById($account->getColumnValue('workspace', 0)); if ($workspace && $workspace instanceof Project && !$mail->hasWorkspace($workspace)) { $mail->addToWorkspace($workspace); } } //END CLASSIFY $user = Users::findById($account->getUserId()); if ($user instanceof User) { $mail->subscribeUser($user); } } catch (Exception $e) { FileRepository::deleteFile($repository_id); if (strpos($e->getMessage(), "Query failed with message 'Got a packet bigger than 'max_allowed_packet' bytes'") === false) { throw $e; } } unset($parsedMail); if (defined('DEBUG_EMAIL_RETRIEVAL') && DEBUG_EMAIL_RETRIEVAL) { Logger::log("mem fin) " . format_filesize(memory_get_usage())); self::log_connection_status(); } return false; }
/** * Move task list * * @access public * @param void * @return null */ function move_list() { $this->setTemplate('move_list'); $task_list = ProjectTaskLists::findById(get_id()); if (!$task_list instanceof ProjectTaskList) { flash_error(lang('task list dnx')); $this->redirectTo('task', 'index'); } // if if (!$task_list->canDelete(logged_user(), active_project())) { flash_error(lang('no access permissions')); $this->redirectTo('task', 'index'); } // if $move_data = array_var($_POST, 'move_data'); tpl_assign('task_list', $task_list); tpl_assign('move_data', $move_data); if (is_array($move_data)) { $target_project_id = $move_data['target_project_id']; $target_project = Projects::findById($target_project_id); if (!$target_project instanceof Project) { flash_error(lang('project dnx')); $this->redirectToUrl($task_list->getMoveUrl()); } // if if (!$task_list->canAdd(logged_user(), $target_project)) { flash_error(lang('no access permissions')); $this->redirectToUrl($task_list->getMoveUrl()); } // if try { DB::beginWork(); $task_list->setProjectId($target_project_id); $task_list->save(); ApplicationLogs::createLog($task_list, active_project(), ApplicationLogs::ACTION_DELETE); ApplicationLogs::createLog($task_list, $target_project, ApplicationLogs::ACTION_ADD); DB::commit(); flash_success(lang('success move task list', $task_list->getName(), active_project()->getName(), $target_project->getName())); } catch (Exception $e) { DB::rollback(); flash_error(lang('error move task list')); } // try $this->redirectToUrl($task_list->getViewUrl()); } }
/** * Return owner project. If project_id field does not exists NULL is returned * * @param void * @return Project */ function getProject() { if ($this->isNew() && function_exists('active_project')) { return active_project(); } // if if (is_null($this->project)) { if ($this->columnExists('project_id')) { $this->project = Projects::findById($this->getProjectId()); } } // if return $this->project; }