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');
 
  30 import('ttGroupHelper');
 
  31 import('ttBehalfUser');
 
  34 import('form.ActionForm');
 
  37   var $login = null;            // User login.
 
  38   var $name = null;             // User name.
 
  39   var $id = null;               // User id.
 
  40   var $org_id = null;           // Organization id.
 
  41   var $group_id = null;         // Group id.
 
  42   var $role_id = null;          // Role id.
 
  43   var $role_name = null;        // Role name.
 
  44   var $rank = null;             // User role rank.
 
  45   var $client_id = null;        // Client id for client user role.
 
  46   var $quota_percent = 100.0;   // Time quota percent for quotas plugin.
 
  47   var $behalf_id = null;        // User id, on behalf of whom we are working.
 
  48   var $behalf_group_id = null;  // Group id, on behalf of which we are working.
 
  49   var $behalf_name = null;      // User name, on behalf of whom we are working.
 
  50   var $group_name = null;       // Group name.
 
  51   var $behalf_group_name = null;// Group name, on behalf of which we are working.
 
  52   var $email = null;            // User email.
 
  53   var $lang = null;             // Language.
 
  54   var $decimal_mark = null;     // Decimal separator.
 
  55   var $date_format = null;      // Date format.
 
  56   var $time_format = null;      // Time format.
 
  57   var $week_start = 0;          // Week start day.
 
  58   var $tracking_mode = 0;       // Tracking mode.
 
  59   var $project_required = 0;    // Whether project selection is required on time entires.
 
  60   var $task_required = 0;       // Whether task selection is required on time entires.
 
  61   var $record_type = 0;         // Record type (duration vs start and finish, or both).
 
  62   var $punch_mode = 0;          // Whether punch mode is enabled for user.
 
  63   var $allow_overlap = 0;       // Whether to allow overlapping time entries.
 
  64   var $future_entries = 0;      // Whether to allow creating future entries.
 
  65   var $bcc_email = null;        // Bcc email.
 
  66   var $allow_ip = null;         // Specification from where user is allowed access.
 
  67   var $password_complexity = null; // Password complexity example.
 
  68   var $currency = null;         // Currency.
 
  69   var $plugins = null;          // Comma-separated list of enabled plugins.
 
  71   // Refactoring ongoing. Towards using helper instead of config string?
 
  72   var $config = null;           // Comma-separated list of miscellaneous config options.
 
  73   var $configHelper = null;     // An instance of ttConfigHelper class.
 
  75   var $custom_logo = 0;         // Whether to use a custom logo for group.
 
  76   var $lock_spec = null;        // Cron specification for record locking.
 
  77   var $holidays = null;         // Holidays specification.
 
  78   var $workday_minutes = 480;   // Number of work minutes in a regular day.
 
  79   var $rights = array();        // An array of user rights such as 'track_own_time', etc.
 
  80   var $is_client = false;       // Whether user is a client as determined by missing 'track_own_time' right.
 
  82   var $behalfUser = null;       // A ttBehalfUser instance with on behalf user attributes.
 
  83   var $behalfGroup = null;      // A ttGroup instance with on behalf group attributes.
 
  86   function __construct($login, $id = null) {
 
  87     if (!$login && !$id) {
 
  88       // nothing to initialize
 
  92     $mdb2 = getConnection();
 
  94     $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,".
 
  95       " u.quota_percent, u.email, g.org_id, g.name as group_name, g.currency, g.lang, g.decimal_mark, g.date_format,".
 
  96       " g.time_format, g.week_start, g.tracking_mode, g.project_required, g.task_required, g.record_type,".
 
  97       " g.bcc_email, g.allow_ip, g.password_complexity, g.plugins, g.config, g.lock_spec, g.holidays, g.workday_minutes, g.custom_logo".
 
  98       " 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 ";
 
 100       $sql .= "u.id = $id";
 
 102       $sql .= "u.login = ".$mdb2->quote($login);
 
 103     $sql .= " AND u.status = 1";
 
 105     $res = $mdb2->query($sql);
 
 106     if (is_a($res, 'PEAR_Error')) {
 
 110     $val = $res->fetchRow();
 
 111     if ($val['id'] > 0) {
 
 112       $this->login = $val['login'];
 
 113       $this->name = $val['name'];
 
 114       $this->id = $val['id'];
 
 115       $this->org_id = $val['org_id'];
 
 116       $this->group_id = $val['group_id'];
 
 117       $this->role_id = $val['role_id'];
 
 118       $this->role_name = $val['role_name'];
 
 119       $this->rights = explode(',', $val['rights']);
 
 120       $this->rank = $val['rank'];
 
 121       $this->client_id = $val['client_id'];
 
 122       $this->is_client = $this->client_id && !in_array('track_own_time', $this->rights);
 
 123       if ($val['quota_percent']) $this->quota_percent = $val['quota_percent'];
 
 124       $this->email = $val['email'];
 
 125       $this->lang = $val['lang'];
 
 126       $this->decimal_mark = $val['decimal_mark'];
 
 127       $this->date_format = $val['date_format'];
 
 128       $this->time_format = $val['time_format'];
 
 129       $this->week_start = $val['week_start'];
 
 130       $this->tracking_mode = $val['tracking_mode'];
 
 131       $this->project_required = $val['project_required'];
 
 132       $this->task_required = $val['task_required'];
 
 133       $this->record_type = $val['record_type'];
 
 134       $this->bcc_email = $val['bcc_email'];
 
 135       $this->allow_ip = $val['allow_ip'];
 
 136       $this->password_complexity = $val['password_complexity'];
 
 137       $this->group_name = $val['group_name'];
 
 138       $this->currency = $val['currency'];
 
 139       $this->plugins = $val['plugins'];
 
 140       $this->lock_spec = $val['lock_spec'];
 
 141       $this->holidays = $val['holidays'];
 
 142       $this->workday_minutes = $val['workday_minutes'];
 
 143       $this->custom_logo = $val['custom_logo'];
 
 145       // TODO: refactor this.
 
 146       $this->config = $val['config'];
 
 147       $this->configHelper = new ttConfigHelper($val['config']);
 
 149       // Set user config options.
 
 150       $this->punch_mode = $this->configHelper->getDefinedValue('punch_mode');
 
 151       $this->allow_overlap = $this->configHelper->getDefinedValue('allow_overlap');
 
 152       $this->future_entries = $this->configHelper->getDefinedValue('future_entries');
 
 154       // Set "on behalf" id and name (user).
 
 155       if (isset($_SESSION['behalf_id'])) {
 
 156         $this->behalf_id = $_SESSION['behalf_id'];
 
 157         $this->behalf_name = $_SESSION['behalf_name'];
 
 159         $this->behalfUser = new ttBehalfUser($this->behalf_id, $this->org_id);
 
 161       // Set "on behalf" id and name (group).
 
 162       if (isset($_SESSION['behalf_group_id'])) {
 
 163         $this->behalf_group_id = $_SESSION['behalf_group_id'];
 
 164         $this->behalf_group_name = $_SESSION['behalf_group_name'];
 
 166         $this->behalfGroup = new ttGroup($this->behalf_group_id, $this->org_id);
 
 171   // getUser returns user id on behalf of whom the current user is operating.
 
 173     return ($this->behalfUser ? $this->behalfUser->id : $this->id);
 
 176   // getName returns user name on behalf of whom the current user is operating.
 
 178     return ($this->behalfUser ? $this->behalfUser->name : $this->name);
 
 181   // getQuotaPercent returns quota percent for active user.
 
 182   function getQuotaPercent() {
 
 183     return ($this->behalfUser ? $this->behalfUser->quota_percent : $this->quota_percent);
 
 186   // The getGroup returns group id on behalf of which the current user is operating.
 
 187   function getGroup() {
 
 188     return ($this->behalfGroup ? $this->behalfGroup->id : $this->group_id);
 
 191   // getDecimalMark returns decimal mark for active group.
 
 192   function getDecimalMark() {
 
 193     return ($this->behalfGroup ? $this->behalfGroup->decimal_mark : $this->decimal_mark);
 
 196   // getDateFormat returns date format for active group.
 
 197   function getDateFormat() {
 
 198     return ($this->behalfGroup ? $this->behalfGroup->date_format : $this->date_format);
 
 201   // getTimeFormat returns time format for active group.
 
 202   function getTimeFormat() {
 
 203     return ($this->behalfGroup ? $this->behalfGroup->time_format : $this->time_format);
 
 206   // getWeekStart returns week start day for active group.
 
 207   function getWeekStart() {
 
 208     return ($this->behalfGroup ? $this->behalfGroup->week_start : $this->week_start);
 
 211   // getTrackingMode returns tracking mode for active group.
 
 212   function getTrackingMode() {
 
 213     return ($this->behalfGroup ? $this->behalfGroup->tracking_mode : $this->tracking_mode);
 
 216   // getRecordType returns record type for active group.
 
 217   function getRecordType() {
 
 218     return ($this->behalfGroup ? $this->behalfGroup->record_type : $this->record_type);
 
 221   // getCurrency returns currency string for active group.
 
 222   function getCurrency() {
 
 223     return ($this->behalfGroup ? $this->behalfGroup->currency : $this->currency);
 
 226   // getPlugins returns plugins string for active group.
 
 227   function getPlugins() {
 
 228     return ($this->behalfGroup ? $this->behalfGroup->plugins : $this->plugins);
 
 231   // getLockSpec returns lock specification for active group.
 
 232   function getLockSpec() {
 
 233     return ($this->behalfGroup ? $this->behalfGroup->lock_spec : $this->lock_spec);
 
 236   // getHolidays returns holidays specification for active group.
 
 237   function getHolidays() {
 
 238     return ($this->behalfGroup ? $this->behalfGroup->holidays : $this->holidays);
 
 241   // getWorkdayMinutes returns workday_minutes for active group.
 
 242   function getWorkdayMinutes() {
 
 243     return ($this->behalfGroup ? $this->behalfGroup->workday_minutes : $this->workday_minutes);
 
 246   // getConfig returns config string for active group.
 
 247   function getConfig() {
 
 248     return ($this->behalfGroup ? $this->behalfGroup->configHelper->getConfig() : $this->configHelper->getConfig());
 
 251   // getConfigHelper returns ttConfigHelper instance for active group.
 
 252   function getConfigHelper() {
 
 253     return ($this->behalfGroup ? $this->behalfGroup->configHelper : $this->configHelper);
 
 256   // getConfigOption returns true if an option is defined for group.
 
 257   // This helps us keeping a set of user attributes smaller.
 
 258   // We determine whether the option is set only on pages that need to know.
 
 259   // For example: confirm_save is used only on time and expense edit pages.
 
 260   function getConfigOption($name) {
 
 261     $config = new ttConfigHelper($this->getConfig());
 
 262     return $config->getDefinedValue($name);
 
 265   // getConfigInt retruns an integer value defined in a group, or false.
 
 266   function getConfigInt($name, $defaultVal) {
 
 267     $config = new ttConfigHelper($this->getConfig());
 
 268     return $config->getIntValue($name, $defaultVal);
 
 271   // can - determines whether user has a right to do something.
 
 272   function can($do_something) {
 
 273     return in_array($do_something, $this->rights);
 
 276   // isClient - determines whether current user is a client.
 
 277   function isClient() {
 
 278     return $this->is_client;
 
 281   // isPluginEnabled checks whether a plugin is enabled for user.
 
 282   function isPluginEnabled($plugin)
 
 284     return in_array($plugin, explode(',', $this->getPlugins()));
 
 287   // isOptionEnabled checks whether a config option is enabled for user.
 
 288   function isOptionEnabled($option)
 
 290     return $this->behalfGroup ? $this->behalfGroup->configHelper->getDefinedValue($option) : $this->configHelper->getDefinedValue($option);
 
 293   // setOption sets an option inside of ttConfigHelper instance.
 
 294   // Note that it does not write to the database.
 
 295   function setOption($option, $enable = true)
 
 297     return $this->behalfGroup ? $this->behalfGroup->configHelper->setDefinedValue($option, $enable) : $this->configHelper->setDefinedValue($option, $enable);
 
 300   // getAssignedProjects - returns an array of assigned projects.
 
 301   function getAssignedProjects($includeFiles = false)
 
 304     $mdb2 = getConnection();
 
 306     $user_id = $this->getUser();
 
 307     $group_id = $this->getGroup();
 
 308     $org_id = $this->org_id;
 
 311       $filePart = ', if(Sub1.entity_id is null, 0, 1) as has_files';
 
 312       $fileJoin =  " left join (select distinct entity_id from tt_files".
 
 313       " where entity_type = 'project' and group_id = $group_id and org_id = $org_id and status = 1) Sub1".
 
 314       " on (p.id = Sub1.entity_id)";
 
 317     // Do a query with inner join to get assigned projects.
 
 318     $sql = "select p.id, p.name, p.description, p.tasks, upb.rate $filePart from tt_projects p $fileJoin".
 
 319       " inner join tt_user_project_binds upb on (upb.user_id = $user_id and upb.project_id = p.id and upb.status = 1)".
 
 320       " where p.group_id = $group_id and p.org_id = $org_id and p.status = 1 order by p.name";
 
 321     $res = $mdb2->query($sql);
 
 322     if (!is_a($res, 'PEAR_Error')) {
 
 323       while ($val = $res->fetchRow()) {
 
 330   // getAssignedTasks - returns an array of assigned tasks.
 
 331   function getAssignedTasks()
 
 333     // Start with projects;
 
 334     $projects = $this->getAssignedProjects();
 
 335     if (!$projects) return false;
 
 337     // Build an array of task ids.
 
 339     foreach($projects as $project) {
 
 340       $one_project_tasks = $project['tasks'] ? explode(',', $project['tasks']) : array();
 
 341       $task_ids = array_unique(array_merge($task_ids, $one_project_tasks));
 
 343     if (!$task_ids) return false;
 
 345     // Get task descriptions.
 
 347     $mdb2 = getConnection();
 
 348     $tasks = implode(',', $task_ids); // This is a comma-separated list of task ids.
 
 350     $group_id = $this->getGroup();
 
 351     $org_id = $this->org_id;
 
 353     $sql = "select id, name, description from tt_tasks".
 
 354       " where group_id = $group_id and org_id = $org_id and status = 1 and id in ($tasks) order by name";
 
 355     $res = $mdb2->query($sql);
 
 356     if (!is_a($res, 'PEAR_Error')) {
 
 357       while ($val = $res->fetchRow()) {
 
 364   // getAssignedClients - returns an array of clients assigned to own projects.
 
 365   function getAssignedClients()
 
 367     // Start with projects;
 
 368     $projects = $this->getAssignedProjects();
 
 369     if (!$projects) return false;
 
 370     $assigned_project_ids = array();
 
 371     foreach($projects as $project) {
 
 372       $assigned_project_ids[] = $project['id'];
 
 375     $mdb2 = getConnection();
 
 377     $group_id = $this->getGroup();
 
 378     $org_id = $this->org_id;
 
 380     // Get active clients for group.
 
 382     $sql = "select id, name, address, projects from tt_clients where group_id = $group_id and org_id = $org_id and status = 1";
 
 383     $res = $mdb2->query($sql);
 
 384     if (!is_a($res, 'PEAR_Error')) {
 
 385       while ($val = $res->fetchRow()) {
 
 386         $client_project_ids = $val['projects'] ? explode(',', $val['projects']) : array();
 
 387         if (array_intersect($assigned_project_ids, $client_project_ids))
 
 388           $clients[] = $val; // Add client if one of user projects is a client project, too.
 
 394   // isDateLocked checks whether a specifc date is locked for modifications.
 
 395   function isDateLocked($date)
 
 397     if (!$this->isPluginEnabled('lk'))
 
 398       return false; // Locking feature is disabled.
 
 400     if (!$this->getLockSpec())
 
 401       return false; // There is no lock specification.
 
 403     if (!$this->behalf_id && $this->can('override_own_date_lock'))
 
 404       return false; // User is working as self and can override own date lock.
 
 406     if ($this->behalf_id && $this->can('override_date_lock'))
 
 407       return false; // User is working on behalf of someone else and can override date lock.
 
 409     require_once(LIBRARY_DIR.'/tdcron/class.tdcron.php');
 
 410     require_once(LIBRARY_DIR.'/tdcron/class.tdcron.entry.php');
 
 412     // Calculate the last occurrence of a lock.
 
 413     $last = tdCron::getLastOccurrence($this->getLockSpec(), time());
 
 414     $lockdate = new DateAndTime(DB_DATEFORMAT, strftime('%Y-%m-%d', $last));
 
 415     if ($date->before($lockdate))
 
 421   // canOverridePunchMode checks whether a user can override punch mode in a situation.
 
 422   function canOverridePunchMode()
 
 424     if (!$this->behalf_id && !$this->can('override_own_punch_mode'))
 
 425       return false; // User is working as self and cannot override for self.
 
 427     if ($this->behalf_id && !$this->can('override_punch_mode'))
 
 428       return false; // User is working on behalf of someone else and cannot override.
 
 433   // getUsers obtains users in a group, as specififed by options.
 
 434   function getUsers($options) {
 
 435     $mdb2 = getConnection();
 
 437     $group_id = $this->getGroup();
 
 438     $org_id = $this->org_id;
 
 440     $skipClients = !isset($options['include_clients']);
 
 441     $includeSelf = isset($options['include_self']);
 
 443     $select_part = 'select u.id, u.group_id, u.name';
 
 444     if (isset($options['include_login'])) {
 
 445       $select_part .= ', u.login';
 
 446       // Piggy-back on include_login to see if we must also include quota_percent.
 
 447       $include_quota = $this->isPluginEnabled('mq');
 
 448       if ($include_quota) {
 
 449         $decimal_mark = $this->getDecimalMark();
 
 450         $replaceDecimalMark = ('.' != $decimal_mark);
 
 451         $select_part .= ', u.quota_percent';
 
 454     if (!isset($options['include_clients'])) $select_part .= ', r.rights';
 
 455     if (isset($options['include_role'])) $select_part .= ', r.name as role_name, r.rank';
 
 457     $from_part = ' from tt_users u';
 
 460     if (isset($options['max_rank']) || $skipClients || isset($options['include_role']))
 
 461       $left_joins .= ' left join tt_roles r on (u.role_id = r.id)';
 
 463     $where_part = " where u.org_id = $org_id and u.group_id = $group_id";
 
 464     if (isset($options['status']))
 
 465       $where_part .= ' and u.status = '.(int)$options['status'];
 
 467       $where_part .= ' and u.status is not null';
 
 469       $where_part .= " and (u.id = $this->id || r.rank <= ".(int)$options['max_rank'].')';
 
 471       if (isset($options['max_rank'])) $where_part .= ' and r.rank <= '.(int)$options['max_rank'];
 
 474     $order_part = " order by upper(u.name)";
 
 476     $sql = $select_part.$from_part.$left_joins.$where_part.$order_part;
 
 477     $res = $mdb2->query($sql);
 
 478     $user_list = array();
 
 479     if (is_a($res, 'PEAR_Error'))
 
 482     while ($val = $res->fetchRow()) {
 
 484         $isClient = in_array('track_own_time', explode(',', $val['rights'])) ? 0 : 1; // Clients do not have track_own_time right.
 
 486           continue; // Skip adding clients.
 
 488       if ($include_quota) {
 
 489         $quota = $val['quota_percent'];
 
 490         if (ttEndsWith($quota, '.00'))
 
 491           $quota = substr($quota, 0, strlen($quota)-3); // Trim trailing ".00";
 
 492         elseif ($replaceDecimalMark)
 
 493           $quota = str_replace('.', $decimal_mark, $quota);
 
 494         $val['quota_percent'] = $quota.'%';
 
 499     if (isset($options['self_first'])) {
 
 500       // Put own entry at the front.
 
 501       $cnt = count($user_list);
 
 502       for($i = 0; $i < $cnt; $i++) {
 
 503         if ($user_list[$i]['id'] == $this->id) {
 
 504           $self = $user_list[$i]; // Found self.
 
 505           array_unshift($user_list, $self); // Put own entry at the front.
 
 506           array_splice($user_list, $i+1, 1); // Remove duplicate.
 
 513   // getGroupsForDropdown obtains an array of groups to populate the "Group" dropdown.
 
 514   // It consists of the entire tree starting from user home group.
 
 515   // Group name is prefixed with additional characters to indicate subgroups level.
 
 516   function getGroupsForDropdown() {
 
 519     // Start with user home group.
 
 522     $group_id = $user->group_id;
 
 524     $this->addGroupToDropdown($groups, $group_id, $subgroup_level);
 
 528   // addGroupToDropdown is a recursive function to populate a tree of groups, used with getGroupsForDropdown().
 
 529   function addGroupToDropdown(&$groups, $group_id, $subgroup_level) {
 
 530     // Add indentation markup to indicate subdirectory level.
 
 531     for ($i = 0; $i < $subgroup_level; $i++) {
 
 532       $name .= '🛑'; // Unicode stop sign.
 
 534     if ($subgroup_level) $name .= ' '; // Add an extra space.
 
 535     $name .= ttGroupHelper::getGroupName($group_id);
 
 537     $groups[] = array('id'=>$group_id, 'name'=>$name);
 
 539     $subgroups = $this->getSubgroups($group_id);
 
 540     foreach($subgroups as $subgroup) {
 
 541       $this->addGroupToDropdown($groups, $subgroup['id'], $subgroup_level+1);
 
 545   // getSubgroups obtains a list of immediate subgroups.
 
 546   function getSubgroups($group_id = null) {
 
 547     $mdb2 = getConnection();
 
 549     if (!$group_id) $group_id = $this->getGroup();
 
 551     $sql = "select id, name, description from tt_groups where org_id = $this->org_id".
 
 552       " and parent_id = $group_id and status is not null order by upper(name)";
 
 553     $res = $mdb2->query($sql);
 
 554     if (!is_a($res, 'PEAR_Error')) {
 
 555       while ($val = $res->fetchRow()) {
 
 562   // getUserDetails function is used to manage users in group and returns user details.
 
 563   // At the moment, the function is used for user edits and deletes.
 
 564   function getUserDetails($user_id) {
 
 565     if (!$this->can('manage_users')) return false;
 
 567     $mdb2 = getConnection();
 
 568     $group_id = $this->getGroup();
 
 569     $org_id = $this->org_id;
 
 571     // Determine max rank. If we are searching in on behalf group
 
 572     // then rank restriction does not apply.
 
 573     $max_rank = $this->behalfGroup ? MAX_RANK : $this->rank;
 
 575     $sql =  "select u.id, u.name, u.login, u.role_id, u.client_id, u.status, u.rate, u.quota_percent, u.email from tt_users u".
 
 576       " left join tt_roles r on (u.role_id = r.id)".
 
 577       " where u.id = $user_id and u.group_id = $group_id and u.org_id = $org_id and u.status is not null".
 
 578       " and (r.rank < $max_rank or (r.rank = $max_rank and u.id = $this->id))"; // Users with lesser roles or self.
 
 579     $res = $mdb2->query($sql);
 
 580     if (!is_a($res, 'PEAR_Error')) {
 
 581       $val = $res->fetchRow();
 
 587   // checkBehalfId checks whether behalf_id is appropriate.
 
 588   // On behalf user must be active and have lower rank if the user is from home group,
 
 590   // - subgroup must ve valid;
 
 591   // - user should be a member of it.
 
 592   function checkBehalfId() {
 
 593     if (!$this->behalfGroup) {
 
 594       // Checking user from home group.
 
 595       $options = array('status'=>ACTIVE,'max_rank'=>$this->rank-1);
 
 596       $users = $this->getUsers($options);
 
 597       foreach($users as $one_user) {
 
 598         if ($one_user['id'] == $this->behalf_id)
 
 602       // Checking user from a subgroup.
 
 603       $group_id = $this->behalfGroup->id;
 
 604       if (!$this->isSubgroupValid($group_id))
 
 607       // So far, so good. Check user now.
 
 608       $options = array('status'=>ACTIVE,'max_rank'=>MAX_RANK);
 
 609       $users = $this->getUsers($options);
 
 610       foreach($users as $one_user) {
 
 611         if ($one_user['id'] == $this->behalf_id)
 
 618   // adjustBehalfId attempts to adjust behalf_id and behalf_name to a first found
 
 621   // Needed for situations when user does not have do_own_something right.
 
 622   // Example: has view_charts but does not have view_own_charts.
 
 623   // In this case we still allow access to charts, but set behalf_id to someone else.
 
 624   // Another example: working in a subgroup on behalf of someone else.
 
 625   function adjustBehalfId() {
 
 626     $rank = $this->getMaxRankForGroup($this->getGroup());
 
 628     // Adjust to first found user in group.
 
 629     $options = array('status'=>ACTIVE,'max_rank'=>$rank);
 
 630     $users = $this->getUsers($options);
 
 631     foreach($users as $one_user) {
 
 632       // Fake loop to access first element.
 
 633       $this->behalf_id = $one_user['id'];
 
 634       $this->behalf_name = $one_user['name'];
 
 635       $_SESSION['behalf_id'] = $this->behalf_id;
 
 636       $_SESSION['behalf_name'] = $this->behalf_name;
 
 642   // updateGroup updates group information with new data.
 
 643   function updateGroup($fields) {
 
 644     $mdb2 = getConnection();
 
 646     $group_id = $fields['group_id'];
 
 647     if ($group_id && !$this->isGroupValid($group_id)) return false;
 
 648     if (!$group_id) $group_id = $this->getGroup();
 
 650     if (isset($fields['name'])) $name_part = ', name = '.$mdb2->quote($fields['name']);
 
 651     if (isset($fields['description'])) $description_part = ', description = '.$mdb2->quote($fields['description']);
 
 652     if (isset($fields['currency'])) $currency_part = ', currency = '.$mdb2->quote($fields['currency']);
 
 653     if (isset($fields['lang'])) $lang_part = ', lang = '.$mdb2->quote($fields['lang']);
 
 654     if (isset($fields['decimal_mark'])) $decimal_mark_part = ', decimal_mark = '.$mdb2->quote($fields['decimal_mark']);
 
 655     if (isset($fields['date_format'])) $date_format_part = ', date_format = '.$mdb2->quote($fields['date_format']);
 
 656     if (isset($fields['time_format'])) $time_format_part = ', time_format = '.$mdb2->quote($fields['time_format']);
 
 657     if (isset($fields['week_start'])) $week_start_part = ', week_start = '.(int) $fields['week_start'];
 
 658     if (isset($fields['tracking_mode'])) {
 
 659       $tracking_mode_part = ', tracking_mode = '.(int) $fields['tracking_mode'];
 
 660       $project_required_part = ' , project_required = '.(int) $fields['project_required'];
 
 661       $task_required_part = ' , task_required = '.(int) $fields['task_required'];
 
 663     if (isset($fields['record_type'])) $record_type_part = ', record_type = '.(int) $fields['record_type'];
 
 664     if (isset($fields['bcc_email'])) $bcc_email_part = ', bcc_email = '.$mdb2->quote($fields['bcc_email']);
 
 665     if (isset($fields['allow_ip'])) $allow_ip_part = ', allow_ip = '.$mdb2->quote($fields['allow_ip']);
 
 666     if (isset($fields['plugins'])) $plugins_part = ', plugins = '.$mdb2->quote($fields['plugins']);
 
 667     if (isset($fields['config'])) $config_part = ', config = '.$mdb2->quote($fields['config']);
 
 668     if (isset($fields['lock_spec'])) $lock_spec_part = ', lock_spec = '.$mdb2->quote($fields['lock_spec']);
 
 669     if (isset($fields['holidays'])) $holidays_part = ', holidays = '.$mdb2->quote($fields['holidays']);
 
 670     if (isset($fields['workday_minutes'])) $workday_minutes_part = ', workday_minutes = '.$mdb2->quote($fields['workday_minutes']);
 
 671     $modified_part = ', modified = now(), modified_ip = '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', modified_by = '.$mdb2->quote($this->id);
 
 673     $parts = trim($name_part.$description_part.$currency_part.$lang_part.$decimal_mark_part.$date_format_part.
 
 674       $time_format_part.$week_start_part.$tracking_mode_part.$task_required_part.$project_required_part.$record_type_part.
 
 675       $bcc_email_part.$allow_ip_part.$plugins_part.$config_part.$lock_spec_part.$holidays_part.$workday_minutes_part.$modified_part, ',');
 
 677     $sql = "update tt_groups set $parts where id = $group_id and org_id = $this->org_id";
 
 678     $affected = $mdb2->exec($sql);
 
 679     if (is_a($affected, 'PEAR_Error')) return false;
 
 684   // markUserDeleted marks a user in group as deleted.
 
 685   function markUserDeleted($user_id) {
 
 686     if (!$this->can('manage_users') || $this->id == $user_id)
 
 689     // Make sure we operate on a legit user.
 
 690     $user_details = $this->getUserDetails($user_id);
 
 691     if (!$user_details) return false;
 
 693     $mdb2 = getConnection();
 
 694     $group_id = $this->getGroup();
 
 695     $org_id = $this->org_id;
 
 697     // Mark user to project binds as deleted.
 
 698     $sql = "update tt_user_project_binds set status = NULL where user_id = $user_id".
 
 699       " and group_id = $group_id and org_id = $org_id";
 
 700     $affected = $mdb2->exec($sql);
 
 701     if (is_a($affected, 'PEAR_Error'))
 
 704     // Mark user favorite reports as deleted.
 
 705     $sql = "update tt_fav_reports set status = NULL where user_id = $user_id".
 
 706       " and group_id = $group_id and org_id = $org_id";
 
 707     $affected = $mdb2->exec($sql);
 
 708     if (is_a($affected, 'PEAR_Error'))
 
 711     // Mark user as deleted.
 
 712     $modified_part = ', modified = now(), modified_ip = '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', modified_by = '.$mdb2->quote($this->id);
 
 713     $sql = "update tt_users set status = null $modified_part where id = $user_id".
 
 714       " and group_id = $group_id and org_id = $org_id";
 
 715     $affected = $mdb2->exec($sql);
 
 716     if (is_a($affected, 'PEAR_Error'))
 
 722   // enablePlugin either enables or disables a specific plugin for group.
 
 723   function enablePlugin($plugin, $enable = true)
 
 725     if (!$this->can('manage_advanced_settings'))
 
 726       return false; // Note: enablePlugin is currently only used on week_view.php.
 
 727                     // So, it's not really a plugin we are enabling, but rather week view display options.
 
 728                     // Therefore, a check for manage_advanced_settings, not manage_features.
 
 730     $plugin_array = explode(',', $this->plugins);
 
 731     if ($enable && !in_array($plugin, $plugin_array))
 
 732       $plugin_array[] = $plugin; // Add plugin to array.
 
 734     if (!$enable && in_array($plugin, $plugin_array)) {
 
 735       $key = array_search($plugin, $plugin_array);
 
 737         unset($plugin_array[$key]); // Remove plugin from array.
 
 740     $plugins = implode(',', $plugin_array);
 
 741     if ($plugins != $this->plugins) {
 
 742       if (!$this->updateGroup(array('plugins' => $plugins)))
 
 744       $this->plugins = $plugins;
 
 750   // isUserValid determines if a user is valid for on behalf work.
 
 751   function isUserValid($user_id) {
 
 752     if ($user_id == $this->id)
 
 754     return ($this->getUserDetails($user_id) != null);
 
 757   // isGroupValid determines if a group is valid for user.
 
 758   function isGroupValid($group_id) {
 
 759     if ($group_id == $this->group_id)
 
 762       return $this->isSubgroupValid($group_id);
 
 765   // isSubgroupValid determines if a subgroup is valid for user.
 
 766   // A subgroup is valid if:
 
 767   //   - user can manage_subgroups;
 
 768   //   - subgroup is either a direct child of user group, or "on the path"
 
 769   //   to it (grand-child, etc.).
 
 770   function isSubgroupValid($subgroup_id) {
 
 771     if (!$this->can('manage_subgroups')) return false; // User cannot manage subgroups.
 
 773     $current_group_id = $subgroup_id;
 
 774     while ($parent_group_id = ttGroupHelper::getParentGroup($current_group_id)) {
 
 775       if ($parent_group_id == $this->group_id) {
 
 776         return true; // Found it.
 
 778       $current_group_id = $parent_group_id;
 
 783   // getMaxRankForGroup determines effective user rank for a user in a given group.
 
 784   // For home group it is the existing user rank (as per role) minus 1.
 
 785   // For subgroups, if user can "manage_subgroups", it is MAX_RANK.
 
 786   function getMaxRankForGroup($group_id) {
 
 788     $max_rank = 0; // Start safely.
 
 789     if ($this->group_id == $group_id) {
 
 790       $max_rank = $this->rank - 1;
 
 794     if ($this->isSubgroupValid($group_id))
 
 795       $max_rank = MAX_RANK;
 
 800   // getUserPartForHeader constructs a string for user to display on pages header.
 
 801   // It changes with "on behalf" attributes for both user and group.
 
 802   function getUserPartForHeader() {
 
 804     if (!$this->id) return null;
 
 806     $user_part = htmlspecialchars($this->name);
 
 807     $user_part .= ' - '.htmlspecialchars($this->role_name);
 
 808     if ($this->behalf_id) {
 
 809       $user_part .= ' <span class="onBehalf">'.$i18n->get('label.on_behalf').' '.htmlspecialchars($this->behalf_name).'</span>';
 
 811     if ($this->behalf_group_id) {
 
 812       $user_part .= ',  <span class="onBehalf">'.htmlspecialchars($this->behalf_group_name).'</span>';
 
 814       if ($this->group_name) // Note: we did not require group names in the past.
 
 815         $user_part .= ', '.$this->group_name;
 
 820   // setOnBehalfGroup sets on behalf group for the user in both the object and the session.
 
 821   function setOnBehalfGroup($group_id) {
 
 823     // Unset things first.
 
 824     $this->behalf_group_id = null;
 
 825     $this->behalf_group_name = null;
 
 826     $this->behalf_id = null;
 
 827     $this->behalf_name = null;
 
 828     unset($this->behalfGroup);
 
 829     unset($_SESSION['behalf_group_id']);
 
 830     unset($_SESSION['behalf_group_name']);
 
 831     unset($_SESSION['behalf_id']);
 
 832     unset($_SESSION['behalf_name']);
 
 834     // Destroy report bean if it was set in session.
 
 835     $form = new Form('dummyForm');
 
 836     $bean = new ActionForm('reportBean', $form, $request);
 
 837     if ($bean->isSaved()) {
 
 838       $bean->destroyBean();
 
 841     // Do not do anything if we don't have rights.
 
 842     if (!$this->can('manage_subgroups')) return;
 
 844     // No need to set if group is our home group.
 
 845     if ($group_id == $this->group_id) return;
 
 847     // No need to set if subgroup is not valid.
 
 848     if (!$this->isSubgroupValid($group_id)) return;
 
 850     // We are good to set on behalf group.
 
 851     $onBehalfGroupName = ttGroupHelper::getGroupName($group_id);
 
 852     $_SESSION['behalf_group_id'] = $group_id;
 
 853     $_SESSION['behalf_group_name'] = $onBehalfGroupName;
 
 854     $this->behalf_group_id = $group_id;
 
 855     $this->behalf_group_name = $onBehalfGroupName;
 
 857     $this->behalfGroup = new ttGroup($this->behalf_group_id, $this->org_id);
 
 859     // Adjust on behalf user to first found user in subgroup.
 
 860     $this->adjustBehalfId();
 
 864   // setOnBehalfUser sets on behalf user both the object and the session.
 
 865   function setOnBehalfUser($user_id) {
 
 867     // Unset things first.
 
 868     $this->behalf_id = null;
 
 869     $this->behalf_name = null;
 
 870     unset($this->behalfUser);
 
 871     unset($_SESSION['behalf_id']);
 
 872     unset($_SESSION['behalf_name']);
 
 874     // No need to set if user is us.
 
 875     if ($user_id == $this->id) return;
 
 877     // No need to set if user id is not valid.
 
 878     if (!$this->isUserValid($user_id)) return;
 
 880     // We are good to set on behalf user.
 
 881     $onBehalfUserName = ttUserHelper::getUserName($user_id);
 
 882     $_SESSION['behalf_id'] = $user_id;
 
 883     $_SESSION['behalf_name'] = $onBehalfUserName;
 
 884     $this->behalf_id = $user_id;
 
 885     $this->behalf_name = $onBehalfUserName;
 
 887     $this->behalfUser = new ttBehalfUser($this->behalf_id, $this->org_id);
 
 891   // The exists() function determines if an active user exists in context of a page.
 
 892   // If we are working as self, true.
 
 893   // If we are working in a subgroup with active users, true.
 
 894   // If we are working in a subgroup without active users, false.
 
 896     if (!$this->behalfGroup)
 
 897       return true; // Working as self.
 
 898     else if ($this->behalfGroup->active_users)
 
 899       return true; // Subgroup has users.