2 // +----------------------------------------------------------------------+
 
   3 // | Anuko Time Tracker
 
   4 // +----------------------------------------------------------------------+
 
   5 // | Copyright (c) Anuko International Ltd. (https://www.anuko.com)
 
   6 // +----------------------------------------------------------------------+
 
   7 // | LIBERAL FREEWARE LICENSE: This source code document may be used
 
   8 // | by anyone for any purpose, and freely redistributed alone or in
 
   9 // | combination with other software, provided that the license is obeyed.
 
  11 // | There are only two ways to violate the license:
 
  13 // | 1. To redistribute this code in source form, with the copyright
 
  14 // |    notice or license removed or altered. (Distributing in compiled
 
  15 // |    forms without embedded copyright notices is permitted).
 
  17 // | 2. To redistribute modified versions of this code in *any* form
 
  18 // |    that bears insufficient indications that the modifications are
 
  19 // |    not the work of the original author(s).
 
  21 // | This license applies to this document only, not any other software
 
  22 // | that it may be combined with.
 
  24 // +----------------------------------------------------------------------+
 
  26 // | https://www.anuko.com/time_tracker/credits.htm
 
  27 // +----------------------------------------------------------------------+
 
  29 import('ttConfigHelper');
 
  32   var $login = null;            // User login.
 
  33   var $name = null;             // User name.
 
  34   var $id = null;               // User id.
 
  35   var $group_id = null;         // Group id.
 
  36   var $role_id = null;          // Role id.
 
  37   var $role_name = null;        // Role name.
 
  38   var $rank = null;             // User role rank.
 
  39   var $client_id = null;        // Client id for client user role.
 
  40   var $behalf_id = null;        // User id, on behalf of whom we are working.
 
  41   var $behalf_group_id = null;  // Group id, on behalf of which we are working.
 
  42   var $behalf_name = null;      // User name, on behalf of whom we are working.
 
  43   var $behalf_group = null;     // Group name, on behalf of which we are working.
 
  44   var $email = null;            // User email.
 
  45   var $lang = null;             // Language.
 
  46   var $decimal_mark = null;     // Decimal separator.
 
  47   var $date_format = null;      // Date format.
 
  48   var $time_format = null;      // Time format.
 
  49   var $week_start = 0;          // Week start day.
 
  50   var $show_holidays = 0;       // Whether to show holidays in calendar.
 
  51   var $tracking_mode = 0;       // Tracking mode.
 
  52   var $project_required = 0;    // Whether project selection is required on time entires.
 
  53   var $task_required = 0;       // Whether task selection is required on time entires.
 
  54   var $record_type = 0;         // Record type (duration vs start and finish, or both).
 
  55   var $punch_mode = 0;          // Whether punch mode is enabled for user.
 
  56   var $allow_overlap = 0;       // Whether to allow overlapping time entries.
 
  57   var $future_entries = 0;      // Whether to allow creating future entries.
 
  58   var $uncompleted_indicators = 0; // Uncompleted time entry indicators (show nowhere or on users page).
 
  59   var $bcc_email = null;        // Bcc email.
 
  60   var $allow_ip = null;         // Specification from where user is allowed access.
 
  61   var $password_complexity = null; // Password complexity example.
 
  62   var $currency = null;         // Currency.
 
  63   var $plugins = null;          // Comma-separated list of enabled plugins.
 
  64   var $config = null;           // Comma-separated list of miscellaneous config options.
 
  65   var $group = null;            // Group name.
 
  66   var $custom_logo = 0;         // Whether to use a custom logo for group.
 
  67   var $lock_spec = null;        // Cron specification for record locking.
 
  68   var $workday_minutes = 480;   // Number of work minutes in a regular day.
 
  69   var $rights = array();        // An array of user rights such as 'track_own_time', etc.
 
  70   var $is_client = false;       // Whether user is a client as determined by missing 'track_own_time' right.
 
  71   var $minutes_in_unit = 15;    // Number of minutes in unit for Work units plugin.
 
  72   var $first_unit_threshold = 0;// Threshold for 1st unit for Work units plugin.
 
  73   var $unit_totals_only = 0;    // Totlas only option for the Work units plugin.
 
  76   function __construct($login, $id = null) {
 
  77     if (!$login && !$id) {
 
  78       // nothing to initialize
 
  82     $mdb2 = getConnection();
 
  84     $sql = "SELECT u.id, u.login, u.name, u.group_id, u.role_id, r.rank, r.name as role_name, r.rights, u.client_id, u.email, g.name as group_name,
 
  85       g.currency, g.lang, g.decimal_mark, g.date_format, g.time_format, g.week_start,
 
  86       g.tracking_mode, g.project_required, g.task_required, g.record_type,
 
  87       g.bcc_email, g.allow_ip, g.password_complexity, g.plugins, g.config, g.lock_spec, g.workday_minutes, g.custom_logo
 
  88       FROM tt_users u LEFT JOIN tt_groups g ON (u.group_id = g.id) LEFT JOIN tt_roles r on (r.id = u.role_id) WHERE ";
 
  92       $sql .= "u.login = ".$mdb2->quote($login);
 
  93     $sql .= " AND u.status = 1";
 
  95     $res = $mdb2->query($sql);
 
  96     if (is_a($res, 'PEAR_Error')) {
 
 100     $val = $res->fetchRow();
 
 101     if ($val['id'] > 0) {
 
 102       $this->login = $val['login'];
 
 103       $this->name = $val['name'];
 
 104       $this->id = $val['id'];
 
 105       $this->group_id = $val['group_id'];
 
 106       $this->role_id = $val['role_id'];
 
 107       $this->role_name = $val['role_name'];
 
 108       $this->rights = explode(',', $val['rights']);
 
 109       $this->is_client = !in_array('track_own_time', $this->rights);
 
 110       $this->rank = $val['rank'];
 
 111       $this->client_id = $val['client_id'];
 
 112       $this->email = $val['email'];
 
 113       $this->lang = $val['lang'];
 
 114       $this->decimal_mark = $val['decimal_mark'];
 
 115       $this->date_format = $val['date_format'];
 
 116       $this->time_format = $val['time_format'];
 
 117       $this->week_start = $val['week_start'];
 
 118       $this->tracking_mode = $val['tracking_mode'];
 
 119       $this->project_required = $val['project_required'];
 
 120       $this->task_required = $val['task_required'];
 
 121       $this->record_type = $val['record_type'];
 
 122       $this->bcc_email = $val['bcc_email'];
 
 123       $this->allow_ip = $val['allow_ip'];
 
 124       $this->password_complexity = $val['password_complexity'];
 
 125       $this->group = $val['group_name'];
 
 126       $this->currency = $val['currency'];
 
 127       $this->plugins = $val['plugins'];
 
 128       $this->lock_spec = $val['lock_spec'];
 
 129       $this->workday_minutes = $val['workday_minutes'];
 
 130       $this->custom_logo = $val['custom_logo'];
 
 132       $this->config = $val['config'];
 
 133       $config = new ttConfigHelper($this->config);
 
 134       // Set user config options.
 
 135       $this->show_holidays = $config->getDefinedValue('show_holidays');
 
 136       $this->punch_mode = $config->getDefinedValue('punch_mode');
 
 137       $this->allow_overlap = $config->getDefinedValue('allow_overlap');
 
 138       $this->future_entries = $config->getDefinedValue('future_entries');
 
 139       $this->uncompleted_indicators = $config->getDefinedValue('uncompleted_indicators');
 
 140       if ($this->isPluginEnabled('wu')) {
 
 141         $minutes_in_unit = $config->getIntValue('minutes_in_unit');
 
 142         if ($minutes_in_unit) $this->minutes_in_unit = $minutes_in_unit;
 
 143         $first_unit_threshold = $config->getIntValue('1st_unit_threshold');
 
 144         if ($first_unit_threshold) $this->first_unit_threshold = $first_unit_threshold;
 
 145         $this->unit_totals_only = $config->getDefinedValue('unit_totals_only');
 
 148       // Set "on behalf" id and name (user).
 
 149       if (isset($_SESSION['behalf_id'])) {
 
 150           $this->behalf_id = $_SESSION['behalf_id'];
 
 151           $this->behalf_name = $_SESSION['behalf_name'];
 
 153       // Set "on behalf" id and name (group).
 
 154       if (isset($_SESSION['behalf_group_id'])) {
 
 155           $this->behalf_group_id = $_SESSION['behalf_group_id'];
 
 156           $this->behalf_group = $_SESSION['behalf_group'];
 
 161   // The getActiveUser returns user id on behalf of whom the current user is operating.
 
 162   function getActiveUser() {
 
 163     return ($this->behalf_id ? $this->behalf_id : $this->id);
 
 166   // The getActiveGroup returns group id on behalf of which the current user is operating.
 
 167   function getActiveGroup() {
 
 168     return ($this->behalf_group_id ? $this->behalf_group_id : $this->group_id);
 
 171   // can - determines whether user has a right to do something.
 
 172   function can($do_something) {
 
 173     return in_array($do_something, $this->rights);
 
 176   // isClient - determines whether current user is a client.
 
 177   function isClient() {
 
 178     return $this->is_client;
 
 181   // isPluginEnabled checks whether a plugin is enabled for user.
 
 182   function isPluginEnabled($plugin)
 
 184     return in_array($plugin, explode(',', $this->plugins));
 
 187   // getAssignedProjects - returns an array of assigned projects.
 
 188   function getAssignedProjects()
 
 191     $mdb2 = getConnection();
 
 193     // Do a query with inner join to get assigned projects.
 
 194     $sql = "select p.id, p.name, p.description, p.tasks, upb.rate from tt_projects p
 
 195       inner join tt_user_project_binds upb on (upb.user_id = ".$this->getActiveUser()." and upb.project_id = p.id and upb.status = 1)
 
 196       where p.group_id = $this->group_id and p.status = 1 order by p.name";
 
 197     $res = $mdb2->query($sql);
 
 198     if (!is_a($res, 'PEAR_Error')) {
 
 199       while ($val = $res->fetchRow()) {
 
 206   // getAssignedTasks - returns an array of assigned tasks.
 
 207   function getAssignedTasks()
 
 209     // Start with projects;
 
 210     $projects = $this->getAssignedProjects();
 
 211     if (!$projects) return false;
 
 213     // Build an array of task ids.
 
 215     foreach($projects as $project) {
 
 216       $one_project_tasks = $project['tasks'] ? explode(',', $project['tasks']) : array();
 
 217       $task_ids = array_unique(array_merge($task_ids, $one_project_tasks));
 
 219     if (!$task_ids) return false;
 
 221     // Get task descriptions.
 
 223     $mdb2 = getConnection();
 
 224     $tasks = implode(',', $task_ids); // This is a comma-separated list of task ids.
 
 226     $sql = "select id, name, description from tt_tasks".
 
 227       " where group_id = $this->group_id and status = 1 and id in ($tasks) order by name";
 
 228     $res = $mdb2->query($sql);
 
 229     if (!is_a($res, 'PEAR_Error')) {
 
 230       while ($val = $res->fetchRow()) {
 
 237   // getAssignedClients - returns an array of clients assigned to own projects.
 
 238   function getAssignedClients()
 
 240     // Start with projects;
 
 241     $projects = $this->getAssignedProjects();
 
 242     if (!$projects) return false;
 
 243     $assigned_project_ids = array();
 
 244     foreach($projects as $project) {
 
 245       $assigned_project_ids[] = $project['id'];
 
 248     $mdb2 = getConnection();
 
 250     // Get active clients for group.
 
 252     $sql = "select id, name, address, projects from tt_clients where group_id = $this->group_id and status = 1";
 
 253     $res = $mdb2->query($sql);
 
 254     if (!is_a($res, 'PEAR_Error')) {
 
 255       while ($val = $res->fetchRow()) {
 
 256         $client_project_ids = $val['projects'] ? explode(',', $val['projects']) : array();
 
 257         if (array_intersect($assigned_project_ids, $client_project_ids))
 
 258           $clients[] = $val; // Add client if one of user projects is a client project, too.
 
 264   // isDateLocked checks whether a specifc date is locked for modifications.
 
 265   function isDateLocked($date)
 
 267     if (!$this->isPluginEnabled('lk'))
 
 268       return false; // Locking feature is disabled.
 
 270     if (!$this->lock_spec)
 
 271       return false; // There is no lock specification.
 
 273     if (!$this->behalf_id && $this->can('override_own_date_lock'))
 
 274       return false; // User is working as self and can override own date lock.
 
 276     if ($this->behalf_id && $this->can('override_date_lock'))
 
 277       return false; // User is working on behalf of someone else and can override date lock.
 
 279     require_once(LIBRARY_DIR.'/tdcron/class.tdcron.php');
 
 280     require_once(LIBRARY_DIR.'/tdcron/class.tdcron.entry.php');
 
 282     // Calculate the last occurrence of a lock.
 
 283     $last = tdCron::getLastOccurrence($this->lock_spec, time());
 
 284     $lockdate = new DateAndTime(DB_DATEFORMAT, strftime('%Y-%m-%d', $last));
 
 285     if ($date->before($lockdate))
 
 291   // canOverridePunchMode checks whether a user can override punch mode in a situation.
 
 292   function canOverridePunchMode()
 
 294     if (!$this->behalf_id && !$this->can('override_own_punch_mode'))
 
 295       return false; // User is working as self and cannot override for self.
 
 297     if ($this->behalf_id && !$this->can('override_punch_mode'))
 
 298       return false; // User is working on behalf of someone else and cannot override.
 
 303   // getUsers obtains users in a group, as specififed by options.
 
 304   function getUsers($options) {
 
 306     $mdb2 = getConnection();
 
 308     $skipClients = !isset($options['include_clients']);
 
 309     $includeSelf = isset($options['include_self']);
 
 311     $select_part = 'select u.id, u.name';
 
 312     if (isset($options['include_login'])) $select_part .= ', u.login';
 
 313     if (!isset($options['include_clients'])) $select_part .= ', r.rights';
 
 314     if (isset($options['include_role'])) $select_part .= ', r.name as role_name, r.rank';
 
 316     $from_part = ' from tt_users u';
 
 319     if (isset($options['max_rank']) || $skipClients || isset($options['include_role']))
 
 320         $left_joins .= ' left join tt_roles r on (u.role_id = r.id)';
 
 322     $where_part = " where u.group_id = $this->group_id";
 
 323     if (isset($options['status']))
 
 324       $where_part .= ' and u.status = '.(int)$options['status'];
 
 326       $where_part .= ' and u.status is not null';
 
 328       $where_part .= " and (u.id = $this->id || r.rank <= ".(int)$options['max_rank'].')';
 
 330       if (isset($options['max_rank'])) $where_part .= ' and r.rank <= '.(int)$options['max_rank'];
 
 333     $order_part = " order by upper(u.name)";
 
 335     $sql = $select_part.$from_part.$left_joins.$where_part.$order_part;
 
 336     $res = $mdb2->query($sql);
 
 337     $user_list = array();
 
 338     if (is_a($res, 'PEAR_Error'))
 
 341     while ($val = $res->fetchRow()) {
 
 343         $isClient = in_array('track_own_time', explode(',', $val['rights'])) ? 0 : 1; // Clients do not have track_own_time right.
 
 345           continue; // Skip adding clients.
 
 350     if (isset($options['self_first'])) {
 
 351       // Put own entry at the front.
 
 352       $cnt = count($user_list);
 
 353       for($i = 0; $i < $cnt; $i++) {
 
 354         if ($user_list[$i]['id'] == $this->id) {
 
 355           $self = $user_list[$i]; // Found self.
 
 356           array_unshift($user_list, $self); // Put own entry at the front.
 
 357           array_splice($user_list, $i+1, 1); // Remove duplicate.
 
 364   // getUser function is used to manage users in group and returns user details.
 
 365   // At the moment, the function is used for user edits and deletes.
 
 366   function getUser($user_id) {
 
 367     if (!$this->can('manage_users')) return false;
 
 369     $mdb2 = getConnection();
 
 371     $sql =  "select u.id, u.name, u.login, u.role_id, u.client_id, u.status, u.rate, u.email from tt_users u".
 
 372             " left join tt_roles r on (u.role_id = r.id)".
 
 373             " where u.id = $user_id and u.group_id = $this->group_id and u.status is not null".
 
 374             " and (r.rank < $this->rank or (r.rank = $this->rank and u.id = $this->id))"; // Users with lesser roles or self.
 
 375     $res = $mdb2->query($sql);
 
 376     if (!is_a($res, 'PEAR_Error')) {
 
 377       $val = $res->fetchRow();
 
 383   // checkBehalfId checks whether behalf_id is appropriate.
 
 384   // On behalf user must be active and have lower rank.
 
 385   function checkBehalfId() {
 
 386     $options = array('status'=>ACTIVE,'max_rank'=>$this->rank-1);
 
 387     $users = $this->getUsers($options);
 
 388     foreach($users as $one_user) {
 
 389       if ($one_user['id'] == $this->behalf_id)
 
 395   // adjustBehalfId attempts to adjust behalf_id and behalf_name to a first found
 
 398   // Needed for situations when user does not have do_own_something right.
 
 399   // Example: has view_charts but does not have view_own_charts.
 
 400   // In this case we still allow access to charts, but set behalf_id to someone else.
 
 401   function adjustBehalfId() {
 
 402     $options = array('status'=>ACTIVE,'max_rank'=>$this->rank-1);
 
 403     $users = $this->getUsers($options);
 
 404     foreach($users as $one_user) {
 
 405       // Fake loop to access first element.
 
 406       $this->behalf_id = $one_user['id'];
 
 407       $this->behalf_name = $one_user['name'];
 
 408       $_SESSION['behalf_id'] = $this->behalf_id;
 
 409       $_SESSION['behalf_name'] = $this->behalf_name;
 
 415   // updateGroup updates group information with new data.
 
 416   function updateGroup($fields) {
 
 417     if (!($this->can('manage_basic_settings') ||
 
 418       $this->can('manage_advanced_settings') ||
 
 419       $this->can('manage_features'))) return false;
 
 421     $mdb2 = getConnection();
 
 423     if (isset($fields['name'])) $name_part = ', name = '.$mdb2->quote($fields['name']);
 
 424     if (isset($fields['currency'])) $currency_part = ', currency = '.$mdb2->quote($fields['currency']);
 
 425     if (isset($fields['lang'])) $lang_part = ', lang = '.$mdb2->quote($fields['lang']);
 
 426     if (isset($fields['decimal_mark'])) $decimal_mark_part = ', decimal_mark = '.$mdb2->quote($fields['decimal_mark']);
 
 427     if (isset($fields['date_format'])) $date_format_part = ', date_format = '.$mdb2->quote($fields['date_format']);
 
 428     if (isset($fields['time_format'])) $time_format_part = ', time_format = '.$mdb2->quote($fields['time_format']);
 
 429     if (isset($fields['week_start'])) $week_start_part = ', week_start = '.(int) $fields['week_start'];
 
 430     if (isset($fields['tracking_mode'])) {
 
 431       $tracking_mode_part = ', tracking_mode = '.(int) $fields['tracking_mode'];
 
 432       $project_required_part = ' , project_required = '.(int) $fields['project_required'];
 
 433       $task_required_part = ' , task_required = '.(int) $fields['task_required'];
 
 435     if (isset($fields['record_type'])) $record_type_part = ', record_type = '.(int) $fields['record_type'];
 
 436     if (isset($fields['bcc_email'])) $bcc_email_part = ', bcc_email = '.$mdb2->quote($fields['bcc_email']);
 
 437     if (isset($fields['allow_ip'])) $allow_ip_part = ', allow_ip = '.$mdb2->quote($fields['allow_ip']);
 
 438     if (isset($fields['plugins'])) $plugins_part = ', plugins = '.$mdb2->quote($fields['plugins']);
 
 439     if (isset($fields['config'])) $config_part = ', config = '.$mdb2->quote($fields['config']);
 
 440     if (isset($fields['lock_spec'])) $lock_spec_part = ', lock_spec = '.$mdb2->quote($fields['lock_spec']);
 
 441     if (isset($fields['workday_minutes'])) $workday_minutes_part = ', workday_minutes = '.$mdb2->quote($fields['workday_minutes']);
 
 442     $modified_part = ', modified = now(), modified_ip = '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', modified_by = '.$mdb2->quote($this->id);
 
 444     $parts = trim($name_part.$currency_part.$lang_part.$decimal_mark_part.$date_format_part.
 
 445       $time_format_part.$week_start_part.$tracking_mode_part.$task_required_part.$project_required_part.$record_type_part.
 
 446       $bcc_email_part.$allow_ip_part.$plugins_part.$config_part.$lock_spec_part.$workday_minutes_part.$modified_part, ',');
 
 448     $sql = "update tt_groups set $parts where id = $this->group_id";
 
 449     $affected = $mdb2->exec($sql);
 
 450     if (is_a($affected, 'PEAR_Error')) return false;
 
 455   // markUserDeleted marks a user in group as deleted.
 
 456   function markUserDeleted($user_id) {
 
 457     if (!$this->can('manage_users') || $this->id == $user_id)
 
 460     // Make sure we operate on a legit user.
 
 461     $user_details = $this->getUser($user_id);
 
 462     if (!$user_details) return false;
 
 464     $mdb2 = getConnection();
 
 466     // Mark user to project binds as deleted.
 
 467     $sql = "update tt_user_project_binds set status = NULL where user_id = $user_id";
 
 468     $affected = $mdb2->exec($sql);
 
 469     if (is_a($affected, 'PEAR_Error'))
 
 472     // Mark user favorite reports as deleted.
 
 473     $sql = "update tt_fav_reports set status = NULL where user_id = $user_id";
 
 474     $affected = $mdb2->exec($sql);
 
 475     if (is_a($affected, 'PEAR_Error'))
 
 478     // Mark user as deleted.
 
 479     $sql = "update tt_users set status = NULL where id = $user_id and group_id = ".$this->group_id;
 
 480     $affected = $mdb2->exec($sql);
 
 481     if (is_a($affected, 'PEAR_Error'))
 
 487   // enablePlugin either enables or disables a specific plugin for group.
 
 488   function enablePlugin($plugin, $enable = true)
 
 490     if (!$this->can('manage_advanced_settings'))
 
 491       return false; // Note: enablePlugin is currently only used on week_view.php.
 
 492                     // So, it's not really a plugin we are enabling, but rather week view display options.
 
 493                     // Therefore, a check for manage_advanced_settings, not manage_features.
 
 495     $plugin_array = explode(',', $this->plugins);
 
 496     if ($enable && !in_array($plugin, $plugin_array))
 
 497       $plugin_array[] = $plugin; // Add plugin to array.
 
 499     if (!$enable && in_array($plugin, $plugin_array)) {
 
 500       $key = array_search($plugin, $plugin_array);
 
 502         unset($plugin_array[$key]); // Remove plugin from array.
 
 505     $plugins = implode(',', $plugin_array);
 
 506     if ($plugins != $this->plugins) {
 
 507       if (!$this->updateGroup(array('plugins' => $plugins)))
 
 509       $this->plugins = $plugins;