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('ttClientHelper');
 
  30 import('DateAndTime');
 
  32 import('ttTimeHelper');
 
  34 require_once(dirname(__FILE__).'/../../plugins/CustomFields.class.php');
 
  36 // Class ttReportHelper is used for help with reports.
 
  37 class ttReportHelper {
 
  39   // getWhere prepares a WHERE clause for a report query.
 
  40   static function getWhere($bean) {
 
  43     // Prepare dropdown parts.
 
  45     if ($bean->getAttribute('client'))
 
  46       $dropdown_parts .= ' and l.client_id = '.$bean->getAttribute('client');
 
  47     elseif ($user->isClient() && $user->client_id)
 
  48       $dropdown_parts .= ' and l.client_id = '.$user->client_id;
 
  49     if ($bean->getAttribute('option')) $dropdown_parts .= ' and l.id in(select log_id from tt_custom_field_log where status = 1 and option_id = '.$bean->getAttribute('option').')';
 
  50     if ($bean->getAttribute('project')) $dropdown_parts .= ' and l.project_id = '.$bean->getAttribute('project');
 
  51     if ($bean->getAttribute('task')) $dropdown_parts .= ' and l.task_id = '.$bean->getAttribute('task');
 
  52     if ($bean->getAttribute('include_records')=='1') $dropdown_parts .= ' and l.billable = 1';
 
  53     if ($bean->getAttribute('include_records')=='2') $dropdown_parts .= ' and l.billable = 0';
 
  54     if ($bean->getAttribute('invoice')=='1') $dropdown_parts .= ' and l.invoice_id is not NULL';
 
  55     if ($bean->getAttribute('invoice')=='2') $dropdown_parts .= ' and l.invoice_id is NULL';
 
  57     // Prepare user list part.
 
  59     if (($user->canManageTeam() || $user->isClient()) && is_array($bean->getAttribute('users')))
 
  60       $userlist = join(',', $bean->getAttribute('users'));
 
  61     // Prepare sql query part for user list.
 
  62     $user_list_part = null;
 
  63     if ($user->canManageTeam() || $user->isClient())
 
  64       $user_list_part = " and l.user_id in ($userlist)";
 
  66       $user_list_part = " and l.user_id = ".$user->id;
 
  68     // Prepare sql query part for where.
 
  69     if ($bean->getAttribute('period'))
 
  70       $period = new Period($bean->getAttribute('period'), new DateAndTime($user->date_format));
 
  72       $period = new Period();
 
  74         new DateAndTime($user->date_format, $bean->getAttribute('start_date')),
 
  75         new DateAndTime($user->date_format, $bean->getAttribute('end_date')));
 
  77     $where = " where l.status = 1 and l.date >= '".$period->getBeginDate(DB_DATEFORMAT)."' and l.date <= '".$period->getEndDate(DB_DATEFORMAT)."'".
 
  78       " $user_list_part $dropdown_parts";
 
  82   // getFavWhere prepares a WHERE clause for a favorite report query.
 
  83   static function getFavWhere($report) {
 
  86     // Prepare dropdown parts.
 
  88     if ($report['client_id'])
 
  89       $dropdown_parts .= ' and l.client_id = '.$report['client_id'];
 
  90     elseif ($user->isClient() && $user->client_id)
 
  91       $dropdown_parts .= ' and l.client_id = '.$user->client_id;
 
  92     if ($report['cf_1_option_id']) $dropdown_parts .= ' and l.id in(select log_id from tt_custom_field_log where status = 1 and option_id = '.$report['cf_1_option_id'].')';
 
  93     if ($report['project_id']) $dropdown_parts .= ' and l.project_id = '.$report['project_id'];
 
  94     if ($report['task_id']) $dropdown_parts .= ' and l.task_id = '.$report['task_id'];
 
  95     if ($report['billable']=='1') $dropdown_parts .= ' and l.billable = 1';
 
  96     if ($report['billable']=='2') $dropdown_parts .= ' and l.billable = 0';
 
  97     if ($report['invoice']=='1') $dropdown_parts .= ' and l.invoice_id is not NULL';
 
  98     if ($report['invoice']=='2') $dropdown_parts .= ' and l.invoice_id is NULL';
 
 100     // Prepare user list part.
 
 102     if (($user->canManageTeam() || $user->isClient())) {
 
 103       if ($report['users'])
 
 104         $userlist = $report['users'];
 
 106         $active_users = ttTeamHelper::getActiveUsers();
 
 107         foreach ($active_users as $single_user)
 
 108           $users[] = $single_user['id'];
 
 109         $userlist = join(',', $users);
 
 112     // Prepare sql query part for user list.
 
 113     $user_list_part = null;
 
 114     if ($user->canManageTeam() || $user->isClient())
 
 115       $user_list_part = " and l.user_id in ($userlist)";
 
 117       $user_list_part = " and l.user_id = ".$user->id;
 
 119     // Prepare sql query part for where.
 
 120     if ($report['period'])
 
 121       $period = new Period($report['period'], new DateAndTime($user->date_format));
 
 123       $period = new Period();
 
 125         new DateAndTime($user->date_format, $report['period_start']),
 
 126         new DateAndTime($user->date_format, $report['period_end']));
 
 128     $where = " where l.status = 1 and l.date >= '".$period->getBeginDate(DB_DATEFORMAT)."' and l.date <= '".$period->getEndDate(DB_DATEFORMAT)."'".
 
 129       " $user_list_part $dropdown_parts";
 
 133   // getExpenseWhere prepares WHERE clause for expenses query in a report.
 
 134   static function getExpenseWhere($bean) {
 
 137     // Prepare dropdown parts.
 
 138     $dropdown_parts = '';
 
 139     if ($bean->getAttribute('client'))
 
 140       $dropdown_parts .= ' and ei.client_id = '.$bean->getAttribute('client');
 
 141     elseif ($user->isClient() && $user->client_id)
 
 142       $dropdown_parts .= ' and ei.client_id = '.$user->client_id;
 
 143     if ($bean->getAttribute('project')) $dropdown_parts .= ' and ei.project_id = '.$bean->getAttribute('project');
 
 144     if ($bean->getAttribute('invoice')=='1') $dropdown_parts .= ' and ei.invoice_id is not NULL';
 
 145     if ($bean->getAttribute('invoice')=='2') $dropdown_parts .= ' and ei.invoice_id is NULL';
 
 147     // Prepare user list part.
 
 149     if (($user->canManageTeam() || $user->isClient()) && is_array($bean->getAttribute('users')))
 
 150       $userlist = join(',', $bean->getAttribute('users'));
 
 151     // Prepare sql query part for user list.
 
 152     $user_list_part = null;
 
 153     if ($user->canManageTeam() || $user->isClient())
 
 154       $user_list_part = " and ei.user_id in ($userlist)";
 
 156       $user_list_part = " and ei.user_id = ".$user->id;
 
 158     // Prepare sql query part for where.
 
 159     if ($bean->getAttribute('period'))
 
 160       $period = new Period($bean->getAttribute('period'), new DateAndTime($user->date_format));
 
 162       $period = new Period();
 
 164         new DateAndTime($user->date_format, $bean->getAttribute('start_date')),
 
 165         new DateAndTime($user->date_format, $bean->getAttribute('end_date')));
 
 167     $where = " where ei.status = 1 and ei.date >= '".$period->getBeginDate(DB_DATEFORMAT)."' and ei.date <= '".$period->getEndDate(DB_DATEFORMAT)."'".
 
 168       " $user_list_part $dropdown_parts";
 
 172   // getFavExpenseWhere prepares a WHERE clause for expenses query in a favorite report.
 
 173   static function getFavExpenseWhere($report) {
 
 176     // Prepare dropdown parts.
 
 177     $dropdown_parts = '';
 
 178     if ($report['client_id'])
 
 179       $dropdown_parts .= ' and ei.client_id = '.$report['client_id'];
 
 180     elseif ($user->isClient() && $user->client_id)
 
 181       $dropdown_parts .= ' and ei.client_id = '.$user->client_id;
 
 182     if ($report['project_id']) $dropdown_parts .= ' and ei.project_id = '.$report['project_id'];
 
 183     if ($report['invoice']=='1') $dropdown_parts .= ' and ei.invoice_id is not NULL';
 
 184     if ($report['invoice']=='2') $dropdown_parts .= ' and ei.invoice_id is NULL';
 
 186     // Prepare user list part.
 
 188     if (($user->canManageTeam() || $user->isClient())) {
 
 189       if ($report['users'])
 
 190         $userlist = $report['users'];
 
 192         $active_users = ttTeamHelper::getActiveUsers();
 
 193         foreach ($active_users as $single_user)
 
 194           $users[] = $single_user['id'];
 
 195         $userlist = join(',', $users);
 
 198     // Prepare sql query part for user list.
 
 199     $user_list_part = null;
 
 200     if ($user->canManageTeam() || $user->isClient())
 
 201       $user_list_part = " and ei.user_id in ($userlist)";
 
 203       $user_list_part = " and ei.user_id = ".$user->id;
 
 205     // Prepare sql query part for where.
 
 206     if ($report['period'])
 
 207       $period = new Period($report['period'], new DateAndTime($user->date_format));
 
 209       $period = new Period();
 
 211         new DateAndTime($user->date_format, $report['period_start']),
 
 212         new DateAndTime($user->date_format, $report['period_end']));
 
 214     $where = " where ei.status = 1 and ei.date >= '".$period->getBeginDate(DB_DATEFORMAT)."' and ei.date <= '".$period->getEndDate(DB_DATEFORMAT)."'".
 
 215       " $user_list_part $dropdown_parts";
 
 219   // getItems retrieves all items associated with a report.
 
 220   // It combines tt_log and tt_expense_items in one array for presentation in one table using mysql union all.
 
 221   // Expense items use the "note" field for item name.
 
 222   static function getItems($bean) {
 
 224     $mdb2 = getConnection();
 
 226     $group_by_option = $bean->getAttribute('group_by');
 
 227     $convertTo12Hour = ('%I:%M %p' == $user->time_format) && ($bean->getAttribute('chstart') || $bean->getAttribute('chfinish'));
 
 229     // Prepare a query for time items in tt_log table.
 
 230     $fields = array(); // An array of fields for database query.
 
 231     array_push($fields, 'l.id as id');
 
 232     array_push($fields, '1 as type'); // Type 1 is for tt_log entries.
 
 233     array_push($fields, 'l.date as date');
 
 234     if($user->canManageTeam() || $user->isClient())
 
 235       array_push($fields, 'u.name as user');
 
 236     // Add client name if it is selected.
 
 237     if ($bean->getAttribute('chclient') || 'client' == $group_by_option)
 
 238       array_push($fields, 'c.name as client');
 
 239     // Add project name if it is selected.
 
 240     if ($bean->getAttribute('chproject') || 'project' == $group_by_option)
 
 241       array_push($fields, 'p.name as project');
 
 242     // Add task name if it is selected.
 
 243     if ($bean->getAttribute('chtask') || 'task' == $group_by_option)
 
 244       array_push($fields, 't.name as task');
 
 246     $include_cf_1 = $bean->getAttribute('chcf_1') || 'cf_1' == $group_by_option;
 
 248       $custom_fields = new CustomFields($user->team_id);
 
 249       $cf_1_type = $custom_fields->fields[0]['type'];
 
 250       if ($cf_1_type == CustomFields::TYPE_TEXT) {
 
 251         array_push($fields, 'cfl.value as cf_1');
 
 252       } elseif ($cf_1_type == CustomFields::TYPE_DROPDOWN) {
 
 253         array_push($fields, 'cfo.value as cf_1');
 
 257     if ($bean->getAttribute('chstart')) {
 
 258       array_push($fields, "l.start as unformatted_start");
 
 259       array_push($fields, "TIME_FORMAT(l.start, '%k:%i') as start");
 
 262     if ($bean->getAttribute('chfinish'))
 
 263       array_push($fields, "TIME_FORMAT(sec_to_time(time_to_sec(l.start) + time_to_sec(l.duration)), '%k:%i') as finish");
 
 265     if ($bean->getAttribute('chduration'))
 
 266       array_push($fields, "TIME_FORMAT(l.duration, '%k:%i') as duration");
 
 268     if ($bean->getAttribute('chnote'))
 
 269       array_push($fields, 'l.comment as note');
 
 271     $includeCost = $bean->getAttribute('chcost');
 
 273       if (MODE_TIME == $user->tracking_mode)
 
 274         array_push($fields, "cast(l.billable * coalesce(u.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10,2)) as cost");   // Use default user rate.
 
 276         array_push($fields, "cast(l.billable * coalesce(upb.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10,2)) as cost"); // Use project rate for user.
 
 277       array_push($fields, "null as expense"); 
 
 279     // Add invoice name if it is selected.
 
 280     if (($user->canManageTeam() || $user->isClient()) && $bean->getAttribute('chinvoice'))
 
 281       array_push($fields, 'i.name as invoice');
 
 283     // Prepare sql query part for left joins.
 
 285     if ($bean->getAttribute('chclient') || 'client' == $group_by_option)
 
 286       $left_joins .= " left join tt_clients c on (c.id = l.client_id)";
 
 287     if (($user->canManageTeam() || $user->isClient()) && $bean->getAttribute('chinvoice'))
 
 288       $left_joins .= " left join tt_invoices i on (i.id = l.invoice_id and i.status = 1)";
 
 289     if ($user->canManageTeam() || $user->isClient() || $user->isPluginEnabled('ex'))
 
 290        $left_joins .= " left join tt_users u on (u.id = l.user_id)";
 
 291     if ($bean->getAttribute('chproject') || 'project' == $group_by_option)
 
 292       $left_joins .= " left join tt_projects p on (p.id = l.project_id)";
 
 293     if ($bean->getAttribute('chtask') || 'task' == $group_by_option)
 
 294       $left_joins .= " left join tt_tasks t on (t.id = l.task_id)";
 
 296       if ($cf_1_type == CustomFields::TYPE_TEXT)
 
 297         $left_joins .= " left join tt_custom_field_log cfl on (l.id = cfl.log_id and cfl.status = 1)";
 
 298       elseif ($cf_1_type == CustomFields::TYPE_DROPDOWN) {
 
 299         $left_joins .=  " left join tt_custom_field_log cfl on (l.id = cfl.log_id and cfl.status = 1)".
 
 300           " left join tt_custom_field_options cfo on (cfl.option_id = cfo.id)";
 
 303     if ($includeCost && MODE_TIME != $user->tracking_mode)
 
 304       $left_joins .= " left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id)";
 
 306     $where = ttReportHelper::getWhere($bean);
 
 308     // Construct sql query for tt_log items.
 
 309     $sql = "select ".join(', ', $fields)." from tt_log l $left_joins $where";
 
 310     // If we don't have expense items (such as when the Expenses plugin is desabled), the above is all sql we need,
 
 311     // with an exception of sorting part, that is added in the end.
 
 313     // However, when we have expenses, we need to do a union with a separate query for expense items from tt_expense_items table.
 
 314     if ($bean->getAttribute('chcost') && $user->isPluginEnabled('ex')) { // if ex(penses) plugin is enabled
 
 316       $fields = array(); // An array of fields for database query.
 
 317       array_push($fields, 'ei.id');
 
 318       array_push($fields, '2 as type'); // Type 2 is for tt_expense_items entries.
 
 319       array_push($fields, 'ei.date');
 
 320       if($user->canManageTeam() || $user->isClient())
 
 321         array_push($fields, 'u.name as user');
 
 322       // Add client name if it is selected.
 
 323       if ($bean->getAttribute('chclient') || 'client' == $group_by_option)
 
 324         array_push($fields, 'c.name as client');
 
 325       // Add project name if it is selected.
 
 326       if ($bean->getAttribute('chproject') || 'project' == $group_by_option)
 
 327         array_push($fields, 'p.name as project');
 
 328       if ($bean->getAttribute('chtask') || 'task' == $group_by_option)
 
 329         array_push($fields, 'null'); // null for task name. We need to match column count for union.
 
 330       if ($bean->getAttribute('chcf_1') || 'cf_1' == $group_by_option)
 
 331         array_push($fields, 'null'); // null for cf_1.
 
 332       if ($bean->getAttribute('chstart')) {
 
 333         array_push($fields, 'null'); // null for unformatted_start.
 
 334         array_push($fields, 'null'); // null for start.
 
 336       if ($bean->getAttribute('chfinish'))
 
 337         array_push($fields, 'null'); // null for finish.
 
 338       if ($bean->getAttribute('chduration'))
 
 339         array_push($fields, 'null'); // null for duration.
 
 340       // Use the note field to print item name.
 
 341       if ($bean->getAttribute('chnote'))
 
 342         array_push($fields, 'ei.name as note');
 
 343       array_push($fields, 'ei.cost as cost');
 
 344       array_push($fields, 'ei.cost as expense');
 
 345       // Add invoice name if it is selected.
 
 346       if (($user->canManageTeam() || $user->isClient()) && $bean->getAttribute('chinvoice'))
 
 347         array_push($fields, 'i.name as invoice');
 
 349       // Prepare sql query part for left joins.
 
 351       if ($user->canManageTeam() || $user->isClient())
 
 352         $left_joins .= " left join tt_users u on (u.id = ei.user_id)";
 
 353       if ($bean->getAttribute('chclient') || 'client' == $group_by_option)
 
 354         $left_joins .= " left join tt_clients c on (c.id = ei.client_id)";
 
 355       if ($bean->getAttribute('chproject') || 'project' == $group_by_option)
 
 356         $left_joins .= " left join tt_projects p on (p.id = ei.project_id)";
 
 357       if (($user->canManageTeam() || $user->isClient()) && $bean->getAttribute('chinvoice'))
 
 358         $left_joins .= " left join tt_invoices i on (i.id = ei.invoice_id and i.status = 1)";
 
 360       $where = ttReportHelper::getExpenseWhere($bean);
 
 362       // Construct sql query for expense items.
 
 363       $sql_for_expense_items = "select ".join(', ', $fields)." from tt_expense_items ei $left_joins $where";
 
 365       // Construct a union.
 
 366       $sql = "($sql) union all ($sql_for_expense_items)";
 
 369     // Determine sort part.
 
 370     $sort_part = ' order by ';
 
 371     if ('no_grouping' == $group_by_option || 'date' == $group_by_option)
 
 372       $sort_part .= 'date';
 
 374       $sort_part .= $group_by_option.', date';
 
 375     if (($user->canManageTeam() || $user->isClient()) && is_array($bean->getAttribute('users')) && 'user' != $group_by_option)
 
 376       $sort_part .= ', user, type';
 
 377     if ($bean->getAttribute('chstart'))
 
 378       $sort_part .= ', unformatted_start';
 
 379     $sort_part .= ', id';
 
 382     // By now we are ready with sql.
 
 384     // Obtain items for report.
 
 385     $res = $mdb2->query($sql);
 
 386     if (is_a($res, 'PEAR_Error')) die($res->getMessage());
 
 388     while ($val = $res->fetchRow()) {
 
 389       if ($convertTo12Hour) {
 
 390         if($val['start'] != '')
 
 391           $val['start'] = ttTimeHelper::to12HourFormat($val['start']);
 
 392         if($val['finish'] != '')
 
 393           $val['finish'] = ttTimeHelper::to12HourFormat($val['finish']);
 
 395       if (isset($val['cost'])) {
 
 396         if ('.' != $user->decimal_mark)
 
 397           $val['cost'] = str_replace('.', $user->decimal_mark, $val['cost']);
 
 399       if (isset($val['expense'])) {
 
 400         if ('.' != $user->decimal_mark)
 
 401           $val['expense'] = str_replace('.', $user->decimal_mark, $val['expense']);
 
 403       if ('no_grouping' != $group_by_option) {
 
 404         $val['grouped_by'] = $val[$group_by_option];
 
 405         if ('date' == $group_by_option) {
 
 406           // This is needed to get the date in user date format.
 
 407           $o_date = new DateAndTime(DB_DATEFORMAT, $val['grouped_by']);
 
 408           $val['grouped_by'] = $o_date->toString($user->date_format);
 
 413       // This is needed to get the date in user date format.
 
 414       $o_date = new DateAndTime(DB_DATEFORMAT, $val['date']);
 
 415       $val['date'] = $o_date->toString($user->date_format);
 
 419       $report_items[] = $row;
 
 422     return $report_items;
 
 425   // getFavItems retrieves all items associated with a favorite report.
 
 426   // It combines tt_log and tt_expense_items in one array for presentation in one table using mysql union all.
 
 427   // Expense items use the "note" field for item name.
 
 428   static function getFavItems($report) {
 
 430     $mdb2 = getConnection();
 
 432     $group_by_option = $report['group_by'];
 
 433     $convertTo12Hour = ('%I:%M %p' == $user->time_format) && ($report['show_start'] || $report['show_end']);
 
 435     // Prepare a query for time items in tt_log table.
 
 436     $fields = array(); // An array of fields for database query.
 
 437     array_push($fields, 'l.id as id');
 
 438     array_push($fields, '1 as type'); // Type 1 is for tt_log entries.
 
 439     array_push($fields, 'l.date as date');
 
 440     if($user->canManageTeam() || $user->isClient())
 
 441       array_push($fields, 'u.name as user');
 
 442     // Add client name if it is selected.
 
 443     if ($report['show_client'] || 'client' == $group_by_option)
 
 444       array_push($fields, 'c.name as client');
 
 445     // Add project name if it is selected.
 
 446     if ($report['show_project'] || 'project' == $group_by_option)
 
 447       array_push($fields, 'p.name as project');
 
 448     // Add task name if it is selected.
 
 449     if ($report['show_task'] || 'task' == $group_by_option)
 
 450       array_push($fields, 't.name as task');
 
 452     $include_cf_1 = $report['show_custom_field_1'] || 'cf_1' == $group_by_option;
 
 454       $custom_fields = new CustomFields($user->team_id);
 
 455       $cf_1_type = $custom_fields->fields[0]['type'];
 
 456       if ($cf_1_type == CustomFields::TYPE_TEXT) {
 
 457         array_push($fields, 'cfl.value as cf_1');
 
 458       } elseif ($cf_1_type == CustomFields::TYPE_DROPDOWN) {
 
 459         array_push($fields, 'cfo.value as cf_1');
 
 463     if ($report['show_start']) {
 
 464       array_push($fields, "l.start as unformatted_start");
 
 465       array_push($fields, "TIME_FORMAT(l.start, '%k:%i') as start");
 
 468     if ($report['show_end'])
 
 469       array_push($fields, "TIME_FORMAT(sec_to_time(time_to_sec(l.start) + time_to_sec(l.duration)), '%k:%i') as finish");
 
 471     if ($report['show_duration'])
 
 472       array_push($fields, "TIME_FORMAT(l.duration, '%k:%i') as duration");
 
 474     if ($report['show_note'])
 
 475       array_push($fields, 'l.comment as note');
 
 477     $includeCost = $report['show_cost'];
 
 479       if (MODE_TIME == $user->tracking_mode)
 
 480         array_push($fields, "cast(l.billable * coalesce(u.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10,2)) as cost");   // Use default user rate.
 
 482         array_push($fields, "cast(l.billable * coalesce(upb.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10,2)) as cost"); // Use project rate for user.
 
 483       array_push($fields, "null as expense"); 
 
 485     // Add invoice name if it is selected.
 
 486     if (($user->canManageTeam() || $user->isClient()) && $report['show_invoice'])
 
 487       array_push($fields, 'i.name as invoice');
 
 489     // Prepare sql query part for left joins.
 
 491     if ($report['show_client'] || 'client' == $group_by_option)
 
 492       $left_joins .= " left join tt_clients c on (c.id = l.client_id)";
 
 493     if (($user->canManageTeam() || $user->isClient()) && $report['show_invoice'])
 
 494       $left_joins .= " left join tt_invoices i on (i.id = l.invoice_id and i.status = 1)";
 
 495     if ($user->canManageTeam() || $user->isClient() || $user->isPluginEnabled('ex'))
 
 496        $left_joins .= " left join tt_users u on (u.id = l.user_id)";
 
 497     if ($report['show_project'] || 'project' == $group_by_option)
 
 498       $left_joins .= " left join tt_projects p on (p.id = l.project_id)";
 
 499     if ($report['show_task'] || 'task' == $group_by_option)
 
 500       $left_joins .= " left join tt_tasks t on (t.id = l.task_id)";
 
 502       if ($cf_1_type == CustomFields::TYPE_TEXT)
 
 503         $left_joins .= " left join tt_custom_field_log cfl on (l.id = cfl.log_id and cfl.status = 1)";
 
 504       elseif ($cf_1_type == CustomFields::TYPE_DROPDOWN) {
 
 505         $left_joins .=  " left join tt_custom_field_log cfl on (l.id = cfl.log_id and cfl.status = 1)".
 
 506           " left join tt_custom_field_options cfo on (cfl.option_id = cfo.id)";
 
 509     if ($includeCost && MODE_TIME != $user->tracking_mode)
 
 510       $left_joins .= " left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id)";
 
 512     $where = ttReportHelper::getFavWhere($report);
 
 514     // Construct sql query for tt_log items.
 
 515     $sql = "select ".join(', ', $fields)." from tt_log l $left_joins $where";
 
 516     // If we don't have expense items (such as when the Expenses plugin is desabled), the above is all sql we need,
 
 517     // with an exception of sorting part, that is added in the end.
 
 519     // However, when we have expenses, we need to do a union with a separate query for expense items from tt_expense_items table.
 
 520     if ($report['show_cost'] && $user->isPluginEnabled('ex')) { // if ex(penses) plugin is enabled
 
 522       $fields = array(); // An array of fields for database query.
 
 523       array_push($fields, 'ei.id');
 
 524       array_push($fields, '2 as type'); // Type 2 is for tt_expense_items entries.
 
 525       array_push($fields, 'ei.date');
 
 526       if($user->canManageTeam() || $user->isClient())
 
 527         array_push($fields, 'u.name as user');
 
 528       // Add client name if it is selected.
 
 529       if ($report['show_client'] || 'client' == $group_by_option)
 
 530         array_push($fields, 'c.name as client');
 
 531       // Add project name if it is selected.
 
 532       if ($report['show_project'] || 'project' == $group_by_option)
 
 533         array_push($fields, 'p.name as project');
 
 534       if ($report['show_task'] || 'task' == $group_by_option)
 
 535         array_push($fields, 'null'); // null for task name. We need to match column count for union.
 
 536       if ($report['show_custom_field_1'] || 'cf_1' == $group_by_option)
 
 537         array_push($fields, 'null'); // null for cf_1.
 
 538       if ($report['show_start']) {
 
 539         array_push($fields, 'null'); // null for unformatted_start.
 
 540         array_push($fields, 'null'); // null for start.
 
 542       if ($report['show_end'])
 
 543         array_push($fields, 'null'); // null for finish.
 
 544       if ($report['show_duration'])
 
 545         array_push($fields, 'null'); // null for duration.
 
 546       // Use the note field to print item name.
 
 547       if ($report['show_note'])
 
 548         array_push($fields, 'ei.name as note');
 
 549       array_push($fields, 'ei.cost as cost');
 
 550       array_push($fields, 'ei.cost as expense');
 
 551       // Add invoice name if it is selected.
 
 552       if (($user->canManageTeam() || $user->isClient()) && $report['show_invoice'])
 
 553         array_push($fields, 'i.name as invoice');
 
 555       // Prepare sql query part for left joins.
 
 557       if ($user->canManageTeam() || $user->isClient())
 
 558         $left_joins .= " left join tt_users u on (u.id = ei.user_id)";
 
 559       if ($report['show_client'] || 'client' == $group_by_option)
 
 560         $left_joins .= " left join tt_clients c on (c.id = ei.client_id)";
 
 561       if ($report['show_project'] || 'project' == $group_by_option)
 
 562         $left_joins .= " left join tt_projects p on (p.id = ei.project_id)";
 
 563       if (($user->canManageTeam() || $user->isClient()) && $report['show_invoice'])
 
 564         $left_joins .= " left join tt_invoices i on (i.id = ei.invoice_id and i.status = 1)";
 
 566       $where = ttReportHelper::getFavExpenseWhere($report);
 
 568       // Construct sql query for expense items.
 
 569       $sql_for_expense_items = "select ".join(', ', $fields)." from tt_expense_items ei $left_joins $where";
 
 571       // Construct a union.
 
 572       $sql = "($sql) union all ($sql_for_expense_items)";
 
 575     // Determine sort part.
 
 576     $sort_part = ' order by ';
 
 577     if ($group_by_option == null || 'no_grouping' == $group_by_option || 'date' == $group_by_option) // TODO: fix DB for NULL values in group_by field.
 
 578       $sort_part .= 'date';
 
 580       $sort_part .= $group_by_option.', date';
 
 581     if (($user->canManageTeam() || $user->isClient()) /*&& is_array($bean->getAttribute('users'))*/ && 'user' != $group_by_option)
 
 582       $sort_part .= ', user, type';
 
 583     if ($report['show_start'])
 
 584       $sort_part .= ', unformatted_start';
 
 585     $sort_part .= ', id';
 
 588     // By now we are ready with sql.
 
 590     // Obtain items for report.
 
 591     $res = $mdb2->query($sql);
 
 592     if (is_a($res, 'PEAR_Error')) die($res->getMessage());
 
 594     while ($val = $res->fetchRow()) {
 
 595       if ($convertTo12Hour) {
 
 596         if($val['start'] != '')
 
 597           $val['start'] = ttTimeHelper::to12HourFormat($val['start']);
 
 598         if($val['finish'] != '')
 
 599           $val['finish'] = ttTimeHelper::to12HourFormat($val['finish']);
 
 601       if (isset($val['cost'])) {
 
 602         if ('.' != $user->decimal_mark)
 
 603           $val['cost'] = str_replace('.', $user->decimal_mark, $val['cost']);
 
 605       if (isset($val['expense'])) {
 
 606         if ('.' != $user->decimal_mark)
 
 607           $val['expense'] = str_replace('.', $user->decimal_mark, $val['expense']);
 
 609       if ('no_grouping' != $group_by_option) {
 
 610         $val['grouped_by'] = $val[$group_by_option];
 
 611         if ('date' == $group_by_option) {
 
 612           // This is needed to get the date in user date format.
 
 613           $o_date = new DateAndTime(DB_DATEFORMAT, $val['grouped_by']);
 
 614           $val['grouped_by'] = $o_date->toString($user->date_format);
 
 619       // This is needed to get the date in user date format.
 
 620       $o_date = new DateAndTime(DB_DATEFORMAT, $val['date']);
 
 621       $val['date'] = $o_date->toString($user->date_format);
 
 625       $report_items[] = $row;
 
 628     return $report_items;
 
 631   // getSubtotals calculates report items subtotals when a report is grouped by.
 
 632   // Without expenses, it's a simple select with group by.
 
 633   // With expenses, it becomes a select with group by from a combined set of records obtained with "union all".
 
 634   static function getSubtotals($bean) {
 
 637     $group_by_option = $bean->getAttribute('group_by');
 
 638     if ('no_grouping' == $group_by_option) return null;
 
 640     $mdb2 = getConnection();
 
 642     // Start with sql to obtain subtotals for time items. This simple sql will be used when we have no expenses.
 
 644     // Determine group by field and a required join.
 
 645     switch ($group_by_option) {
 
 647         $group_field = 'l.date';
 
 651         $group_field = 'u.name';
 
 652         $group_join = 'left join tt_users u on (l.user_id = u.id) ';
 
 655         $group_field = 'c.name';
 
 656         $group_join = 'left join tt_clients c on (l.client_id = c.id) ';
 
 659         $group_field = 'p.name';
 
 660         $group_join = 'left join tt_projects p on (l.project_id = p.id) ';
 
 663         $group_field = 't.name';
 
 664         $group_join = 'left join tt_tasks t on (l.task_id = t.id) ';
 
 667         $group_field = 'cfo.value';
 
 668         $custom_fields = new CustomFields($user->team_id);
 
 669         if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_TEXT)
 
 670           $group_join = 'left join tt_custom_field_log cfl on (l.id = cfl.log_id and cfl.status = 1) left join tt_custom_field_options cfo on (cfl.value = cfo.id) ';
 
 671         elseif ($custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN)
 
 672           $group_join = 'left join tt_custom_field_log cfl on (l.id = cfl.log_id and cfl.status = 1) left join tt_custom_field_options cfo on (cfl.option_id = cfo.id) ';
 
 676     $where = ttReportHelper::getWhere($bean);
 
 677     if ($bean->getAttribute('chcost')) {
 
 678       if (MODE_TIME == $user->tracking_mode) {
 
 679         if ($group_by_option != 'user')
 
 680           $left_join = 'left join tt_users u on (l.user_id = u.id)';
 
 681         $sql = "select $group_field as group_field, sum(time_to_sec(l.duration)) as time, 
 
 682           sum(cast(l.billable * coalesce(u.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10, 2))) as cost,
 
 683           null as expenses from tt_log l
 
 684           $group_join $left_join $where group by $group_field";
 
 686         // If we are including cost and tracking projects, our query (the same as above) needs to join the tt_user_project_binds table.
 
 687         $sql = "select $group_field as group_field, sum(time_to_sec(l.duration)) as time, 
 
 688           sum(cast(l.billable * coalesce(upb.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10,2))) as cost,
 
 689           null as expenses from tt_log l
 
 691           left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id) $where group by $group_field";
 
 694       $sql = "select $group_field as group_field, sum(time_to_sec(l.duration)) as time, null as expenses from tt_log l
 
 695          $group_join $where group by $group_field";
 
 697     // By now we have sql for time items.
 
 699     // However, when we have expenses, we need to do a union with a separate query for expense items from tt_expense_items table.
 
 700     if ($bean->getAttribute('chcost') && $user->isPluginEnabled('ex')) { // if ex(penses) plugin is enabled
 
 702       // Determine group by field and a required join.
 
 704       $group_field = 'null';
 
 705       switch ($group_by_option) {
 
 707           $group_field = 'ei.date';
 
 711           $group_field = 'u.name';
 
 712           $group_join = 'left join tt_users u on (ei.user_id = u.id) ';
 
 715           $group_field = 'c.name';
 
 716           $group_join = 'left join tt_clients c on (ei.client_id = c.id) ';
 
 719           $group_field = 'p.name';
 
 720           $group_join = 'left join tt_projects p on (ei.project_id = p.id) ';
 
 724       $where = ttReportHelper::getExpenseWhere($bean);
 
 725       $sql_for_expenses = "select $group_field as group_field, null as time, sum(ei.cost) as cost, sum(ei.cost) as expenses from tt_expense_items ei 
 
 727       // Add a "group by" clause if we are grouping.
 
 728       if ('null' != $group_field) $sql_for_expenses .= " group by $group_field";
 
 730       // Create a combined query.
 
 731       $sql = "select group_field, sum(time) as time, sum(cost) as cost, sum(expenses) as expenses from (($sql) union all ($sql_for_expenses)) t group by group_field";
 
 735     $res = $mdb2->query($sql);
 
 736     if (is_a($res, 'PEAR_Error')) die($res->getMessage());
 
 738     while ($val = $res->fetchRow()) {
 
 739       if ('date' == $group_by_option) {
 
 740         // This is needed to get the date in user date format.
 
 741         $o_date = new DateAndTime(DB_DATEFORMAT, $val['group_field']);
 
 742         $val['group_field'] = $o_date->toString($user->date_format);
 
 745       $time = $val['time'] ? sec_to_time_fmt_hm($val['time']) : null;
 
 746       if ($bean->getAttribute('chcost')) {
 
 747         if ('.' != $user->decimal_mark) {
 
 748           $val['cost'] = str_replace('.', $user->decimal_mark, $val['cost']);
 
 749           $val['expenses'] = str_replace('.', $user->decimal_mark, $val['expenses']);
 
 751         $subtotals[$val['group_field']] = array('name'=>$val['group_field'],'time'=>$time,'cost'=>$val['cost'],'expenses'=>$val['expenses']);
 
 753         $subtotals[$val['group_field']] = array('name'=>$val['group_field'],'time'=>$time);
 
 759   // getFavSubtotals calculates report items subtotals when a favorite report is grouped by.
 
 760   // Without expenses, it's a simple select with group by.
 
 761   // With expenses, it becomes a select with group by from a combined set of records obtained with "union all".
 
 762   static function getFavSubtotals($report) {
 
 765     $group_by_option = $report['group_by'];
 
 766     if ('no_grouping' == $group_by_option) return null;
 
 768     $mdb2 = getConnection();
 
 770     // Start with sql to obtain subtotals for time items. This simple sql will be used when we have no expenses.
 
 772     // Determine group by field and a required join.
 
 773     switch ($group_by_option) {
 
 775         $group_field = 'l.date';
 
 779         $group_field = 'u.name';
 
 780         $group_join = 'left join tt_users u on (l.user_id = u.id) ';
 
 783         $group_field = 'c.name';
 
 784         $group_join = 'left join tt_clients c on (l.client_id = c.id) ';
 
 787         $group_field = 'p.name';
 
 788         $group_join = 'left join tt_projects p on (l.project_id = p.id) ';
 
 791         $group_field = 't.name';
 
 792         $group_join = 'left join tt_tasks t on (l.task_id = t.id) ';
 
 795         $group_field = 'cfo.value';
 
 796         $custom_fields = new CustomFields($user->team_id);
 
 797         if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_TEXT)
 
 798           $group_join = 'left join tt_custom_field_log cfl on (l.id = cfl.log_id and cfl.status = 1) left join tt_custom_field_options cfo on (cfl.value = cfo.id) ';
 
 799         elseif ($custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN)
 
 800           $group_join = 'left join tt_custom_field_log cfl on (l.id = cfl.log_id and cfl.status = 1) left join tt_custom_field_options cfo on (cfl.option_id = cfo.id) ';
 
 804     $where = ttReportHelper::getFavWhere($report);
 
 805     if ($report['show_cost']) {
 
 806       if (MODE_TIME == $user->tracking_mode) {
 
 807         if ($group_by_option != 'user')
 
 808           $left_join = 'left join tt_users u on (l.user_id = u.id)';
 
 809         $sql = "select $group_field as group_field, sum(time_to_sec(l.duration)) as time, 
 
 810           sum(cast(l.billable * coalesce(u.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10, 2))) as cost,
 
 811           null as expenses from tt_log l
 
 812           $group_join $left_join $where group by $group_field";
 
 814         // If we are including cost and tracking projects, our query (the same as above) needs to join the tt_user_project_binds table.
 
 815         $sql = "select $group_field as group_field, sum(time_to_sec(l.duration)) as time, 
 
 816           sum(cast(l.billable * coalesce(upb.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10,2))) as cost,
 
 817           null as expenses from tt_log l 
 
 819           left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id) $where group by $group_field";
 
 822       $sql = "select $group_field as group_field, sum(time_to_sec(l.duration)) as time, null as expenses from tt_log l 
 
 823          $group_join $where group by $group_field";
 
 825     // By now we have sql for time items.
 
 827     // However, when we have expenses, we need to do a union with a separate query for expense items from tt_expense_items table.
 
 828     if ($report['show_cost'] && $user->isPluginEnabled('ex')) { // if ex(penses) plugin is enabled
 
 830       // Determine group by field and a required join.
 
 832       $group_field = 'null';
 
 833       switch ($group_by_option) {
 
 835           $group_field = 'ei.date';
 
 839           $group_field = 'u.name';
 
 840           $group_join = 'left join tt_users u on (ei.user_id = u.id) ';
 
 843           $group_field = 'c.name';
 
 844           $group_join = 'left join tt_clients c on (ei.client_id = c.id) ';
 
 847           $group_field = 'p.name';
 
 848           $group_join = 'left join tt_projects p on (ei.project_id = p.id) ';
 
 852       $where = ttReportHelper::getFavExpenseWhere($report);
 
 853       $sql_for_expenses = "select $group_field as group_field, null as time, sum(ei.cost) as cost, sum(ei.cost) as expenses from tt_expense_items ei 
 
 855       // Add a "group by" clause if we are grouping.
 
 856       if ('null' != $group_field) $sql_for_expenses .= " group by $group_field";
 
 858       // Create a combined query.
 
 859       $sql = "select group_field, sum(time) as time, sum(cost) as cost, sum(expenses) as expenses from (($sql) union all ($sql_for_expenses)) t group by group_field";
 
 863     $res = $mdb2->query($sql);
 
 864     if (is_a($res, 'PEAR_Error')) die($res->getMessage());
 
 866     while ($val = $res->fetchRow()) {
 
 867       if ('date' == $group_by_option) {
 
 868         // This is needed to get the date in user date format.
 
 869         $o_date = new DateAndTime(DB_DATEFORMAT, $val['group_field']);
 
 870         $val['group_field'] = $o_date->toString($user->date_format);
 
 873       $time = $val['time'] ? sec_to_time_fmt_hm($val['time']) : null;
 
 874       if ($report['show_cost']) {
 
 875         if ('.' != $user->decimal_mark) {
 
 876           $val['cost'] = str_replace('.', $user->decimal_mark, $val['cost']);
 
 877           $val['expenses'] = str_replace('.', $user->decimal_mark, $val['expenses']);
 
 879         $subtotals[$val['group_field']] = array('name'=>$val['group_field'],'time'=>$time,'cost'=>$val['cost'],'expenses'=>$val['expenses']);
 
 881         $subtotals[$val['group_field']] = array('name'=>$val['group_field'],'time'=>$time);
 
 887   // getTotals calculates total hours and cost for all report items.
 
 888   static function getTotals($bean)
 
 892     $mdb2 = getConnection();
 
 894     $where = ttReportHelper::getWhere($bean);
 
 896     // Start with a query for time items.
 
 897     if ($bean->getAttribute('chcost')) {
 
 898       if (MODE_TIME == $user->tracking_mode) {
 
 899         $sql = "select sum(time_to_sec(l.duration)) as time,
 
 900           sum(cast(l.billable * coalesce(u.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10,2))) as cost,
 
 903           left join tt_users u on (l.user_id = u.id) $where";
 
 905         $sql = "select sum(time_to_sec(l.duration)) as time,
 
 906           sum(cast(l.billable * coalesce(upb.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10,2))) as cost,
 
 909           left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id) $where";
 
 912       $sql = "select sum(time_to_sec(l.duration)) as time, null as cost, null as expenses from tt_log l $where";
 
 914     // If we have expenses, query becomes a bit more complex.
 
 915     if ($bean->getAttribute('chcost') && $user->isPluginEnabled('ex')) {
 
 916       $where = ttReportHelper::getExpenseWhere($bean);
 
 917       $sql_for_expenses = "select null as time, sum(cost) as cost, sum(cost) as expenses from tt_expense_items ei $where";
 
 918       // Create a combined query.
 
 919       $sql = "select sum(time) as time, sum(cost) as cost, sum(expenses) as expenses from (($sql) union all ($sql_for_expenses)) t";
 
 923     $res = $mdb2->query($sql);
 
 924     if (is_a($res, 'PEAR_Error')) die($res->getMessage());
 
 926     $val = $res->fetchRow();
 
 927     $total_time = $val['time'] ? sec_to_time_fmt_hm($val['time']) : null;
 
 928     if ($bean->getAttribute('chcost')) {
 
 929       $total_cost = $val['cost'];
 
 930       if (!$total_cost) $total_cost = '0.00';
 
 931       if ('.' != $user->decimal_mark)
 
 932         $total_cost = str_replace('.', $user->decimal_mark, $total_cost);
 
 933       $total_expenses = $val['expenses'];
 
 934       if (!$total_expenses) $total_expenses = '0.00';
 
 935       if ('.' != $user->decimal_mark)
 
 936         $total_expenses = str_replace('.', $user->decimal_mark, $total_expenses);
 
 939     if ($bean->getAttribute('period'))
 
 940       $period = new Period($bean->getAttribute('period'), new DateAndTime($user->date_format));
 
 942       $period = new Period();
 
 944         new DateAndTime($user->date_format, $bean->getAttribute('start_date')),
 
 945         new DateAndTime($user->date_format, $bean->getAttribute('end_date')));
 
 948     $totals['start_date'] = $period->getBeginDate();
 
 949     $totals['end_date'] = $period->getEndDate();
 
 950     $totals['time'] = $total_time;
 
 951     $totals['cost'] = $total_cost;
 
 952     $totals['expenses'] = $total_expenses;
 
 957   // getFavTotals calculates total hours and cost for all favorite report items.
 
 958   static function getFavTotals($report)
 
 962     $mdb2 = getConnection();
 
 964     $where = ttReportHelper::getFavWhere($report);
 
 966     // Start with a query for time items.
 
 967     if ($report['show_cost']) {
 
 968       if (MODE_TIME == $user->tracking_mode) {
 
 969         $sql = "select sum(time_to_sec(l.duration)) as time,
 
 970           sum(cast(l.billable * coalesce(u.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10,2))) as cost,
 
 973           left join tt_users u on (l.user_id = u.id) $where";
 
 975         $sql = "select sum(time_to_sec(l.duration)) as time,
 
 976           sum(cast(l.billable * coalesce(upb.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10,2))) as cost,
 
 979           left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id) $where";
 
 982       $sql = "select sum(time_to_sec(l.duration)) as time, null as cost, null as expenses from tt_log l $where";
 
 984     // If we have expenses, query becomes a bit more complex.
 
 985     if ($report['show_cost'] && $user->isPluginEnabled('ex')) {
 
 986       $where = ttReportHelper::getFavExpenseWhere($report);
 
 987       $sql_for_expenses = "select null as time, sum(cost) as cost, sum(cost) as expenses from tt_expense_items ei $where";
 
 988       // Create a combined query.
 
 989       $sql = "select sum(time) as time, sum(cost) as cost, sum(expenses) as expenses from (($sql) union all ($sql_for_expenses)) t";
 
 993     $res = $mdb2->query($sql);
 
 994     if (is_a($res, 'PEAR_Error')) die($res->getMessage());
 
 996     $val = $res->fetchRow();
 
 997     $total_time = $val['time'] ? sec_to_time_fmt_hm($val['time']) : null;
 
 998     if ($report['show_cost']) {
 
 999       $total_cost = $val['cost'];
 
1000       if (!$total_cost) $total_cost = '0.00';
 
1001       if ('.' != $user->decimal_mark)
 
1002         $total_cost = str_replace('.', $user->decimal_mark, $total_cost);
 
1003       $total_expenses = $val['expenses'];
 
1004       if (!$total_expenses) $total_expenses = '0.00';
 
1005       if ('.' != $user->decimal_mark)
 
1006         $total_expenses = str_replace('.', $user->decimal_mark, $total_expenses);
 
1009     if ($report['period'])
 
1010       $period = new Period($report['period'], new DateAndTime($user->date_format));
 
1012       $period = new Period();
 
1014         new DateAndTime($user->date_format, $report['period_start']),
 
1015         new DateAndTime($user->date_format, $report['period_end']));
 
1018     $totals['start_date'] = $period->getBeginDate();
 
1019     $totals['end_date'] = $period->getEndDate();
 
1020     $totals['time'] = $total_time;
 
1021     $totals['cost'] = $total_cost;
 
1022     $totals['expenses'] = $total_expenses;
 
1027   // The assignToInvoice assigns a set of records to a specific invoice.
 
1028   static function assignToInvoice($invoice_id, $time_log_ids, $expense_item_ids)
 
1030     $mdb2 = getConnection();
 
1031     if ($time_log_ids) {
 
1032       $sql = "update tt_log set invoice_id = ".$mdb2->quote($invoice_id).
 
1033         " where id in(".join(', ', $time_log_ids).")";
 
1034       $affected = $mdb2->exec($sql);
 
1035       if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
 
1037     if ($expense_item_ids) {
 
1038       $sql = "update tt_expense_items set invoice_id = ".$mdb2->quote($invoice_id).
 
1039         " where id in(".join(', ', $expense_item_ids).")";
 
1040       $affected = $mdb2->exec($sql);
 
1041       if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
 
1045   // prepareReportBody - prepares an email body for report.
 
1046   static function prepareReportBody($bean, $comment)
 
1051     $items = ttReportHelper::getItems($bean);
 
1052     $group_by = $bean->getAttribute('group_by');
 
1053     if ($group_by && 'no_grouping' != $group_by)
 
1054       $subtotals = ttReportHelper::getSubtotals($bean);
 
1055     $totals = ttReportHelper::getTotals($bean);
 
1057     // Use custom fields plugin if it is enabled.
 
1058     if ($user->isPluginEnabled('cf'))
 
1059       $custom_fields = new CustomFields($user->team_id);
 
1061     // Define some styles to use in email.
 
1062     $style_title = 'text-align: center; font-size: 15pt; font-family: Arial, Helvetica, sans-serif;';
 
1063     $tableHeader = 'font-weight: bold; background-color: #a6ccf7; text-align: left;';
 
1064     $tableHeaderCentered = 'font-weight: bold; background-color: #a6ccf7; text-align: center;';
 
1065     $rowItem = 'background-color: #ccccce;';
 
1066     $rowItemAlt = 'background-color: #f5f5f5;';
 
1067     $rowSubtotal = 'background-color: #e0e0e0;';
 
1068     $cellLeftAligned = 'text-align: left; vertical-align: top;';
 
1069     $cellRightAligned = 'text-align: right; vertical-align: top;';
 
1070     $cellLeftAlignedSubtotal = 'font-weight: bold; text-align: left; vertical-align: top;';
 
1071     $cellRightAlignedSubtotal = 'font-weight: bold; text-align: right; vertical-align: top;';
 
1073     // Start creating email body.
 
1075     $body .= '<head><meta http-equiv="content-type" content="text/html; charset='.CHARSET.'"></head>';
 
1079     $body .= '<p style="'.$style_title.'">'.$i18n->getKey('form.mail.report_subject').': '.$totals['start_date'].' - '.$totals['end_date'].'</p>';
 
1082     if ($comment) $body .= '<p>'.htmlspecialchars($comment).'</p>';
 
1084     if ($bean->getAttribute('chtotalsonly')) {
 
1085       // Totals only report. Output subtotals.
 
1087       // Determine group_by header.
 
1088       if ('cf_1' == $group_by)
 
1089         $group_by_header = htmlspecialchars($custom_fields->fields[0]['label']);
 
1091         $key = 'label.'.$group_by;
 
1092         $group_by_header = $i18n->getKey($key);
 
1095       $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
 
1097       $body .= '<td style="'.$tableHeader.'">'.$group_by_header.'</td>';
 
1098       if ($bean->getAttribute('chduration'))
 
1099         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->getKey('label.duration').'</td>';
 
1100       if ($bean->getAttribute('chcost'))
 
1101         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->getKey('label.cost').'</td>';
 
1103       foreach($subtotals as $subtotal) {
 
1104         $body .= '<tr style="'.$rowSubtotal.'">';
 
1105         $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($subtotal['name'] ? htmlspecialchars($subtotal['name']) : ' ').'</td>';
 
1106         if ($bean->getAttribute('chduration')) {
 
1107           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
 
1108           if ($subtotal['time'] <> '0:00') $body .= $subtotal['time'];
 
1111         if ($bean->getAttribute('chcost')) {
 
1112           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
 
1113           $body .= ($user->canManageTeam() || $user->isClient()) ? $subtotal['cost'] : $subtotal['expenses'];
 
1120       $body .= '<tr><td> </td></tr>';
 
1121       $body .= '<tr style="'.$rowSubtotal.'">';
 
1122       $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->getKey('label.total').'</td>';
 
1123       if ($bean->getAttribute('chduration')) {
 
1124         $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
 
1125         if ($totals['time'] <> '0:00') $body .= $totals['time'];
 
1128       if ($bean->getAttribute('chcost')) {
 
1129         $body .= '<td nowrap style="'.$cellRightAlignedSubtotal.'">'.htmlspecialchars($user->currency).' ';
 
1130         $body .= ($user->canManageTeam() || $user->isClient()) ? $totals['cost'] : $totals['expenses'];
 
1135       $body .= '</table>';
 
1139       // Print table header.
 
1140       $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
 
1142       $body .= '<td style="'.$tableHeader.'">'.$i18n->getKey('label.date').'</td>';
 
1143       if ($user->canManageTeam() || $user->isClient())
 
1144         $body .= '<td style="'.$tableHeader.'">'.$i18n->getKey('label.user').'</td>';
 
1145       if ($bean->getAttribute('chclient'))
 
1146         $body .= '<td style="'.$tableHeader.'">'.$i18n->getKey('label.client').'</td>';
 
1147       if ($bean->getAttribute('chproject'))
 
1148         $body .= '<td style="'.$tableHeader.'">'.$i18n->getKey('label.project').'</td>';
 
1149       if ($bean->getAttribute('chtask'))
 
1150         $body .= '<td style="'.$tableHeader.'">'.$i18n->getKey('label.task').'</td>';
 
1151       if ($bean->getAttribute('chcf_1'))
 
1152         $body .= '<td style="'.$tableHeader.'">'.htmlspecialchars($custom_fields->fields[0]['label']).'</td>';
 
1153       if ($bean->getAttribute('chstart'))
 
1154         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->getKey('label.start').'</td>';
 
1155       if ($bean->getAttribute('chfinish'))
 
1156         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->getKey('label.finish').'</td>';
 
1157       if ($bean->getAttribute('chduration'))
 
1158         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->getKey('label.duration').'</td>';
 
1159       if ($bean->getAttribute('chnote'))
 
1160         $body .= '<td style="'.$tableHeader.'">'.$i18n->getKey('label.note').'</td>';
 
1161       if ($bean->getAttribute('chcost'))
 
1162         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->getKey('label.cost').'</td>';
 
1163       if ($bean->getAttribute('chinvoice'))
 
1164         $body .= '<td style="'.$tableHeader.'">'.$i18n->getKey('label.invoice').'</td>';
 
1167       // Initialize variables to print subtotals.
 
1168       if ($items && 'no_grouping' != $group_by) {
 
1169         $print_subtotals = true;
 
1171         $prev_grouped_by = '';
 
1172         $cur_grouped_by = '';
 
1174       // Initialize variables to alternate color of rows for different dates.
 
1177       $row_style = $rowItem;
 
1179       // Print report items.
 
1180       if (is_array($items)) {
 
1181         foreach ($items as $record) {
 
1182           $cur_date = $record['date'];
 
1183           // Print a subtotal row after a block of grouped items.
 
1184           if ($print_subtotals) {
 
1185             $cur_grouped_by = $record['grouped_by'];
 
1186             if ($cur_grouped_by != $prev_grouped_by && !$first_pass) {
 
1187               $body .= '<tr style="'.$rowSubtotal.'">';
 
1188               $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->getKey('label.subtotal').'</td>';
 
1189               $subtotal_name = htmlspecialchars($subtotals[$prev_grouped_by]['name']);
 
1190               if ($user->canManageTeam() || $user->isClient()) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'user' ? $subtotal_name : '').'</td>';
 
1191               if ($bean->getAttribute('chclient')) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'client' ? $subtotal_name : '').'</td>';
 
1192               if ($bean->getAttribute('chproject')) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'project' ? $subtotal_name : '').'</td>';
 
1193               if ($bean->getAttribute('chtask')) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'task' ? $subtotal_name : '').'</td>';
 
1194               if ($bean->getAttribute('chcf_1')) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'cf_1' ? $subtotal_name : '').'</td>';
 
1195               if ($bean->getAttribute('chstart')) $body .= '<td></td>';
 
1196               if ($bean->getAttribute('chfinish')) $body .= '<td></td>';
 
1197               if ($bean->getAttribute('chduration')) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['time'].'</td>';
 
1198               if ($bean->getAttribute('chnote')) $body .= '<td></td>';
 
1199               if ($bean->getAttribute('chcost')) {
 
1200                 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
 
1201                 $body .= ($user->canManageTeam() || $user->isClient()) ? $subtotals[$prev_grouped_by]['cost'] : $subtotals[$prev_grouped_by]['expenses'];
 
1204               if ($bean->getAttribute('chinvoice')) $body .= '<td></td>';
 
1206               $body .= '<tr><td> </td></tr>';
 
1208             $first_pass = false;
 
1211           // Print a regular row.
 
1212           if ($cur_date != $prev_date)
 
1213             $row_style = ($row_style == $rowItem) ? $rowItemAlt : $rowItem;
 
1214           $body .= '<tr style="'.$row_style.'">';
 
1215           $body .= '<td style="'.$cellLeftAligned.'">'.$record['date'].'</td>';
 
1216           if ($user->canManageTeam() || $user->isClient())
 
1217             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['user']).'</td>';
 
1218           if ($bean->getAttribute('chclient'))
 
1219             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['client']).'</td>';
 
1220           if ($bean->getAttribute('chproject'))
 
1221             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['project']).'</td>';
 
1222           if ($bean->getAttribute('chtask'))
 
1223             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['task']).'</td>';
 
1224           if ($bean->getAttribute('chcf_1'))
 
1225             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['cf_1']).'</td>';
 
1226           if ($bean->getAttribute('chstart'))
 
1227             $body .= '<td nowrap style="'.$cellRightAligned.'">'.$record['start'].'</td>';
 
1228           if ($bean->getAttribute('chfinish'))
 
1229             $body .= '<td nowrap style="'.$cellRightAligned.'">'.$record['finish'].'</td>';
 
1230           if ($bean->getAttribute('chduration'))
 
1231             $body .= '<td style="'.$cellRightAligned.'">'.$record['duration'].'</td>';
 
1232           if ($bean->getAttribute('chnote'))
 
1233             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['note']).'</td>';
 
1234           if ($bean->getAttribute('chcost'))
 
1235             $body .= '<td style="'.$cellRightAligned.'">'.$record['cost'].'</td>';
 
1236           if ($bean->getAttribute('chinvoice'))
 
1237             $body .= '<td style="'.$cellRightAligned.'">'.htmlspecialchars($record['invoice']).'</td>';
 
1240           $prev_date = $record['date'];
 
1241           if ($print_subtotals)
 
1242             $prev_grouped_by = $record['grouped_by'];
 
1246       // Print a terminating subtotal.
 
1247       if ($print_subtotals) {
 
1248         $body .= '<tr style="'.$rowSubtotal.'">';
 
1249         $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->getKey('label.subtotal').'</td>';
 
1250         $subtotal_name = htmlspecialchars($subtotals[$cur_grouped_by]['name']);
 
1251         if ($user->canManageTeam() || $user->isClient()) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'user' ? $subtotal_name : '').'</td>';
 
1252         if ($bean->getAttribute('chclient')) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'client' ? $subtotal_name : '').'</td>';
 
1253         if ($bean->getAttribute('chproject')) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'project' ? $subtotal_name : '').'</td>';
 
1254         if ($bean->getAttribute('chtask')) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'task' ? $subtotal_name : '').'</td>';
 
1255         if ($bean->getAttribute('chcf_1')) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'cf_1' ? $subtotal_name : '').'</td>';
 
1256         if ($bean->getAttribute('chstart')) $body .= '<td></td>';
 
1257         if ($bean->getAttribute('chfinish')) $body .= '<td></td>';
 
1258         if ($bean->getAttribute('chduration')) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$cur_grouped_by]['time'].'</td>';
 
1259         if ($bean->getAttribute('chnote')) $body .= '<td></td>';
 
1260         if ($bean->getAttribute('chcost')) {
 
1261           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
 
1262           $body .= ($user->canManageTeam() || $user->isClient()) ? $subtotals[$cur_grouped_by]['cost'] : $subtotals[$cur_grouped_by]['expenses'];
 
1265         if ($bean->getAttribute('chinvoice')) $body .= '<td></td>';
 
1270       $body .= '<tr><td> </td></tr>';
 
1271       $body .= '<tr style="'.$rowSubtotal.'">';
 
1272       $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->getKey('label.total').'</td>';
 
1273       if ($user->canManageTeam() || $user->isClient()) $body .= '<td></td>';
 
1274       if ($bean->getAttribute('chclient')) $body .= '<td></td>';
 
1275       if ($bean->getAttribute('chproject')) $body .= '<td></td>';
 
1276       if ($bean->getAttribute('chtask')) $body .= '<td></td>';
 
1277       if ($bean->getAttribute('chcf_1')) $body .= '<td></td>';
 
1278       if ($bean->getAttribute('chstart')) $body .= '<td></td>';
 
1279       if ($bean->getAttribute('chfinish')) $body .= '<td></td>';
 
1280       if ($bean->getAttribute('chduration')) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$totals['time'].'</td>';
 
1281       if ($bean->getAttribute('chnote')) $body .= '<td></td>';
 
1282       if ($bean->getAttribute('chcost')) {
 
1283         $body .= '<td nowrap style="'.$cellRightAlignedSubtotal.'">'.htmlspecialchars($user->currency).' ';
 
1284         $body .= ($user->canManageTeam() || $user->isClient()) ? $totals['cost'] : $totals['expenses'];
 
1287       if ($bean->getAttribute('chinvoice')) $body .= '<td></td>';
 
1290       $body .= '</table>';
 
1294     if (!defined('REPORT_FOOTER') || !(REPORT_FOOTER == false))
 
1295       $body .= '<p style="text-align: center;">'.$i18n->getKey('form.mail.footer').'</p>';
 
1297     // Finish creating email body.
 
1298     $body .= '</body></html>';
 
1303   // prepareFavReportBody - prepares an email body for a favorite report.
 
1304   static function prepareFavReportBody($report)
 
1309     $items = ttReportHelper::getFavItems($report);
 
1310     $group_by = $report['group_by'];
 
1311     if ($group_by && 'no_grouping' != $group_by)
 
1312       $subtotals = ttReportHelper::getFavSubtotals($report);
 
1313     $totals = ttReportHelper::getFavTotals($report);
 
1315     // Use custom fields plugin if it is enabled.
 
1316     if ($user->isPluginEnabled('cf'))
 
1317       $custom_fields = new CustomFields($user->team_id);
 
1319     // Define some styles to use in email.
 
1320     $style_title = 'text-align: center; font-size: 15pt; font-family: Arial, Helvetica, sans-serif;';
 
1321     $tableHeader = 'font-weight: bold; background-color: #a6ccf7; text-align: left;';
 
1322     $tableHeaderCentered = 'font-weight: bold; background-color: #a6ccf7; text-align: center;';
 
1323     $rowItem = 'background-color: #ccccce;';
 
1324     $rowItemAlt = 'background-color: #f5f5f5;';
 
1325     $rowSubtotal = 'background-color: #e0e0e0;';
 
1326     $cellLeftAligned = 'text-align: left; vertical-align: top;';
 
1327     $cellRightAligned = 'text-align: right; vertical-align: top;';
 
1328     $cellLeftAlignedSubtotal = 'font-weight: bold; text-align: left; vertical-align: top;';
 
1329     $cellRightAlignedSubtotal = 'font-weight: bold; text-align: right; vertical-align: top;';
 
1331     // Start creating email body.
 
1333     $body .= '<head><meta http-equiv="content-type" content="text/html; charset='.CHARSET.'"></head>';
 
1337     $body .= '<p style="'.$style_title.'">'.$i18n->getKey('form.mail.report_subject').': '.$totals['start_date'].' - '.$totals['end_date'].'</p>';
 
1340     // if ($comment) $body .= '<p>'.htmlspecialchars($comment).'</p>'; // No comment for fav. reports.
 
1342     if ($report['show_totals_only']) {
 
1343       // Totals only report. Output subtotals.
 
1345       // Determine group_by header.
 
1346       if ('cf_1' == $group_by)
 
1347         $group_by_header = htmlspecialchars($custom_fields->fields[0]['label']);
 
1349         $key = 'label.'.$group_by;
 
1350         $group_by_header = $i18n->getKey($key);
 
1353       $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
 
1355       $body .= '<td style="'.$tableHeader.'">'.$group_by_header.'</td>';
 
1356       if ($report['show_duration'])
 
1357         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->getKey('label.duration').'</td>';
 
1358       if ($report['show_cost'])
 
1359         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->getKey('label.cost').'</td>';
 
1361       foreach($subtotals as $subtotal) {
 
1362         $body .= '<tr style="'.$rowSubtotal.'">';
 
1363         $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($subtotal['name'] ? htmlspecialchars($subtotal['name']) : ' ').'</td>';
 
1364         if ($report['show_duration']) {
 
1365           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
 
1366           if ($subtotal['time'] <> '0:00') $body .= $subtotal['time'];
 
1369         if ($report['show_cost']) {
 
1370           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
 
1371           $body .= ($user->canManageTeam() || $user->isClient()) ? $subtotal['cost'] : $subtotal['expenses'];
 
1378       $body .= '<tr><td> </td></tr>';
 
1379       $body .= '<tr style="'.$rowSubtotal.'">';
 
1380       $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->getKey('label.total').'</td>';
 
1381       if ($report['show_duration']) {
 
1382         $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
 
1383         if ($totals['time'] <> '0:00') $body .= $totals['time'];
 
1386       if ($report['show_cost']) {
 
1387         $body .= '<td nowrap style="'.$cellRightAlignedSubtotal.'">'.htmlspecialchars($user->currency).' ';
 
1388         $body .= ($user->canManageTeam() || $user->isClient()) ? $totals['cost'] : $totals['expenses'];
 
1393       $body .= '</table>';
 
1397       // Print table header.
 
1398       $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
 
1400       $body .= '<td style="'.$tableHeader.'">'.$i18n->getKey('label.date').'</td>';
 
1401       if ($user->canManageTeam() || $user->isClient())
 
1402         $body .= '<td style="'.$tableHeader.'">'.$i18n->getKey('label.user').'</td>';
 
1403       if ($report['show_client'])
 
1404         $body .= '<td style="'.$tableHeader.'">'.$i18n->getKey('label.client').'</td>';
 
1405       if ($report['show_project'])
 
1406         $body .= '<td style="'.$tableHeader.'">'.$i18n->getKey('label.project').'</td>';
 
1407       if ($report['show_task'])
 
1408         $body .= '<td style="'.$tableHeader.'">'.$i18n->getKey('label.task').'</td>';
 
1409       if ($report['show_custom_field_1'])
 
1410         $body .= '<td style="'.$tableHeader.'">'.htmlspecialchars($custom_fields->fields[0]['label']).'</td>';
 
1411       if ($report['show_start'])
 
1412         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->getKey('label.start').'</td>';
 
1413       if ($report['show_end'])
 
1414         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->getKey('label.finish').'</td>';
 
1415       if ($report['show_duration'])
 
1416         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->getKey('label.duration').'</td>';
 
1417       if ($report['show_note'])
 
1418         $body .= '<td style="'.$tableHeader.'">'.$i18n->getKey('label.note').'</td>';
 
1419       if ($report['show_cost'])
 
1420         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->getKey('label.cost').'</td>';
 
1421       if ($report['show_invoice'])
 
1422         $body .= '<td style="'.$tableHeader.'">'.$i18n->getKey('label.invoice').'</td>';
 
1425       // Initialize variables to print subtotals.
 
1426       if ($items && 'no_grouping' != $group_by) {
 
1427         $print_subtotals = true;
 
1429         $prev_grouped_by = '';
 
1430         $cur_grouped_by = '';
 
1432       // Initialize variables to alternate color of rows for different dates.
 
1435       $row_style = $rowItem;
 
1437       // Print report items.
 
1438       if (is_array($items)) {
 
1439         foreach ($items as $record) {
 
1440           $cur_date = $record['date'];
 
1441           // Print a subtotal row after a block of grouped items.
 
1442           if ($print_subtotals) {
 
1443             $cur_grouped_by = $record['grouped_by'];
 
1444             if ($cur_grouped_by != $prev_grouped_by && !$first_pass) {
 
1445               $body .= '<tr style="'.$rowSubtotal.'">';
 
1446               $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->getKey('label.subtotal').'</td>';
 
1447               $subtotal_name = htmlspecialchars($subtotals[$prev_grouped_by]['name']);
 
1448               if ($user->canManageTeam() || $user->isClient()) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'user' ? $subtotal_name : '').'</td>';
 
1449               if ($report['show_client']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'client' ? $subtotal_name : '').'</td>';
 
1450               if ($report['show_project']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'project' ? $subtotal_name : '').'</td>';
 
1451               if ($report['show_task']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'task' ? $subtotal_name : '').'</td>';
 
1452               if ($report['show_custom_field_1']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'cf_1' ? $subtotal_name : '').'</td>';
 
1453               if ($report['show_start']) $body .= '<td></td>';
 
1454               if ($report['show_end']) $body .= '<td></td>';
 
1455               if ($report['show_duration']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['time'].'</td>';
 
1456               if ($report['show_note']) $body .= '<td></td>';
 
1457               if ($report['show_cost']) {
 
1458                 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
 
1459                 $body .= ($user->canManageTeam() || $user->isClient()) ? $subtotals[$prev_grouped_by]['cost'] : $subtotals[$prev_grouped_by]['expenses'];
 
1462               if ($report['show_invoice']) $body .= '<td></td>';
 
1464               $body .= '<tr><td> </td></tr>';
 
1466             $first_pass = false;
 
1469           // Print a regular row.
 
1470           if ($cur_date != $prev_date)
 
1471             $row_style = ($row_style == $rowItem) ? $rowItemAlt : $rowItem;
 
1472           $body .= '<tr style="'.$row_style.'">';
 
1473           $body .= '<td style="'.$cellLeftAligned.'">'.$record['date'].'</td>';
 
1474           if ($user->canManageTeam() || $user->isClient())
 
1475             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['user']).'</td>';
 
1476           if ($report['show_client'])
 
1477             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['client']).'</td>';
 
1478           if ($report['show_project'])
 
1479             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['project']).'</td>';
 
1480           if ($report['show_task'])
 
1481             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['task']).'</td>';
 
1482           if ($report['show_custom_field_1'])
 
1483             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['cf_1']).'</td>';
 
1484           if ($report['show_start'])
 
1485             $body .= '<td nowrap style="'.$cellRightAligned.'">'.$record['start'].'</td>';
 
1486           if ($report['show_end'])
 
1487             $body .= '<td nowrap style="'.$cellRightAligned.'">'.$record['finish'].'</td>';
 
1488           if ($report['show_duration'])
 
1489             $body .= '<td style="'.$cellRightAligned.'">'.$record['duration'].'</td>';
 
1490           if ($report['show_note'])
 
1491             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['note']).'</td>';
 
1492           if ($report['show_cost'])
 
1493             $body .= '<td style="'.$cellRightAligned.'">'.$record['cost'].'</td>';
 
1494           if ($report['show_invoice'])
 
1495             $body .= '<td style="'.$cellRightAligned.'">'.htmlspecialchars($record['invoice']).'</td>';
 
1498           $prev_date = $record['date'];
 
1499           if ($print_subtotals)
 
1500             $prev_grouped_by = $record['grouped_by'];
 
1504       // Print a terminating subtotal.
 
1505       if ($print_subtotals) {
 
1506         $body .= '<tr style="'.$rowSubtotal.'">';
 
1507         $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->getKey('label.subtotal').'</td>';
 
1508         $subtotal_name = htmlspecialchars($subtotals[$cur_grouped_by]['name']);
 
1509         if ($user->canManageTeam() || $user->isClient()) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'user' ? $subtotal_name : '').'</td>';
 
1510         if ($report['show_client']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'client' ? $subtotal_name : '').'</td>';
 
1511         if ($report['show_project']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'project' ? $subtotal_name : '').'</td>';
 
1512         if ($report['show_task']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'task' ? $subtotal_name : '').'</td>';
 
1513         if ($report['show_custom_field_1']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'cf_1' ? $subtotal_name : '').'</td>';
 
1514         if ($report['show_start']) $body .= '<td></td>';
 
1515         if ($report['show_end']) $body .= '<td></td>';
 
1516         if ($report['show_duration']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$cur_grouped_by]['time'].'</td>';
 
1517         if ($report['show_note']) $body .= '<td></td>';
 
1518         if ($report['show_cost']) {
 
1519           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
 
1520           $body .= ($user->canManageTeam() || $user->isClient()) ? $subtotals[$cur_grouped_by]['cost'] : $subtotals[$cur_grouped_by]['expenses'];
 
1523         if ($report['show_invoice']) $body .= '<td></td>';
 
1528       $body .= '<tr><td> </td></tr>';
 
1529       $body .= '<tr style="'.$rowSubtotal.'">';
 
1530       $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->getKey('label.total').'</td>';
 
1531       if ($user->canManageTeam() || $user->isClient()) $body .= '<td></td>';
 
1532       if ($report['show_client']) $body .= '<td></td>';
 
1533       if ($report['show_project']) $body .= '<td></td>';
 
1534       if ($report['show_task']) $body .= '<td></td>';
 
1535       if ($report['show_custom_field_1']) $body .= '<td></td>';
 
1536       if ($report['show_start']) $body .= '<td></td>';
 
1537       if ($report['show_end']) $body .= '<td></td>';
 
1538       if ($report['show_duration']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$totals['time'].'</td>';
 
1539       if ($report['show_note']) $body .= '<td></td>';
 
1540       if ($report['show_cost']) {
 
1541         $body .= '<td nowrap style="'.$cellRightAlignedSubtotal.'">'.htmlspecialchars($user->currency).' ';
 
1542         $body .= ($user->canManageTeam() || $user->isClient()) ? $totals['cost'] : $totals['expenses'];
 
1545       if ($report['show_invoice']) $body .= '<td></td>';
 
1548       $body .= '</table>';
 
1552     if (!defined('REPORT_FOOTER') || !(REPORT_FOOTER == false))
 
1553       $body .= '<p style="text-align: center;">'.$i18n->getKey('form.mail.footer').'</p>';
 
1555     // Finish creating email body.
 
1556     $body .= '</body></html>';
 
1561   // sendFavReport - sends a favorite report to a specified email, called from cron.php
 
1562   static function sendFavReport($report, $email) {
 
1563     // We are called from cron.php, we have no $bean in session.
 
1564     // cron.php set global $user and $i18n objects to match our favorite report user.
 
1568     // Prepare report body.
 
1569     $body = ttReportHelper::prepareFavReportBody($report);
 
1571     import('mail.Mailer');
 
1572     $mailer = new Mailer();
 
1573     $mailer->setCharSet(CHARSET);
 
1574     $mailer->setContentType('text/html');
 
1575     $mailer->setSender(SENDER);
 
1576     $mailer->setReceiver($email);
 
1577     $mailer->setMailMode(MAIL_MODE);
 
1578     if (!$mailer->send($report['name'], $body))