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 // Definitions of types for timesheet dropdown.
 
  37 define('TIMESHEET_ALL', 0); // Include all records.
 
  38 define('TIMESHEET_NOT_ASSIGNED', 1); // Include records not assigned to timesheets.
 
  39 define('TIMESHEET_ASSIGNED', 2); // Include records assigned to timesheets.
 
  40 define('TIMESHEET_PENDING', 3); // Include records in submitted timesheets that are pending manager approval.
 
  41 define('TIMESHEET_APPROVED', 4); // Include records in approved timesheets.
 
  42 define('TIMESHEET_NOT_APPROVED', 5); // Include records in disapproved timesheets.
 
  44 // Class ttReportHelper is used for help with reports.
 
  45 class ttReportHelper {
 
  47   // getWhere prepares a WHERE clause for a report query.
 
  48   static function getWhere($options) {
 
  51     $group_id = $user->getGroup();
 
  52     $org_id = $user->org_id;
 
  54     // A shortcut for timesheets.
 
  55     if ($options['timesheet_id']) {
 
  56       $where = " where l.timesheet_id = ".$options['timesheet_id']." and l.group_id = $group_id and l.org_id = $org_id";
 
  60     // Prepare dropdown parts.
 
  62     if ($options['client_id'])
 
  63       $dropdown_parts .= ' and l.client_id = '.$options['client_id'];
 
  64     elseif ($user->isClient() && $user->client_id)
 
  65       $dropdown_parts .= ' and l.client_id = '.$user->client_id;
 
  66     if ($options['cf_1_option_id']) $dropdown_parts .= ' and l.id in(select log_id from tt_custom_field_log where status = 1 and option_id = '.$options['cf_1_option_id'].')';
 
  67     if ($options['project_id']) $dropdown_parts .= ' and l.project_id = '.$options['project_id'];
 
  68     if ($options['task_id']) $dropdown_parts .= ' and l.task_id = '.$options['task_id'];
 
  69     if ($options['billable']=='1') $dropdown_parts .= ' and l.billable = 1';
 
  70     if ($options['billable']=='2') $dropdown_parts .= ' and l.billable = 0';
 
  71     if ($options['invoice']=='1') $dropdown_parts .= ' and l.invoice_id is not null';
 
  72     if ($options['invoice']=='2') $dropdown_parts .= ' and l.invoice_id is null';
 
  73     if ($options['timesheet']==TIMESHEET_NOT_ASSIGNED) $dropdown_parts .= ' and l.timesheet_id is null';
 
  74     if ($options['timesheet']==TIMESHEET_ASSIGNED) $dropdown_parts .= ' and l.timesheet_id is not null';
 
  75     if ($options['paid_status']=='1') $dropdown_parts .= ' and l.paid = 1';
 
  76     if ($options['paid_status']=='2') $dropdown_parts .= ' and l.paid = 0';
 
  78     // Prepare sql query part for user list.
 
  79     $userlist = $options['users'] ? $options['users'] : '-1';
 
  80     if ($user->can('view_reports') || $user->can('view_all_reports') || $user->isClient())
 
  81       $user_list_part = " and l.user_id in ($userlist)";
 
  83       $user_list_part = " and l.user_id = ".$user->getUser();
 
  84     $user_list_part .= " and l.group_id = $group_id and l.org_id = $org_id";
 
  86     // Prepare sql query part for where.
 
  87     $dateFormat = $user->getDateFormat();
 
  88     if ($options['period'])
 
  89       $period = new Period($options['period'], new DateAndTime($dateFormat));
 
  91       $period = new Period();
 
  93         new DateAndTime($dateFormat, $options['period_start']),
 
  94         new DateAndTime($dateFormat, $options['period_end']));
 
  96     $where = " where l.status = 1 and l.date >= '".$period->getStartDate(DB_DATEFORMAT)."' and l.date <= '".$period->getEndDate(DB_DATEFORMAT)."'".
 
  97       " $user_list_part $dropdown_parts";
 
 101   // getExpenseWhere prepares WHERE clause for expenses query in a report.
 
 102   static function getExpenseWhere($options) {
 
 105     $group_id = $user->getGroup();
 
 106     $org_id = $user->org_id;
 
 108     // A shortcut for timesheets.
 
 109     if ($options['timesheet_id']) {
 
 110       $where = " where ei.timesheet_id = ".$options['timesheet_id']." and ei.group_id = $group_id and ei.org_id = $org_id";
 
 114     // Prepare dropdown parts.
 
 115     $dropdown_parts = '';
 
 116     if ($options['client_id'])
 
 117       $dropdown_parts .= ' and ei.client_id = '.$options['client_id'];
 
 118     elseif ($user->isClient() && $user->client_id)
 
 119       $dropdown_parts .= ' and ei.client_id = '.$user->client_id;
 
 120     if ($options['project_id']) $dropdown_parts .= ' and ei.project_id = '.$options['project_id'];
 
 121     if ($options['invoice']=='1') $dropdown_parts .= ' and ei.invoice_id is not null';
 
 122     if ($options['invoice']=='2') $dropdown_parts .= ' and ei.invoice_id is null';
 
 123     if ($options['timesheet']==TIMESHEET_NOT_ASSIGNED) $dropdown_parts .= ' and ei.timesheet_id is null';
 
 124     if ($options['timesheet']==TIMESHEET_ASSIGNED) $dropdown_parts .= ' and ei.timesheet_id is not null';
 
 125     if ($options['paid_status']=='1') $dropdown_parts .= ' and ei.paid = 1';
 
 126     if ($options['paid_status']=='2') $dropdown_parts .= ' and ei.paid = 0';
 
 128     // Prepare sql query part for user list.
 
 129     $userlist = $options['users'] ? $options['users'] : '-1';
 
 130     if ($user->can('view_reports') || $user->can('view_all_reports') || $user->isClient())
 
 131       $user_list_part = " and ei.user_id in ($userlist)";
 
 133       $user_list_part = " and ei.user_id = ".$user->getUser();
 
 134     $user_list_part .= " and ei.group_id = $group_id and ei.org_id = $org_id";
 
 136     // Prepare sql query part for where.
 
 137     $dateFormat = $user->getDateFormat();
 
 138     if ($options['period'])
 
 139       $period = new Period($options['period'], new DateAndTime($dateFormat));
 
 141       $period = new Period();
 
 143         new DateAndTime($dateFormat, $options['period_start']),
 
 144         new DateAndTime($dateFormat, $options['period_end']));
 
 146     $where = " where ei.status = 1 and ei.date >= '".$period->getStartDate(DB_DATEFORMAT)."' and ei.date <= '".$period->getEndDate(DB_DATEFORMAT)."'".
 
 147       " $user_list_part $dropdown_parts";
 
 151   // getItems retrieves all items associated with a report.
 
 152   // It combines tt_log and tt_expense_items in one array for presentation in one table using mysql union all.
 
 153   // Expense items use the "note" field for item name.
 
 154   static function getItems($options) {
 
 156     $mdb2 = getConnection();
 
 158     // Determine these once as they are used in multiple places in this function.
 
 159     $canViewReports = $user->can('view_reports') || $user->can('view_all_reports');
 
 160     $isClient = $user->isClient();
 
 162     $grouping = ttReportHelper::grouping($options);
 
 164       $grouping_by_date = ttReportHelper::groupingBy('date', $options);
 
 165       $grouping_by_client = ttReportHelper::groupingBy('client', $options);
 
 166       $grouping_by_project = ttReportHelper::groupingBy('project', $options);
 
 167       $grouping_by_task = ttReportHelper::groupingBy('task', $options);
 
 168       $grouping_by_user = ttReportHelper::groupingBy('user', $options);
 
 169       $grouping_by_cf_1 = ttReportHelper::groupingBy('cf_1', $options);
 
 171     $convertTo12Hour = ('%I:%M %p' == $user->getTimeFormat()) && ($options['show_start'] || $options['show_end']);
 
 172     $trackingMode = $user->getTrackingMode();
 
 173     $decimalMark = $user->getDecimalMark();
 
 175     // Prepare a query for time items in tt_log table.
 
 176     $fields = array(); // An array of fields for database query.
 
 177     array_push($fields, 'l.id');
 
 178     array_push($fields, 'l.user_id');
 
 179     array_push($fields, '1 as type'); // Type 1 is for tt_log entries.
 
 180     array_push($fields, 'l.date');
 
 181     if($canViewReports || $isClient)
 
 182       array_push($fields, 'u.name as user');
 
 183     // Add client name if it is selected.
 
 184     if ($options['show_client'] || $grouping_by_client)
 
 185       array_push($fields, 'c.name as client');
 
 186     // Add project name if it is selected.
 
 187     if ($options['show_project'] || $grouping_by_project)
 
 188       array_push($fields, 'p.name as project');
 
 189     // Add task name if it is selected.
 
 190     if ($options['show_task'] || $grouping_by_task)
 
 191       array_push($fields, 't.name as task');
 
 193     $include_cf_1 = $options['show_custom_field_1'] || $grouping_by_cf_1;
 
 195       $custom_fields = new CustomFields();
 
 196       $cf_1_type = $custom_fields->fields[0]['type'];
 
 197       if ($cf_1_type == CustomFields::TYPE_TEXT) {
 
 198         array_push($fields, 'cfl.value as cf_1');
 
 199       } elseif ($cf_1_type == CustomFields::TYPE_DROPDOWN) {
 
 200         array_push($fields, 'cfo.value as cf_1');
 
 204     if ($options['show_start']) {
 
 205       array_push($fields, "l.start as unformatted_start");
 
 206       array_push($fields, "TIME_FORMAT(l.start, '%k:%i') as start");
 
 209     if ($options['show_end'])
 
 210       array_push($fields, "TIME_FORMAT(sec_to_time(time_to_sec(l.start) + time_to_sec(l.duration)), '%k:%i') as finish");
 
 212     if ($options['show_duration'])
 
 213       array_push($fields, "TIME_FORMAT(l.duration, '%k:%i') as duration");
 
 215     if ($options['show_work_units']) {
 
 216       if ($user->getConfigOption('unit_totals_only'))
 
 217         array_push($fields, "null as units");
 
 219         $firstUnitThreshold = $user->getConfigInt('1st_unit_threshold', 0);
 
 220         $minutesInUnit = $user->getConfigInt('minutes_in_unit', 15);
 
 221         array_push($fields, "if(l.billable = 0 or time_to_sec(l.duration)/60 < $firstUnitThreshold, 0, ceil(time_to_sec(l.duration)/60/$minutesInUnit)) as units");
 
 225     if ($options['show_note'])
 
 226       array_push($fields, 'l.comment as note');
 
 228     $includeCost = $options['show_cost'];
 
 230       if (MODE_TIME == $trackingMode)
 
 231         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.
 
 233         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.
 
 234       array_push($fields, "null as expense"); 
 
 237     if ($canViewReports && $options['show_paid'])
 
 238       array_push($fields, 'l.paid');
 
 240     if ($canViewReports && $options['show_ip']) {
 
 241       array_push($fields, 'l.created');
 
 242       array_push($fields, 'l.created_ip');
 
 243       array_push($fields, 'l.modified');
 
 244       array_push($fields, 'l.modified_ip');
 
 246     // Add invoice name if it is selected.
 
 247     if (($canViewReports || $isClient) && $options['show_invoice'])
 
 248       array_push($fields, 'i.name as invoice');
 
 249     // Add timesheet name if it is selected.
 
 250     if ($options['show_timesheet'])
 
 251       array_push($fields, 'ts.name as timesheet_name');
 
 253     // Prepare sql query part for left joins.
 
 255     if ($options['show_client'] || $grouping_by_client)
 
 256       $left_joins .= " left join tt_clients c on (c.id = l.client_id)";
 
 257     if (($canViewReports || $isClient) && $options['show_invoice'])
 
 258       $left_joins .= " left join tt_invoices i on (i.id = l.invoice_id and i.status = 1)";
 
 259     if ($canViewReports || $isClient || $user->isPluginEnabled('ex'))
 
 260        $left_joins .= " left join tt_users u on (u.id = l.user_id)";
 
 261     if ($options['show_project'] || $grouping_by_project)
 
 262       $left_joins .= " left join tt_projects p on (p.id = l.project_id)";
 
 263     if ($options['show_task'] || $grouping_by_task)
 
 264       $left_joins .= " left join tt_tasks t on (t.id = l.task_id)";
 
 266       if ($cf_1_type == CustomFields::TYPE_TEXT)
 
 267         $left_joins .= " left join tt_custom_field_log cfl on (l.id = cfl.log_id and cfl.status = 1)";
 
 268       elseif ($cf_1_type == CustomFields::TYPE_DROPDOWN) {
 
 269         $left_joins .=  " left join tt_custom_field_log cfl on (l.id = cfl.log_id and cfl.status = 1)".
 
 270           " left join tt_custom_field_options cfo on (cfl.option_id = cfo.id)";
 
 273     if ($includeCost && MODE_TIME != $trackingMode)
 
 274       $left_joins .= " left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id)";
 
 276     // Prepare sql query part for inner joins.
 
 278     if ($user->isPluginEnabled('ts')) {
 
 279       $timesheet_option = $options['timesheet'];
 
 280       if ($timesheet_option == TIMESHEET_PENDING)
 
 281         $inner_joins .= " inner join tt_timesheets ts on (l.timesheet_id = ts.id and ts.submit_status = 1 and ts.approval_status is null)";
 
 282       else if ($timesheet_option == TIMESHEET_APPROVED)
 
 283         $inner_joins .= " inner join tt_timesheets ts on (l.timesheet_id = ts.id and ts.approval_status = 1)";
 
 284       else if ($timesheet_option == TIMESHEET_NOT_APPROVED)
 
 285         $inner_joins .= " inner join tt_timesheets ts on (l.timesheet_id = ts.id and ts.approval_status = 0)";
 
 286       else if ($options['show_timesheet'])
 
 287         $inner_joins .= " left join tt_timesheets ts on (l.timesheet_id = ts.id)"; // Left join for timesheet nme.
 
 290     $where = ttReportHelper::getWhere($options);
 
 292     // Construct sql query for tt_log items.
 
 293     $sql = "select ".join(', ', $fields)." from tt_log l $left_joins $inner_joins $where";
 
 294     // If we don't have expense items (such as when the Expenses plugin is disabled), the above is all sql we need,
 
 295     // with an exception of sorting part, that is added in the end.
 
 297     // However, when we have expenses, we need to do a union with a separate query for expense items from tt_expense_items table.
 
 298     if ($options['show_cost'] && $user->isPluginEnabled('ex')) { // if ex(penses) plugin is enabled
 
 300       $fields = array(); // An array of fields for database query.
 
 301       array_push($fields, 'ei.id');
 
 302       array_push($fields, 'ei.user_id');
 
 303       array_push($fields, '2 as type'); // Type 2 is for tt_expense_items entries.
 
 304       array_push($fields, 'ei.date');
 
 305       if($canViewReports || $isClient)
 
 306         array_push($fields, 'u.name as user');
 
 307       // Add client name if it is selected.
 
 308       if ($options['show_client'] || $grouping_by_client)
 
 309         array_push($fields, 'c.name as client');
 
 310       // Add project name if it is selected.
 
 311       if ($options['show_project'] || $grouping_by_project)
 
 312         array_push($fields, 'p.name as project');
 
 313       if ($options['show_task'] || $grouping_by_task)
 
 314         array_push($fields, 'null'); // null for task name. We need to match column count for union.
 
 315       if ($options['show_custom_field_1'] || $grouping_by_cf_1)
 
 316         array_push($fields, 'null'); // null for cf_1.
 
 317       if ($options['show_start']) {
 
 318         array_push($fields, 'null'); // null for unformatted_start.
 
 319         array_push($fields, 'null'); // null for start.
 
 321       if ($options['show_end'])
 
 322         array_push($fields, 'null'); // null for finish.
 
 323       if ($options['show_duration'])
 
 324         array_push($fields, 'null'); // null for duration.
 
 325       if ($options['show_work_units'])
 
 326         array_push($fields, 'null as units'); // null for work units.
 
 327       // Use the note field to print item name.
 
 328       if ($options['show_note'])
 
 329         array_push($fields, 'ei.name as note');
 
 330       array_push($fields, 'ei.cost as cost');
 
 331       array_push($fields, 'ei.cost as expense');
 
 333       if ($canViewReports && $options['show_paid'])
 
 334         array_push($fields, 'ei.paid');
 
 336       if ($canViewReports && $options['show_ip']) {
 
 337         array_push($fields, 'ei.created');
 
 338         array_push($fields, 'ei.created_ip');
 
 339         array_push($fields, 'ei.modified');
 
 340         array_push($fields, 'ei.modified_ip');
 
 342       // Add invoice name if it is selected.
 
 343       if (($canViewReports || $isClient) && $options['show_invoice'])
 
 344         array_push($fields, 'i.name as invoice');
 
 345       if ($options['show_timesheet'])
 
 346         array_push($fields, 'ts.name as timesheet_name');
 
 348       // Prepare sql query part for left joins.
 
 350       if ($canViewReports || $isClient)
 
 351         $left_joins .= " left join tt_users u on (u.id = ei.user_id)";
 
 352       if ($options['show_client'] || $grouping_by_client)
 
 353         $left_joins .= " left join tt_clients c on (c.id = ei.client_id)";
 
 354       if ($options['show_project'] || $grouping_by_project)
 
 355         $left_joins .= " left join tt_projects p on (p.id = ei.project_id)";
 
 356       if (($canViewReports || $isClient) && $options['show_invoice'])
 
 357         $left_joins .= " left join tt_invoices i on (i.id = ei.invoice_id and i.status = 1)";
 
 359       // Prepare sql query part for inner joins.
 
 361       if ($user->isPluginEnabled('ts')) {
 
 362         $timesheet_option = $options['timesheet'];
 
 363         if ($timesheet_option == TIMESHEET_PENDING)
 
 364           $inner_joins .= " inner join tt_timesheets ts on (ei.timesheet_id = ts.id and ts.submit_status = 1 and ts.approval_status is null)";
 
 365         else if ($timesheet_option == TIMESHEET_APPROVED)
 
 366           $inner_joins .= " inner join tt_timesheets ts on (ei.timesheet_id = ts.id and ts.approval_status = 1)";
 
 367         else if ($timesheet_option == TIMESHEET_NOT_APPROVED)
 
 368           $inner_joins .= " inner join tt_timesheets ts on (ei.timesheet_id = ts.id and ts.approval_status = 0)";
 
 369         else if ($options['show_timesheet'])
 
 370           $inner_joins .= " left join tt_timesheets ts on (ei.timesheet_id = ts.id)"; // Left join for timesheet name.
 
 373       $where = ttReportHelper::getExpenseWhere($options);
 
 375       // Construct sql query for expense items.
 
 376       $sql_for_expense_items = "select ".join(', ', $fields)." from tt_expense_items ei $left_joins $inner_joins $where";
 
 378       // Construct a union.
 
 379       $sql = "($sql) union all ($sql_for_expense_items)";
 
 382     // Determine sort part.
 
 383     $sort_part = ' order by ';
 
 385       $sort_part2 .= ($options['group_by1'] != null && $options['group_by1'] != 'no_grouping') ? ', '.$options['group_by1'] : '';
 
 386       $sort_part2 .= ($options['group_by2'] != null && $options['group_by2'] != 'no_grouping') ? ', '.$options['group_by2'] : '';
 
 387       $sort_part2 .= ($options['group_by3'] != null && $options['group_by3'] != 'no_grouping') ? ', '.$options['group_by3'] : '';
 
 388       if (!$grouping_by_date) $sort_part2 .= ', date';
 
 389       $sort_part .= ltrim($sort_part2, ', '); // Remove leading comma and space.
 
 391       $sort_part .= 'date';
 
 393     if (($canViewReports || $isClient) && $options['users'] && !$grouping_by_user)
 
 394       $sort_part .= ', user, type';
 
 395     if ($options['show_start'])
 
 396       $sort_part .= ', unformatted_start';
 
 397     $sort_part .= ', id';
 
 400     // By now we are ready with sql.
 
 402     // Obtain items for report.
 
 403     $res = $mdb2->query($sql);
 
 404     if (is_a($res, 'PEAR_Error')) die($res->getMessage());
 
 406     while ($val = $res->fetchRow()) {
 
 407       if ($convertTo12Hour) {
 
 408         if($val['start'] != '')
 
 409           $val['start'] = ttTimeHelper::to12HourFormat($val['start']);
 
 410         if($val['finish'] != '')
 
 411           $val['finish'] = ttTimeHelper::to12HourFormat($val['finish']);
 
 413       if (isset($val['cost'])) {
 
 414         if ('.' != $decimalMark)
 
 415           $val['cost'] = str_replace('.', $decimalMark, $val['cost']);
 
 417       if (isset($val['expense'])) {
 
 418         if ('.' != $decimalMark)
 
 419           $val['expense'] = str_replace('.', $decimalMark, $val['expense']);
 
 422       if ($grouping) $val['grouped_by'] = ttReportHelper::makeGroupByKey($options, $val);
 
 423       $val['date'] = ttDateToUserFormat($val['date']);
 
 425       $report_items[] = $val;
 
 428     return $report_items;
 
 431   // putInSession stores tt_log and tt_expense_items ids from a report in user session
 
 432   // as 2 comma-separated lists.
 
 433   static function putInSession($report_items) {
 
 434     unset($_SESSION['report_item_ids']);
 
 435     unset($_SESSION['report_item_expense_ids']);
 
 437     // Iterate through records and build 2 comma-separated lists.
 
 438     foreach($report_items as $item) {
 
 439       if ($item['type'] == 1)
 
 440         $report_item_ids .= ','.$item['id'];
 
 441       else if ($item['type'] == 2)
 
 442          $report_item_expense_ids .= ','.$item['id'];
 
 444     $report_item_ids = trim($report_item_ids, ',');
 
 445     $report_item_expense_ids = trim($report_item_expense_ids, ',');
 
 447     // The lists are reqdy. Put them in session.
 
 448     if ($report_item_ids) $_SESSION['report_item_ids'] = $report_item_ids;
 
 449     if ($report_item_expense_ids) $_SESSION['report_item_expense_ids'] = $report_item_expense_ids;
 
 452   // getFromSession obtains tt_log and tt_expense_items ids stored in user session.
 
 453   static function getFromSession() {
 
 455     $report_item_ids = $_SESSION['report_item_ids'];
 
 456     if ($report_item_ids)
 
 457       $items['report_item_ids'] = explode(',', $report_item_ids);
 
 458     $report_item_expense_ids = $_SESSION['report_item_expense_ids'];
 
 459     if ($report_item_expense_ids)
 
 460       $items['report_item_expense_ids'] = explode(',', $report_item_expense_ids);
 
 464   // getSubtotals calculates report items subtotals when a report is grouped by.
 
 465   // Without expenses, it's a simple select with group by.
 
 466   // With expenses, it becomes a select with group by from a combined set of records obtained with "union all".
 
 467   static function getSubtotals($options) {
 
 469     $mdb2 = getConnection();
 
 471     $concat_part = ttReportHelper::makeConcatPart($options);
 
 472     $work_unit_part = ttReportHelper::makeWorkUnitPart($options);
 
 473     $join_part = ttReportHelper::makeJoinPart($options);
 
 474     $cost_part = ttReportHelper::makeCostPart($options);
 
 475     $where = ttReportHelper::getWhere($options);
 
 476     $group_by_part = ttReportHelper::makeGroupByPart($options);
 
 478     $parts = "$concat_part, sum(time_to_sec(l.duration)) as time, null as expenses".$work_unit_part.$cost_part;
 
 479     $sql = "select $parts from tt_log l $join_part $where $group_by_part";
 
 480     // By now we have sql for time items.
 
 482     // However, when we have expenses, we need to do a union with a separate query for expense items from tt_expense_items table.
 
 483     if ($options['show_cost'] && $user->isPluginEnabled('ex')) { // if ex(penses) plugin is enabled
 
 485       $concat_part = ttReportHelper::makeConcatExpensesPart($options);
 
 486       $join_part = ttReportHelper::makeJoinExpensesPart($options);
 
 487       $where = ttReportHelper::getExpenseWhere($options);
 
 488       $group_by_expenses_part = ttReportHelper::makeGroupByExpensesPart($options);
 
 489       $sql_for_expenses = "select $concat_part, null as time";
 
 490       if ($options['show_work_units']) $sql_for_expenses .= ", null as units";
 
 491       $sql_for_expenses .= ", sum(ei.cost) as cost, sum(ei.cost) as expenses from tt_expense_items ei $join_part $where $group_by_expenses_part";
 
 493       // Create a combined query.
 
 494       $fields = ttReportHelper::makeCombinedSelectPart($options);
 
 495       $combined = "select $fields, sum(time) as time";
 
 496       if ($options['show_work_units']) $combined .= ", sum(units) as units";
 
 497       $combined .= ", sum(cost) as cost, sum(expenses) as expenses from (($sql) union all ($sql_for_expenses)) t group by $fields";
 
 502     $res = $mdb2->query($sql);
 
 503     if (is_a($res, 'PEAR_Error')) die($res->getMessage());
 
 504     while ($val = $res->fetchRow()) {
 
 505       $time = $val['time'] ? sec_to_time_fmt_hm($val['time']) : null;
 
 506       $rowLabel = ttReportHelper::makeGroupByLabel($val['group_field'], $options);
 
 507       if ($options['show_cost']) {
 
 508         $decimalMark = $user->getDecimalMark();
 
 509         if ('.' != $decimalMark) {
 
 510           $val['cost'] = str_replace('.', $decimalMark, $val['cost']);
 
 511           $val['expenses'] = str_replace('.', $decimalMark, $val['expenses']);
 
 513         $subtotals[$val['group_field']] = array('name'=>$rowLabel,'user'=>$val['user'],'project'=>$val['project'],'task'=>$val['task'],'client'=>$val['client'],'cf_1'=>$val['cf_1'],'time'=>$time,'units'=> $val['units'],'cost'=>$val['cost'],'expenses'=>$val['expenses']);
 
 515         $subtotals[$val['group_field']] = array('name'=>$rowLabel,'user'=>$val['user'],'project'=>$val['project'],'task'=>$val['task'],'client'=>$val['client'],'cf_1'=>$val['cf_1'],'time'=>$time, 'units'=> $val['units']);
 
 521   // getTotals calculates total hours and cost for all report items.
 
 522   static function getTotals($options)
 
 525     $mdb2 = getConnection();
 
 527     $trackingMode = $user->getTrackingMode();
 
 528     $decimalMark = $user->getDecimalMark();
 
 529     $where = ttReportHelper::getWhere($options);
 
 532     $time_part = "sum(time_to_sec(l.duration)) as time";
 
 533     if ($options['show_work_units']) {
 
 534       $unitTotalsOnly = $user->getConfigOption('unit_totals_only');
 
 535       $firstUnitThreshold = $user->getConfigInt('1st_unit_threshold', 0);
 
 536       $minutesInUnit = $user->getConfigInt('minutes_in_unit', 15);
 
 537       $units_part = $unitTotalsOnly ? ", null as units" : ", sum(if(l.billable = 0 or time_to_sec(l.duration)/60 < $firstUnitThreshold, 0, ceil(time_to_sec(l.duration)/60/$minutesInUnit))) as units";
 
 539     if ($options['show_cost']) {
 
 540       if (MODE_TIME == $trackingMode)
 
 541         $cost_part = ", sum(cast(l.billable * coalesce(u.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10,2))) as cost, null as expenses";
 
 543         $cost_part = ", sum(cast(l.billable * coalesce(upb.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10,2))) as cost, null as expenses";
 
 545       $cost_part = ", null as cost, null as expenses";
 
 547     if ($options['show_cost']) {
 
 548       if (MODE_TIME == $trackingMode) {
 
 549         $left_joins = "left join tt_users u on (l.user_id = u.id)";
 
 551         $left_joins = "left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id)";
 
 554     // Prepare sql query part for inner joins.
 
 556     if ($user->isPluginEnabled('ts') && $options['timesheet']) {
 
 557       $timesheet_option = $options['timesheet'];
 
 558       if ($timesheet_option == TIMESHEET_PENDING)
 
 559         $inner_joins .= " inner join tt_timesheets ts on (l.timesheet_id = ts.id and ts.submit_status = 1 and ts.approval_status is null)";
 
 560       else if ($timesheet_option == TIMESHEET_APPROVED)
 
 561         $inner_joins .= " inner join tt_timesheets ts on (l.timesheet_id = ts.id and ts.approval_status = 1)";
 
 562       else if ($timesheet_option == TIMESHEET_NOT_APPROVED)
 
 563         $inner_joins .= " inner join tt_timesheets ts on (l.timesheet_id = ts.id and ts.approval_status = 0)";
 
 565     // Prepare a query for time items.
 
 566     $sql = "select $time_part $units_part $cost_part from tt_log l $left_joins $inner_joins $where";
 
 568     // If we have expenses, query becomes a bit more complex.
 
 569     if ($options['show_cost'] && $user->isPluginEnabled('ex')) {
 
 570       // Prepare sql query part for inner joins.
 
 572       if ($user->isPluginEnabled('ts') && $options['timesheet']) {
 
 573         $timesheet_option = $options['timesheet'];
 
 574         if ($timesheet_option == TIMESHEET_PENDING)
 
 575           $inner_joins .= " inner join tt_timesheets ts on (ei.timesheet_id = ts.id and ts.submit_status = 1 and ts.approval_status is null)";
 
 576         else if ($timesheet_option == TIMESHEET_APPROVED)
 
 577           $inner_joins .= " inner join tt_timesheets ts on (ei.timesheet_id = ts.id and ts.approval_status = 1)";
 
 578         else if ($timesheet_option == TIMESHEET_NOT_APPROVED)
 
 579           $inner_joins .= " inner join tt_timesheets ts on (ei.timesheet_id = ts.id and ts.approval_status = 0)";
 
 581       $where = ttReportHelper::getExpenseWhere($options);
 
 582       $sql_for_expenses = "select null as time";
 
 583       if ($options['show_work_units']) $sql_for_expenses .= ", null as units";
 
 584       $sql_for_expenses .= ", sum(cost) as cost, sum(cost) as expenses from tt_expense_items ei $inner_joins $where";
 
 586       // Create a combined query.
 
 587       $combined = "select sum(time) as time";
 
 588       if ($options['show_work_units']) $combined .= ", sum(units) as units";
 
 589       $combined .= ", sum(cost) as cost, sum(expenses) as expenses from (($sql) union all ($sql_for_expenses)) t";
 
 594     $res = $mdb2->query($sql);
 
 595     if (is_a($res, 'PEAR_Error')) die($res->getMessage());
 
 597     $val = $res->fetchRow();
 
 598     $total_time = $val['time'] ? sec_to_time_fmt_hm($val['time']) : null;
 
 599     if ($options['show_cost']) {
 
 600       $total_cost = $val['cost'];
 
 601       if (!$total_cost) $total_cost = '0.00';
 
 602       if ('.' != $decimalMark)
 
 603         $total_cost = str_replace('.', $decimalMark, $total_cost);
 
 604       $total_expenses = $val['expenses'];
 
 605       if (!$total_expenses) $total_expenses = '0.00';
 
 606       if ('.' != $decimalMark)
 
 607         $total_expenses = str_replace('.', $decimalMark, $total_expenses);
 
 610     $dateFormat = $user->getDateFormat();
 
 611     if ($options['period'])
 
 612       $period = new Period($options['period'], new DateAndTime($dateFormat));
 
 614       $period = new Period();
 
 616         new DateAndTime($dateFormat, $options['period_start']),
 
 617         new DateAndTime($dateFormat, $options['period_end']));
 
 620     $totals['start_date'] = $period->getStartDate();
 
 621     $totals['end_date'] = $period->getEndDate();
 
 622     $totals['time'] = $total_time;
 
 623     $totals['units'] = $val['units'];
 
 624     $totals['cost'] = $total_cost;
 
 625     $totals['expenses'] = $total_expenses;
 
 630   // The assignToInvoice assigns a set of records to a specific invoice.
 
 631   static function assignToInvoice($invoice_id, $time_log_ids, $expense_item_ids) {
 
 633     $mdb2 = getConnection();
 
 635     $group_id = $user->getGroup();
 
 636     $org_id = $user->org_id;
 
 639       $sql = "update tt_log set invoice_id = ".$mdb2->quote($invoice_id).
 
 640         " where id in(".join(', ', $time_log_ids).") and group_id = $group_id and org_id = $org_id";
 
 641       $affected = $mdb2->exec($sql);
 
 642       if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
 
 644     if ($expense_item_ids) {
 
 645       $sql = "update tt_expense_items set invoice_id = ".$mdb2->quote($invoice_id).
 
 646         " where id in(".join(', ', $expense_item_ids).") and group_id = $group_id and org_id = $org_id";
 
 647       $affected = $mdb2->exec($sql);
 
 648       if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
 
 652   // The markPaid marks a set of records as either paid or unpaid.
 
 653   static function markPaid($time_log_ids, $expense_item_ids, $paid = true) {
 
 655     $mdb2 = getConnection();
 
 657     $group_id = $user->getGroup();
 
 658     $org_id = $user->org_id;
 
 660     $paid_val = (int) $paid;
 
 662       $sql = "update tt_log set paid = $paid_val".
 
 663         " where id in(".join(', ', $time_log_ids).") and group_id = $group_id and org_id = $org_id";
 
 664       $affected = $mdb2->exec($sql);
 
 665       if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
 
 667     if ($expense_item_ids) {
 
 668       $sql = "update tt_expense_items set paid = $paid_val".
 
 669         " where id in(".join(', ', $expense_item_ids).") and group_id = $group_id and org_id = $org_id";
 
 670       $affected = $mdb2->exec($sql);
 
 671       if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
 
 675   // prepareReportBody - prepares an email body for report.
 
 676   static function prepareReportBody($options, $comment = null)
 
 681     // Determine these once as they are used in multiple places in this function.
 
 682     $canViewReports = $user->can('view_reports') || $user->can('view_all_reports');
 
 683     $isClient = $user->isClient();
 
 685     $items = ttReportHelper::getItems($options);
 
 686     $grouping = ttReportHelper::grouping($options);
 
 688       $subtotals = ttReportHelper::getSubtotals($options);
 
 689     $totals = ttReportHelper::getTotals($options);
 
 691     // Use custom fields plugin if it is enabled.
 
 692     if ($user->isPluginEnabled('cf'))
 
 693       $custom_fields = new CustomFields();
 
 695     // Define some styles to use in email.
 
 696     $style_title = 'text-align: center; font-size: 15pt; font-family: Arial, Helvetica, sans-serif;';
 
 697     $tableHeader = 'font-weight: bold; background-color: #a6ccf7; text-align: left;';
 
 698     $tableHeaderCentered = 'font-weight: bold; background-color: #a6ccf7; text-align: center;';
 
 699     $rowItem = 'background-color: #ffffff;';
 
 700     $rowItemAlt = 'background-color: #f5f5f5;';
 
 701     $rowSubtotal = 'background-color: #e0e0e0;';
 
 702     $cellLeftAligned = 'text-align: left; vertical-align: top;';
 
 703     $cellRightAligned = 'text-align: right; vertical-align: top;';
 
 704     $cellLeftAlignedSubtotal = 'font-weight: bold; text-align: left; vertical-align: top;';
 
 705     $cellRightAlignedSubtotal = 'font-weight: bold; text-align: right; vertical-align: top;';
 
 707     // Start creating email body.
 
 709     $body .= '<head><meta http-equiv="content-type" content="text/html; charset='.CHARSET.'"></head>';
 
 713     $body .= '<p style="'.$style_title.'">'.$i18n->get('form.mail.report_subject').': '.$totals['start_date'].' - '.$totals['end_date'].'</p>';
 
 716     if ($comment) $body .= '<p>'.htmlspecialchars($comment).'</p>';
 
 718     if ($options['show_totals_only']) {
 
 719       // Totals only report. Output subtotals.
 
 720       $group_by_header = ttReportHelper::makeGroupByHeader($options);
 
 722       $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
 
 724       $body .= '<td style="'.$tableHeader.'">'.$group_by_header.'</td>';
 
 725       if ($options['show_duration'])
 
 726         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.duration').'</td>';
 
 727       if ($options['show_work_units'])
 
 728         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.work_units_short').'</td>';
 
 729       if ($options['show_cost'])
 
 730         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.cost').'</td>';
 
 732       foreach($subtotals as $subtotal) {
 
 733         $body .= '<tr style="'.$rowSubtotal.'">';
 
 734         $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($subtotal['name'] ? htmlspecialchars($subtotal['name']) : ' ').'</td>';
 
 735         if ($options['show_duration']) {
 
 736           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
 
 737           if ($subtotal['time'] <> '0:00') $body .= $subtotal['time'];
 
 740         if ($options['show_work_units']) {
 
 741           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
 
 742           $body .= $subtotal['units'];
 
 745         if ($options['show_cost']) {
 
 746           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
 
 747           $body .= ($canViewReports || $isClient) ? $subtotal['cost'] : $subtotal['expenses'];
 
 754       $body .= '<tr><td> </td></tr>';
 
 755       $body .= '<tr style="'.$rowSubtotal.'">';
 
 756       $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.total').'</td>';
 
 757       if ($options['show_duration']) {
 
 758         $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
 
 759         if ($totals['time'] <> '0:00') $body .= $totals['time'];
 
 762       if ($options['show_work_units']) {
 
 763         $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
 
 764         $body .= $totals['units'];
 
 767       if ($options['show_cost']) {
 
 768         $body .= '<td nowrap style="'.$cellRightAlignedSubtotal.'">'.htmlspecialchars($user->currency).' ';
 
 769         $body .= ($canViewReports || $isClient) ? $totals['cost'] : $totals['expenses'];
 
 778       // Print table header.
 
 779       $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
 
 781       $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.date').'</td>';
 
 782       if ($canViewReports || $isClient)
 
 783         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.user').'</td>';
 
 784       if ($options['show_client'])
 
 785         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.client').'</td>';
 
 786       if ($options['show_project'])
 
 787         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.project').'</td>';
 
 788       if ($options['show_task'])
 
 789         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.task').'</td>';
 
 790       if ($options['show_custom_field_1'])
 
 791         $body .= '<td style="'.$tableHeader.'">'.htmlspecialchars($custom_fields->fields[0]['label']).'</td>';
 
 792       if ($options['show_start'])
 
 793         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.start').'</td>';
 
 794       if ($options['show_end'])
 
 795         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.finish').'</td>';
 
 796       if ($options['show_duration'])
 
 797         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.duration').'</td>';
 
 798       if ($options['show_work_units'])
 
 799         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.work_units_short').'</td>';
 
 800       if ($options['show_note'])
 
 801         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.note').'</td>';
 
 802       if ($options['show_cost'])
 
 803         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.cost').'</td>';
 
 804       if ($options['show_paid'])
 
 805         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.paid').'</td>';
 
 806       if ($options['show_ip'])
 
 807         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.ip').'</td>';
 
 808       if ($options['show_invoice'])
 
 809         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.invoice').'</td>';
 
 812       // Initialize variables to print subtotals.
 
 813       if ($items && $grouping) {
 
 814         $print_subtotals = true;
 
 816         $prev_grouped_by = '';
 
 817         $cur_grouped_by = '';
 
 819       // Initialize variables to alternate color of rows for different dates.
 
 822       $row_style = $rowItem;
 
 824       // Print report items.
 
 825       if (is_array($items)) {
 
 826         foreach ($items as $record) {
 
 827           $cur_date = $record['date'];
 
 828           // Print a subtotal row after a block of grouped items.
 
 829           if ($print_subtotals) {
 
 830             $cur_grouped_by = $record['grouped_by'];
 
 831             if ($cur_grouped_by != $prev_grouped_by && !$first_pass) {
 
 832               $body .= '<tr style="'.$rowSubtotal.'">';
 
 833               $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.subtotal').'</td>';
 
 834               $subtotal_name = htmlspecialchars($subtotals[$prev_grouped_by]['name']);
 
 835               if ($canViewReports || $isClient) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['user'].'</td>';
 
 836               if ($options['show_client']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['client'].'</td>';
 
 837               if ($options['show_project']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['project'].'</td>';
 
 838               if ($options['show_task']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['task'].'</td>';
 
 839               if ($options['show_custom_field_1']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['cf_1'].'</td>';
 
 840               if ($options['show_start']) $body .= '<td></td>';
 
 841               if ($options['show_end']) $body .= '<td></td>';
 
 842               if ($options['show_duration']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['time'].'</td>';
 
 843               if ($options['show_work_units']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['units'].'</td>';
 
 844               if ($options['show_note']) $body .= '<td></td>';
 
 845               if ($options['show_cost']) {
 
 846                 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
 
 847                 $body .= ($canViewReports || $isClient) ? $subtotals[$prev_grouped_by]['cost'] : $subtotals[$prev_grouped_by]['expenses'];
 
 850               if ($options['show_paid']) $body .= '<td></td>';
 
 851               if ($options['show_ip']) $body .= '<td></td>';
 
 852               if ($options['show_invoice']) $body .= '<td></td>';
 
 854               $body .= '<tr><td> </td></tr>';
 
 859           // Print a regular row.
 
 860           if ($cur_date != $prev_date)
 
 861             $row_style = ($row_style == $rowItem) ? $rowItemAlt : $rowItem;
 
 862           $body .= '<tr style="'.$row_style.'">';
 
 863           $body .= '<td style="'.$cellLeftAligned.'">'.$record['date'].'</td>';
 
 864           if ($canViewReports || $isClient)
 
 865             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['user']).'</td>';
 
 866           if ($options['show_client'])
 
 867             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['client']).'</td>';
 
 868           if ($options['show_project'])
 
 869             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['project']).'</td>';
 
 870           if ($options['show_task'])
 
 871             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['task']).'</td>';
 
 872           if ($options['show_custom_field_1'])
 
 873             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['cf_1']).'</td>';
 
 874           if ($options['show_start'])
 
 875             $body .= '<td nowrap style="'.$cellRightAligned.'">'.$record['start'].'</td>';
 
 876           if ($options['show_end'])
 
 877             $body .= '<td nowrap style="'.$cellRightAligned.'">'.$record['finish'].'</td>';
 
 878           if ($options['show_duration'])
 
 879             $body .= '<td style="'.$cellRightAligned.'">'.$record['duration'].'</td>';
 
 880           if ($options['show_work_units'])
 
 881             $body .= '<td style="'.$cellRightAligned.'">'.$record['units'].'</td>';
 
 882           if ($options['show_note'])
 
 883             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['note']).'</td>';
 
 884           if ($options['show_cost'])
 
 885             $body .= '<td style="'.$cellRightAligned.'">'.$record['cost'].'</td>';
 
 886           if ($options['show_paid']) {
 
 887             $body .= '<td style="'.$cellRightAligned.'">';
 
 888             $body .= $record['paid'] == 1 ? $i18n->get('label.yes') : $i18n->get('label.no');
 
 891           if ($options['show_ip']) {
 
 892             $body .= '<td style="'.$cellRightAligned.'">';
 
 893             $body .= $record['modified'] ? $record['modified_ip'].' '.$record['modified'] : $record['created_ip'].' '.$record['created'];
 
 896           if ($options['show_invoice'])
 
 897             $body .= '<td style="'.$cellRightAligned.'">'.htmlspecialchars($record['invoice']).'</td>';
 
 900           $prev_date = $record['date'];
 
 901           if ($print_subtotals)
 
 902             $prev_grouped_by = $record['grouped_by'];
 
 906       // Print a terminating subtotal.
 
 907       if ($print_subtotals) {
 
 908         $body .= '<tr style="'.$rowSubtotal.'">';
 
 909         $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.subtotal').'</td>';
 
 910         $subtotal_name = htmlspecialchars($subtotals[$cur_grouped_by]['name']);
 
 911         if ($canViewReports || $isClient) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['user'].'</td>';
 
 912         if ($options['show_client']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['client'].'</td>';
 
 913         if ($options['show_project']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['project'].'</td>';
 
 914         if ($options['show_task']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['task'].'</td>';
 
 915         if ($options['show_custom_field_1']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['cf_1'].'</td>';
 
 916         if ($options['show_start']) $body .= '<td></td>';
 
 917         if ($options['show_end']) $body .= '<td></td>';
 
 918         if ($options['show_duration']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$cur_grouped_by]['time'].'</td>';
 
 919         if ($options['show_work_units']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$cur_grouped_by]['units'].'</td>';
 
 920         if ($options['show_note']) $body .= '<td></td>';
 
 921         if ($options['show_cost']) {
 
 922           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
 
 923           $body .= ($canViewReports || $isClient) ? $subtotals[$cur_grouped_by]['cost'] : $subtotals[$cur_grouped_by]['expenses'];
 
 926         if ($options['show_paid']) $body .= '<td></td>';
 
 927         if ($options['show_ip']) $body .= '<td></td>';
 
 928         if ($options['show_invoice']) $body .= '<td></td>';
 
 933       $body .= '<tr><td> </td></tr>';
 
 934       $body .= '<tr style="'.$rowSubtotal.'">';
 
 935       $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.total').'</td>';
 
 936       if ($canViewReports || $isClient) $body .= '<td></td>';
 
 937       if ($options['show_client']) $body .= '<td></td>';
 
 938       if ($options['show_project']) $body .= '<td></td>';
 
 939       if ($options['show_task']) $body .= '<td></td>';
 
 940       if ($options['show_custom_field_1']) $body .= '<td></td>';
 
 941       if ($options['show_start']) $body .= '<td></td>';
 
 942       if ($options['show_end']) $body .= '<td></td>';
 
 943       if ($options['show_duration']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$totals['time'].'</td>';
 
 944       if ($options['show_work_units']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$totals['units'].'</td>';
 
 945       if ($options['show_note']) $body .= '<td></td>';
 
 946       if ($options['show_cost']) {
 
 947         $body .= '<td nowrap style="'.$cellRightAlignedSubtotal.'">'.htmlspecialchars($user->currency).' ';
 
 948         $body .= ($canViewReports || $isClient) ? $totals['cost'] : $totals['expenses'];
 
 951       if ($options['show_paid']) $body .= '<td></td>';
 
 952       if ($options['show_ip']) $body .= '<td></td>';
 
 953       if ($options['show_invoice']) $body .= '<td></td>';
 
 960     if (!defined('REPORT_FOOTER') || !(REPORT_FOOTER == false))
 
 961       $body .= '<p style="text-align: center;">'.$i18n->get('form.mail.footer').'</p>';
 
 963     // Finish creating email body.
 
 964     $body .= '</body></html>';
 
 969   // checkFavReportCondition - checks whether it is okay to send fav report.
 
 970   static function checkFavReportCondition($options, $condition)
 
 972     $items = ttReportHelper::getItems($options);
 
 974     $condition = trim(str_replace('count', '', $condition));
 
 976     $greater_or_equal = ttStartsWith($condition, '>=');
 
 977     if ($greater_or_equal) $condition = trim(str_replace('>=', '', $condition));
 
 979     $less_or_equal = ttStartsWith($condition, '<=');
 
 980     if ($less_or_equal) $condition = trim(str_replace('<=', '', $condition));
 
 982     $not_equal = ttStartsWith($condition, '<>');
 
 983     if ($not_equal) $condition = trim(str_replace('<>', '', $condition));
 
 985     $greater = ttStartsWith($condition, '>');
 
 986     if ($greater) $condition = trim(str_replace('>', '', $condition));
 
 988     $less = ttStartsWith($condition, '<');
 
 989     if ($less) $condition = trim(str_replace('<', '', $condition));
 
 991     $equal = ttStartsWith($condition, '=');
 
 992     if ($equal) $condition = trim(str_replace('=', '', $condition));
 
 994     $count_required = (int) $condition;
 
 996     if ($greater && count($items) > $count_required) return true;
 
 997     if ($greater_or_equal && count($items) >= $count_required) return true;
 
 998     if ($less && count($items) < $count_required) return true;
 
 999     if ($less_or_equal && count($items) <= $count_required) return true;
 
1000     if ($equal && count($items) == $count_required) return true;
 
1001     if ($not_equal && count($items) <> $count_required) return true;
 
1006   // sendFavReport - sends a favorite report to a specified email, called from cron.php
 
1007   static function sendFavReport($options, $subject, $email, $cc) {
 
1008     // We are called from cron.php, we have no $bean in session.
 
1009     // cron.php sets global $user and $i18n objects to match our favorite report user.
 
1013     // Prepare report body.
 
1014     $body = ttReportHelper::prepareReportBody($options);
 
1016     import('mail.Mailer');
 
1017     $mailer = new Mailer();
 
1018     $mailer->setCharSet(CHARSET);
 
1019     $mailer->setContentType('text/html');
 
1020     $mailer->setSender(SENDER);
 
1022       $mailer->setReceiverCC($cc);
 
1023     if (!empty($user->bcc_email))
 
1024       $mailer->setReceiverBCC($user->bcc_email);
 
1025     $mailer->setReceiver($email);
 
1026     $mailer->setMailMode(MAIL_MODE);
 
1027     if (empty($subject)) $subject = $options['name'];
 
1028     if (!$mailer->send($subject, $body))
 
1034   // getReportOptions - returns an array of report options constructed from session bean.
 
1036   // Note: similarly to ttFavReportHelper::getReportOptions, this function is a part of
 
1037   // refactoring to simplify maintenance of report generating functions, as we currently
 
1038   // have 2 sets: normal reporting (from bean), and fav report emailing (from db fields).
 
1039   // Using options obtained from either db or bean shall allow us to use only one set of functions.
 
1040   static function getReportOptions($bean) {
 
1043     // Prepare an array of report options.
 
1046     // Construct one by one.
 
1047     $options['name'] = null; // No name required.
 
1048     $options['user_id'] = $user->id; // Not sure if we need user_id here. Fav reports use it to recycle $user object in cron.php.
 
1049     $options['client_id'] = $bean->getAttribute('client');
 
1050     $options['cf_1_option_id'] = $bean->getAttribute('option');
 
1051     $options['project_id'] = $bean->getAttribute('project');
 
1052     $options['task_id'] = $bean->getAttribute('task');
 
1053     $options['billable'] = $bean->getAttribute('include_records');
 
1054     $options['invoice'] = $bean->getAttribute('invoice');
 
1055     $options['paid_status'] = $bean->getAttribute('paid_status');
 
1056     $options['timesheet'] = $bean->getAttribute('timesheet');
 
1057     if ($user->isPluginEnabled('ts') && $user->isClient() && !$user->can('view_client_unapproved'))
 
1058       $options['timesheet'] = TIMESHEET_APPROVED; // Restrict clients to approved timesheet records only.
 
1059     if (is_array($bean->getAttribute('users'))) $options['users'] = join(',', $bean->getAttribute('users'));
 
1060     $options['period'] = $bean->getAttribute('period');
 
1061     $options['period_start'] = $bean->getAttribute('start_date');
 
1062     $options['period_end'] = $bean->getAttribute('end_date');
 
1063     $options['show_client'] = $bean->getAttribute('chclient');
 
1064     $options['show_invoice'] = $bean->getAttribute('chinvoice');
 
1065     $options['show_paid'] = $bean->getAttribute('chpaid');
 
1066     $options['show_ip'] = $bean->getAttribute('chip');
 
1067     $options['show_project'] = $bean->getAttribute('chproject');
 
1068     $options['show_start'] = $bean->getAttribute('chstart');
 
1069     $options['show_duration'] = $bean->getAttribute('chduration');
 
1070     $options['show_cost'] = $bean->getAttribute('chcost');
 
1071     $options['show_task'] = $bean->getAttribute('chtask');
 
1072     $options['show_end'] = $bean->getAttribute('chfinish');
 
1073     $options['show_note'] = $bean->getAttribute('chnote');
 
1074     $options['show_custom_field_1'] = $bean->getAttribute('chcf_1');
 
1075     $options['show_work_units'] = $bean->getAttribute('chunits');
 
1076     $options['show_timesheet'] = $bean->getAttribute('chtimesheet');
 
1077     $options['show_totals_only'] = $bean->getAttribute('chtotalsonly');
 
1078     $options['group_by1'] = $bean->getAttribute('group_by1');
 
1079     $options['group_by2'] = $bean->getAttribute('group_by2');
 
1080     $options['group_by3'] = $bean->getAttribute('group_by3');
 
1084   // verifyBean is a security function to make sure data in bean makes sense for a group.
 
1085   static function verifyBean($bean) {
 
1089     $users_in_bean = $bean->getAttribute('users');
 
1090     if (is_array($users_in_bean)) {
 
1091       $users_in_group = ttGroupHelper::getUsers();
 
1092       foreach ($users_in_group as $user_in_group) {
 
1093         $valid_ids[] = $user_in_group['id'];
 
1095       foreach ($users_in_bean as $user_in_bean) {
 
1096         if (!in_array($user_in_bean, $valid_ids)) {
 
1102     // TODO: add additional checks here. Perhaps do it before saving the bean for consistency.
 
1106   // makeGroupByKey builds a combined group by key from group_by1, group_by2 and group_by3 values
 
1107   // (passed in $options) and a row of data ($row obtained from a db query).
 
1108   static function makeGroupByKey($options, $row) {
 
1109     if ($options['group_by1'] != null && $options['group_by1'] != 'no_grouping') {
 
1110       // We have group_by1.
 
1111       $group_by1 = $options['group_by1'];
 
1112       $group_by1_value = $row[$group_by1];
 
1113       //if ($group_by1 == 'date') $group_by1_value = ttDateToUserFormat($group_by1_value);
 
1114       if (empty($group_by1_value)) $group_by1_value = 'Null'; // To match what comes out of makeConcatPart.
 
1115       $group_by_key .= ' - '.$group_by1_value;
 
1117     if ($options['group_by2'] != null && $options['group_by2'] != 'no_grouping') {
 
1118       // We have group_by2.
 
1119       $group_by2 = $options['group_by2'];
 
1120       $group_by2_value = $row[$group_by2];
 
1121       //if ($group_by2 == 'date') $group_by2_value = ttDateToUserFormat($group_by2_value);
 
1122       if (empty($group_by2_value)) $group_by2_value = 'Null'; // To match what comes out of makeConcatPart.
 
1123       $group_by_key .= ' - '.$group_by2_value;
 
1125     if ($options['group_by3'] != null && $options['group_by3'] != 'no_grouping') {
 
1126       // We have group_by3.
 
1127       $group_by3 = $options['group_by3'];
 
1128       $group_by3_value = $row[$group_by3];
 
1129       //if ($group_by3 == 'date') $group_by3_value = ttDateToUserFormat($group_by3_value);
 
1130       if (empty($group_by3_value)) $group_by3_value = 'Null'; // To match what comes out of makeConcatPart.
 
1131       $group_by_key .= ' - '.$group_by3_value;
 
1133     $group_by_key = trim($group_by_key, ' -');
 
1134     return $group_by_key;
 
1137   // makeGroupByPart builds a combined group by part for sql query for time items using group_by1,
 
1138   // group_by2, and group_by3 values passed in $options.
 
1139   static function makeGroupByPart($options) {
 
1140     if (!ttReportHelper::grouping($options)) return null;
 
1142     $group_by1 = $options['group_by1'];
 
1143     $group_by2 = $options['group_by2'];
 
1144     $group_by3 = $options['group_by3'];
 
1146     switch ($group_by1) {
 
1148         $group_by_parts .= ', l.date';
 
1151         $group_by_parts .= ', u.name';
 
1154         $group_by_parts .= ', c.name';
 
1157         $group_by_parts .= ', p.name';
 
1160         $group_by_parts .= ', t.name';
 
1163         $group_by_parts .= ', cfo.value';
 
1166     switch ($group_by2) {
 
1168         $group_by_parts .= ', l.date';
 
1171         $group_by_parts .= ', u.name';
 
1174         $group_by_parts .= ', c.name';
 
1177         $group_by_parts .= ', p.name';
 
1180         $group_by_parts .= ', t.name';
 
1183         $group_by_parts .= ', cfo.value';
 
1186     switch ($group_by3) {
 
1188         $group_by_parts .= ', l.date';
 
1191         $group_by_parts .= ', u.name';
 
1194         $group_by_parts .= ', c.name';
 
1197         $group_by_parts .= ', p.name';
 
1200         $group_by_parts .= ', t.name';
 
1203         $group_by_parts .= ', cfo.value';
 
1206     // Remove garbage from the beginning.
 
1207     $group_by_parts = ltrim($group_by_parts, ', ');
 
1208     $group_by_part = "group by $group_by_parts";
 
1209     return $group_by_part;
 
1212   // makeGroupByExpensesPart builds a combined group by part for sql query for expense items using
 
1213   // group_by1, group_by2, and group_by3 values passed in $options.
 
1214   static function makeGroupByExpensesPart($options) {
 
1215     $no_grouping = ($options['group_by1'] == null || $options['group_by1'] == 'no_grouping') &&
 
1216       ($options['group_by2'] == null || $options['group_by2'] == 'no_grouping') &&
 
1217       ($options['group_by3'] == null || $options['group_by3'] == 'no_grouping');
 
1218     if ($no_grouping) return null;
 
1220     $group_by1 = $options['group_by1'];
 
1221     $group_by2 = $options['group_by2'];
 
1222     $group_by3 = $options['group_by3'];
 
1224     switch ($group_by1) {
 
1226         $group_by_parts .= ', ei.date';
 
1229         $group_by_parts .= ', u.name';
 
1232         $group_by_parts .= ', c.name';
 
1235         $group_by_parts .= ', p.name';
 
1238     switch ($group_by2) {
 
1240         $group_by_parts .= ', ei.date';
 
1243         $group_by_parts .= ', u.name';
 
1246         $group_by_parts .= ', c.name';
 
1249         $group_by_parts .= ', p.name';
 
1252     switch ($group_by3) {
 
1254         $group_by_parts .= ', ei.date';
 
1257         $group_by_parts .= ', u.name';
 
1260         $group_by_parts .= ', c.name';
 
1263         $group_by_parts .= ', p.name';
 
1266     // Remove garbage from the beginning.
 
1267     $group_by_parts = ltrim($group_by_parts, ', ');
 
1268     if ($group_by_parts)
 
1269       $group_by_part = "group by $group_by_parts";
 
1270     return $group_by_part;
 
1273   // makeConcatPart builds a concatenation part for getSubtotals query (for time items).
 
1274   static function makeConcatPart($options) {
 
1275     $group_by1 = $options['group_by1'];
 
1276     $group_by2 = $options['group_by2'];
 
1277     $group_by3 = $options['group_by3'];
 
1279     switch ($group_by1) {
 
1281         $what_to_concat .= ", ' - ', l.date";
 
1284         $what_to_concat .= ", ' - ', u.name";
 
1285         $fields_part .= ', u.name as user';
 
1288         $what_to_concat .= ", ' - ', coalesce(c.name, 'Null')";
 
1289         $fields_part .= ', c.name as client';
 
1292         $what_to_concat .= ", ' - ', coalesce(p.name, 'Null')";
 
1293         $fields_part .= ', p.name as project';
 
1296         $what_to_concat .= ", ' - ', coalesce(t.name, 'Null')";
 
1297         $fields_part .= ', t.name as task';
 
1300         $what_to_concat .= ", ' - ', coalesce(cfo.value, 'Null')";
 
1301         $fields_part .= ', cfo.value as cf_1';
 
1304     switch ($group_by2) {
 
1306         $what_to_concat .= ", ' - ', l.date";
 
1309         $what_to_concat .= ", ' - ', u.name";
 
1310         $fields_part .= ', u.name as user';
 
1313         $what_to_concat .= ", ' - ', coalesce(c.name, 'Null')";
 
1314         $fields_part .= ', c.name as client';
 
1317         $what_to_concat .= ", ' - ', coalesce(p.name, 'Null')";
 
1318         $fields_part .= ', p.name as project';
 
1321         $what_to_concat .= ", ' - ', coalesce(t.name, 'Null')";
 
1322         $fields_part .= ', t.name as task';
 
1325         $what_to_concat .= ", ' - ', coalesce(cfo.value, 'Null')";
 
1326         $fields_part .= ', cfo.value as cf_1';
 
1329     switch ($group_by3) {
 
1331         $what_to_concat .= ", ' - ', l.date";
 
1334         $what_to_concat .= ", ' - ', u.name";
 
1335         $fields_part .= ', u.name as user';
 
1338         $what_to_concat .= ", ' - ', coalesce(c.name, 'Null')";
 
1339         $fields_part .= ', c.name as client';
 
1342         $what_to_concat .= ", ' - ', coalesce(p.name, 'Null')";
 
1343         $fields_part .= ', p.name as project';
 
1346         $what_to_concat .= ", ' - ', coalesce(t.name, 'Null')";
 
1347         $fields_part .= ', t.name as task';
 
1350         $what_to_concat .= ", ' - ', coalesce(cfo.value, 'Null')";
 
1351         $fields_part .= ', cfo.value as cf_1';
 
1354     // Remove garbage from both ends.
 
1355     $what_to_concat = trim($what_to_concat, "', -");
 
1356     $concat_part = "concat($what_to_concat) as group_field";
 
1357     $concat_part = trim($concat_part, ' -');
 
1358     return "$concat_part $fields_part";
 
1361   // makeConcatPart builds a concatenation part for getSubtotals query (for expense items).
 
1362   static function makeConcatExpensesPart($options) {
 
1363     $group_by1 = $options['group_by1'];
 
1364     $group_by2 = $options['group_by2'];
 
1365     $group_by3 = $options['group_by3'];
 
1367     switch ($group_by1) {
 
1369         $what_to_concat .= ", ' - ', ei.date";
 
1372         $what_to_concat .= ", ' - ', u.name";
 
1373         $fields_part .= ', u.name as user';
 
1376         $what_to_concat .= ", ' - ', coalesce(c.name, 'Null')";
 
1377         $fields_part .= ', c.name as client';
 
1380         $what_to_concat .= ", ' - ', coalesce(p.name, 'Null')";
 
1381         $fields_part .= ', p.name as project';
 
1385         $what_to_concat .= ", ' - ', 'Null'";
 
1386         $fields_part .= ', null as task';
 
1390         $what_to_concat .= ", ' - ', 'Null'";
 
1391         $fields_part .= ', null as cf_1';
 
1394     switch ($group_by2) {
 
1396         $what_to_concat .= ", ' - ', ei.date";
 
1399         $what_to_concat .= ", ' - ', u.name";
 
1400         $fields_part .= ', u.name as user';
 
1403         $what_to_concat .= ", ' - ', coalesce(c.name, 'Null')";
 
1404         $fields_part .= ', c.name as client';
 
1407         $what_to_concat .= ", ' - ', coalesce(p.name, 'Null')";
 
1408         $fields_part .= ', p.name as project';
 
1412         $what_to_concat .= ", ' - ', 'Null'";
 
1413         $fields_part .= ', null as task';
 
1417         $what_to_concat .= ", ' - ', 'Null'";
 
1418         $fields_part .= ', null as cf_1';
 
1421     switch ($group_by3) {
 
1423         $what_to_concat .= ", ' - ', ei.date";
 
1426         $what_to_concat .= ", ' - ', u.name";
 
1427         $fields_part .= ', u.name as user';
 
1430         $what_to_concat .= ", ' - ', coalesce(c.name, 'Null')";
 
1431         $fields_part .= ', c.name as client';
 
1434         $what_to_concat .= ", ' - ', coalesce(p.name, 'Null')";
 
1435         $fields_part .= ', p.name as project';
 
1439         $what_to_concat .= ", ' - ', 'Null'";
 
1440         $fields_part .= ', null as task';
 
1444         $what_to_concat .= ", ' - ', 'Null'";
 
1445         $fields_part .= ', null as cf_1';
 
1448     // Remove garbage from the beginning.
 
1449     if ($what_to_concat)
 
1450         $what_to_concat = substr($what_to_concat, 8);
 
1451     $concat_part = "concat($what_to_concat) as group_field";
 
1452     return "$concat_part $fields_part";
 
1455   // makeCombinedSelectPart builds a list of fields for a combined select on a union for getSubtotals.
 
1456   // This is used when we include expenses.
 
1457   static function makeCombinedSelectPart($options) {
 
1458     $group_by1 = $options['group_by1'];
 
1459     $group_by2 = $options['group_by2'];
 
1460     $group_by3 = $options['group_by3'];
 
1462     $fields = "group_field";
 
1464     switch ($group_by1) {
 
1466         $fields .= ', user';
 
1469         $fields_part .= ', client';
 
1472         $fields .= ', project';
 
1476         $fields .= ', task';
 
1480         $fields .= ', cf_1';
 
1483     switch ($group_by2) {
 
1485         $fields .= ', user';
 
1488         $fields_part .= ', client';
 
1491         $fields .= ', project';
 
1495         $fields .= ', task';
 
1499         $fields .= ', cf_1';
 
1502     switch ($group_by3) {
 
1504         $fields .= ', user';
 
1507         $fields_part .= ', client';
 
1510         $fields .= ', project';
 
1514         $fields .= ', task';
 
1518         $fields .= ', cf_1';
 
1524   // makeJoinPart builds a left join part for getSubtotals query (for time items).
 
1525   static function makeJoinPart($options) {
 
1528     $trackingMode = $user->getTrackingMode();
 
1529     if (ttReportHelper::groupingBy('user', $options) || MODE_TIME == $trackingMode) {
 
1530       $join .= ' left join tt_users u on (l.user_id = u.id)';
 
1532     if (ttReportHelper::groupingBy('client', $options)) {
 
1533       $join .= ' left join tt_clients c on (l.client_id = c.id)';
 
1535     if (ttReportHelper::groupingBy('project', $options)) {
 
1536       $join .= ' left join tt_projects p on (l.project_id = p.id)';
 
1538     if (ttReportHelper::groupingBy('task', $options)) {
 
1539       $join .= ' left join tt_tasks t on (l.task_id = t.id)';
 
1541     if (ttReportHelper::groupingBy('cf_1', $options)) {
 
1542       $custom_fields = new CustomFields();
 
1543       if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_TEXT)
 
1544         $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)';
 
1545       elseif ($custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN)
 
1546         $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)';
 
1548     if ($options['show_cost'] && $trackingMode != MODE_TIME) {
 
1549       $join .= ' left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id)';
 
1551     // Prepare inner joins.
 
1552     $inner_joins = null;
 
1553     if ($user->isPluginEnabled('ts') && $options['timesheet']) {
 
1554       $timesheet_option = $options['timesheet'];
 
1555       if ($timesheet_option == TIMESHEET_PENDING)
 
1556         $inner_joins .= " inner join tt_timesheets ts on (l.timesheet_id = ts.id and ts.submit_status = 1 and ts.approval_status is null)";
 
1557       else if ($timesheet_option == TIMESHEET_APPROVED)
 
1558         $inner_joins .= " inner join tt_timesheets ts on (l.timesheet_id = ts.id and ts.approval_status = 1)";
 
1559       else if ($timesheet_option == TIMESHEET_NOT_APPROVED)
 
1560         $inner_joins .= " inner join tt_timesheets ts on (l.timesheet_id = ts.id and ts.approval_status = 0)";
 
1562     $join .= $inner_joins;
 
1566   // makeWorkUnitPart builds an sql part for work units for time items.
 
1567   static function makeWorkUnitPart($options) {
 
1570     $workUnits = $options['show_work_units'];
 
1572       $unitTotalsOnly = $user->getConfigOption('unit_totals_only');
 
1573       $firstUnitThreshold = $user->getConfigInt('1st_unit_threshold', 0);
 
1574       $minutesInUnit = $user->getConfigInt('minutes_in_unit', 15);
 
1575       if ($unitTotalsOnly)
 
1576         $work_unit_part = ", if (sum(l.billable * time_to_sec(l.duration)/60) < $firstUnitThreshold, 0, ceil(sum(l.billable * time_to_sec(l.duration)/60/$minutesInUnit))) as units";
 
1578         $work_unit_part = ", sum(if(l.billable = 0 or time_to_sec(l.duration)/60 < $firstUnitThreshold, 0, ceil(time_to_sec(l.duration)/60/$minutesInUnit))) as units";
 
1580     return $work_unit_part;
 
1583   // makeCostPart builds a cost part for time items.
 
1584   static function makeCostPart($options) {
 
1587     if ($options['show_cost']) {
 
1588       if (MODE_TIME == $user->getTrackingMode())
 
1589         $cost_part = ", sum(cast(l.billable * coalesce(u.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10, 2))) as cost";
 
1591         $cost_part .= ", sum(cast(l.billable * coalesce(upb.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10,2))) as cost";
 
1596   // makeJoinExpensesPart builds a left join part for getSubtotals query for expense items.
 
1597   static function makeJoinExpensesPart($options) {
 
1600     if (ttReportHelper::groupingBy('user', $options)) {
 
1601       $join .= ' left join tt_users u on (ei.user_id = u.id)';
 
1603     if (ttReportHelper::groupingBy('client', $options)) {
 
1604       $join .= ' left join tt_clients c on (ei.client_id = c.id)';
 
1606     if (ttReportHelper::groupingBy('project', $options)) {
 
1607       $join .= ' left join tt_projects p on (ei.project_id = p.id)';
 
1609     // Prepare inner joins.
 
1610     $inner_joins = null;
 
1611     if ($user->isPluginEnabled('ts') && $options['timesheet']) {
 
1612       $timesheet_option = $options['timesheet'];
 
1613       if ($timesheet_option == TIMESHEET_PENDING)
 
1614         $inner_joins .= " inner join tt_timesheets ts on (ei.timesheet_id = ts.id and ts.submit_status = 1 and ts.approval_status is null)";
 
1615       else if ($timesheet_option == TIMESHEET_APPROVED)
 
1616         $inner_joins .= " inner join tt_timesheets ts on (ei.timesheet_id = ts.id and ts.approval_status = 1)";
 
1617       else if ($timesheet_option == TIMESHEET_NOT_APPROVED)
 
1618         $inner_joins .= " inner join tt_timesheets ts on (ei.timesheet_id = ts.id and ts.approval_status = 0)";
 
1620     $join .= $inner_joins;
 
1624   // grouping determines if we are grouping the report by either group_by1,
 
1625   // group_by2, or group_by3 values passed in $options.
 
1626   static function grouping($options) {
 
1627     $grouping = ($options['group_by1'] != null && $options['group_by1'] != 'no_grouping') ||
 
1628       ($options['group_by2'] != null && $options['group_by2'] != 'no_grouping') ||
 
1629       ($options['group_by3'] != null && $options['group_by3'] != 'no_grouping');
 
1633   // groupingBy determines if we are grouping a report by a value of $what
 
1634   // ('date', 'user', 'project', etc.) by checking group_by1, group_by2,
 
1635   // and group_by3 values passed in $options.
 
1636   static function groupingBy($what, $options) {
 
1637     $grouping = ($options['group_by1'] == $what) || ($options['group_by2'] == $what) || ($options['group_by3'] == $what);
 
1641   // makeGroupByHeader builds a column header for a totals-only report using group_by1,
 
1642   // group_by2, and group_by3 values passed in $options.
 
1643   static function makeGroupByHeader($options) {
 
1645     global $custom_fields;
 
1647     $no_grouping = ($options['group_by1'] == null || $options['group_by1'] == 'no_grouping') &&
 
1648       ($options['group_by2'] == null || $options['group_by2'] == 'no_grouping') &&
 
1649       ($options['group_by3'] == null || $options['group_by3'] == 'no_grouping');
 
1650     if ($no_grouping) return null;
 
1652     if ($options['group_by1'] != null && $options['group_by1'] != 'no_grouping') {
 
1653       // We have group_by1.
 
1654       $group_by1 = $options['group_by1'];
 
1655       if ('cf_1' == $group_by1)
 
1656         $group_by_header .= ' - '.$custom_fields->fields[0]['label'];
 
1658         $key = 'label.'.$group_by1;
 
1659         $group_by_header .= ' - '.$i18n->get($key);
 
1662     if ($options['group_by2'] != null && $options['group_by2'] != 'no_grouping') {
 
1663       // We have group_by2.
 
1664       $group_by2 = $options['group_by2'];
 
1665       if ('cf_1' == $group_by2)
 
1666         $group_by_header .= ' - '.$custom_fields->fields[0]['label'];
 
1668         $key = 'label.'.$group_by2;
 
1669         $group_by_header .= ' - '.$i18n->get($key);
 
1672     if ($options['group_by3'] != null && $options['group_by3'] != 'no_grouping') {
 
1673       // We have group_by3.
 
1674       $group_by3 = $options['group_by3'];
 
1675       if ('cf_1' == $group_by3)
 
1676         $group_by_header .= ' - '.$custom_fields->fields[0]['label'];
 
1678         $key = 'label.'.$group_by3;
 
1679         $group_by_header .= ' - '.$i18n->get($key);
 
1682     $group_by_header = ltrim($group_by_header, ' -');
 
1683     return $group_by_header;
 
1686   // makeGroupByXmlTag creates an xml tag for a totals only report using group_by1,
 
1687   // group_by2, and group_by3 values passed in $options.
 
1688   static function makeGroupByXmlTag($options) {
 
1689     if ($options['group_by1'] != null && $options['group_by1'] != 'no_grouping') {
 
1690       // We have group_by1.
 
1691       $tag .= '_'.$options['group_by1'];
 
1693     if ($options['group_by2'] != null && $options['group_by2'] != 'no_grouping') {
 
1694       // We have group_by2.
 
1695       $tag .= '_'.$options['group_by2'];
 
1697     if ($options['group_by3'] != null && $options['group_by3'] != 'no_grouping') {
 
1698       // We have group_by3.
 
1699       $tag .= '_'.$options['group_by3'];
 
1701     $tag = ltrim($tag, '_');
 
1705   // makeGroupByLabel builds a label for one row in a "Totals only" report of grouped by items.
 
1706   // It does one thing: if we are grouping by date, the date format is converted for user.
 
1707   static function makeGroupByLabel($key, $options) {
 
1708     if (!ttReportHelper::groupingBy('date', $options))
 
1709       return $key; // No need to format.
 
1712     if ($user->getDateFormat() == DB_DATEFORMAT)
 
1713       return $key; // No need to format.
 
1716     if (preg_match('/\d\d\d\d-\d\d-\d\d/', $key, $matches)) {
 
1717       // Replace the first found match of a date in DB_DATEFORMAT.
 
1718       // This is not entirely clean but better than nothing for a label in a row.
 
1719       $userDate = ttDateToUserFormat($matches[0]);
 
1720       $label = str_replace($matches[0], $userDate, $key);