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['approved']=='1') $dropdown_parts .= ' and l.approved = 1';
 
  76     if ($options['approved']=='2') $dropdown_parts .= ' and l.approved = 0';
 
  77     if ($options['paid_status']=='1') $dropdown_parts .= ' and l.paid = 1';
 
  78     if ($options['paid_status']=='2') $dropdown_parts .= ' and l.paid = 0';
 
  80     // Prepare sql query part for user list.
 
  81     $userlist = $options['users'] ? $options['users'] : '-1';
 
  82     if ($user->can('view_reports') || $user->can('view_all_reports') || $user->isClient())
 
  83       $user_list_part = " and l.user_id in ($userlist)";
 
  85       $user_list_part = " and l.user_id = ".$user->getUser();
 
  86     $user_list_part .= " and l.group_id = $group_id and l.org_id = $org_id";
 
  88     // Prepare sql query part for where.
 
  89     $dateFormat = $user->getDateFormat();
 
  90     if ($options['period'])
 
  91       $period = new Period($options['period'], new DateAndTime($dateFormat));
 
  93       $period = new Period();
 
  95         new DateAndTime($dateFormat, $options['period_start']),
 
  96         new DateAndTime($dateFormat, $options['period_end']));
 
  98     $where = " where l.status = 1 and l.date >= '".$period->getStartDate(DB_DATEFORMAT)."' and l.date <= '".$period->getEndDate(DB_DATEFORMAT)."'".
 
  99       " $user_list_part $dropdown_parts";
 
 103   // getExpenseWhere prepares WHERE clause for expenses query in a report.
 
 104   static function getExpenseWhere($options) {
 
 107     $group_id = $user->getGroup();
 
 108     $org_id = $user->org_id;
 
 110     // Prepare dropdown parts.
 
 111     $dropdown_parts = '';
 
 112     if ($options['client_id'])
 
 113       $dropdown_parts .= ' and ei.client_id = '.$options['client_id'];
 
 114     elseif ($user->isClient() && $user->client_id)
 
 115       $dropdown_parts .= ' and ei.client_id = '.$user->client_id;
 
 116     if ($options['project_id']) $dropdown_parts .= ' and ei.project_id = '.$options['project_id'];
 
 117     if ($options['invoice']=='1') $dropdown_parts .= ' and ei.invoice_id is not null';
 
 118     if ($options['invoice']=='2') $dropdown_parts .= ' and ei.invoice_id is null';
 
 119     if (isset($options['timesheet']) && ($options['timesheet']!=TIMESHEET_ALL && $options['timesheet']!=TIMESHEET_NOT_ASSIGNED)) {
 
 120         $dropdown_parts .= ' and 0 = 1'; // Expense items do not have a timesheet_id.
 
 122     if ($options['approved']=='1') $dropdown_parts .= ' and ei.approved = 1';
 
 123     if ($options['approved']=='2') $dropdown_parts .= ' and ei.approved = 0';
 
 124     if ($options['paid_status']=='1') $dropdown_parts .= ' and ei.paid = 1';
 
 125     if ($options['paid_status']=='2') $dropdown_parts .= ' and ei.paid = 0';
 
 127     // Prepare sql query part for user list.
 
 128     $userlist = $options['users'] ? $options['users'] : '-1';
 
 129     if ($user->can('view_reports') || $user->can('view_all_reports') || $user->isClient())
 
 130       $user_list_part = " and ei.user_id in ($userlist)";
 
 132       $user_list_part = " and ei.user_id = ".$user->getUser();
 
 133     $user_list_part .= " and ei.group_id = $group_id and ei.org_id = $org_id";
 
 135     // Prepare sql query part for where.
 
 136     $dateFormat = $user->getDateFormat();
 
 137     if ($options['period'])
 
 138       $period = new Period($options['period'], new DateAndTime($dateFormat));
 
 140       $period = new Period();
 
 142         new DateAndTime($dateFormat, $options['period_start']),
 
 143         new DateAndTime($dateFormat, $options['period_end']));
 
 145     $where = " where ei.status = 1 and ei.date >= '".$period->getStartDate(DB_DATEFORMAT)."' and ei.date <= '".$period->getEndDate(DB_DATEFORMAT)."'".
 
 146       " $user_list_part $dropdown_parts";
 
 150   // getItems retrieves all items associated with a report.
 
 151   // It combines tt_log and tt_expense_items in one array for presentation in one table using mysql union all.
 
 152   // Expense items use the "note" field for item name.
 
 153   static function getItems($options) {
 
 155     $mdb2 = getConnection();
 
 157     // Determine these once as they are used in multiple places in this function.
 
 158     $canViewReports = $user->can('view_reports') || $user->can('view_all_reports');
 
 159     $isClient = $user->isClient();
 
 161     $grouping = ttReportHelper::grouping($options);
 
 163       $grouping_by_date = ttReportHelper::groupingBy('date', $options);
 
 164       $grouping_by_client = ttReportHelper::groupingBy('client', $options);
 
 165       $grouping_by_project = ttReportHelper::groupingBy('project', $options);
 
 166       $grouping_by_task = ttReportHelper::groupingBy('task', $options);
 
 167       $grouping_by_user = ttReportHelper::groupingBy('user', $options);
 
 168       $grouping_by_cf_1 = ttReportHelper::groupingBy('cf_1', $options);
 
 170     $convertTo12Hour = ('%I:%M %p' == $user->getTimeFormat()) && ($options['show_start'] || $options['show_end']);
 
 171     $trackingMode = $user->getTrackingMode();
 
 172     $decimalMark = $user->getDecimalMark();
 
 174     // Prepare a query for time items in tt_log table.
 
 175     $fields = array(); // An array of fields for database query.
 
 176     array_push($fields, 'l.id');
 
 177     array_push($fields, 'l.user_id');
 
 178     array_push($fields, '1 as type'); // Type 1 is for tt_log entries.
 
 179     array_push($fields, 'l.date');
 
 180     if($canViewReports || $isClient)
 
 181       array_push($fields, 'u.name as user');
 
 182     // Add client name if it is selected.
 
 183     if ($options['show_client'] || $grouping_by_client)
 
 184       array_push($fields, 'c.name as client');
 
 185     // Add project name if it is selected.
 
 186     if ($options['show_project'] || $grouping_by_project)
 
 187       array_push($fields, 'p.name as project');
 
 188     // Add task name if it is selected.
 
 189     if ($options['show_task'] || $grouping_by_task)
 
 190       array_push($fields, 't.name as task');
 
 192     $include_cf_1 = $options['show_custom_field_1'] || $grouping_by_cf_1;
 
 194       $custom_fields = new CustomFields();
 
 195       $cf_1_type = $custom_fields->fields[0]['type'];
 
 196       if ($cf_1_type == CustomFields::TYPE_TEXT) {
 
 197         array_push($fields, 'cfl.value as cf_1');
 
 198       } elseif ($cf_1_type == CustomFields::TYPE_DROPDOWN) {
 
 199         array_push($fields, 'cfo.value as cf_1');
 
 203     if ($options['show_start']) {
 
 204       array_push($fields, "l.start as unformatted_start");
 
 205       array_push($fields, "TIME_FORMAT(l.start, '%k:%i') as start");
 
 208     if ($options['show_end'])
 
 209       array_push($fields, "TIME_FORMAT(sec_to_time(time_to_sec(l.start) + time_to_sec(l.duration)), '%k:%i') as finish");
 
 211     if ($options['show_duration'])
 
 212       array_push($fields, "TIME_FORMAT(l.duration, '%k:%i') as duration");
 
 214     if ($options['show_work_units']) {
 
 215       if ($user->getConfigOption('unit_totals_only'))
 
 216         array_push($fields, "null as units");
 
 218         $firstUnitThreshold = $user->getConfigInt('1st_unit_threshold', 0);
 
 219         $minutesInUnit = $user->getConfigInt('minutes_in_unit', 15);
 
 220         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");
 
 224     if ($options['show_note'])
 
 225       array_push($fields, 'l.comment as note');
 
 227     $includeCost = $options['show_cost'];
 
 229       if (MODE_TIME == $trackingMode)
 
 230         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.
 
 232         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.
 
 233       array_push($fields, "null as expense"); 
 
 236     if ($options['show_approved'])
 
 237       array_push($fields, 'l.approved');
 
 239     if ($canViewReports && $options['show_paid'])
 
 240       array_push($fields, 'l.paid');
 
 242     if ($canViewReports && $options['show_ip']) {
 
 243       array_push($fields, 'l.created');
 
 244       array_push($fields, 'l.created_ip');
 
 245       array_push($fields, 'l.modified');
 
 246       array_push($fields, 'l.modified_ip');
 
 248     // Add invoice name if it is selected.
 
 249     if (($canViewReports || $isClient) && $options['show_invoice'])
 
 250       array_push($fields, 'i.name as invoice');
 
 251     // Add timesheet name if it is selected.
 
 252     if ($options['show_timesheet'])
 
 253       array_push($fields, 'ts.name as timesheet_name');
 
 255     // Prepare sql query part for left joins.
 
 257     if ($options['show_client'] || $grouping_by_client)
 
 258       $left_joins .= " left join tt_clients c on (c.id = l.client_id)";
 
 259     if (($canViewReports || $isClient) && $options['show_invoice'])
 
 260       $left_joins .= " left join tt_invoices i on (i.id = l.invoice_id and i.status = 1)";
 
 261     if ($canViewReports || $isClient || $user->isPluginEnabled('ex'))
 
 262        $left_joins .= " left join tt_users u on (u.id = l.user_id)";
 
 263     if ($options['show_project'] || $grouping_by_project)
 
 264       $left_joins .= " left join tt_projects p on (p.id = l.project_id)";
 
 265     if ($options['show_task'] || $grouping_by_task)
 
 266       $left_joins .= " left join tt_tasks t on (t.id = l.task_id)";
 
 268       if ($cf_1_type == CustomFields::TYPE_TEXT)
 
 269         $left_joins .= " left join tt_custom_field_log cfl on (l.id = cfl.log_id and cfl.status = 1)";
 
 270       elseif ($cf_1_type == CustomFields::TYPE_DROPDOWN) {
 
 271         $left_joins .=  " left join tt_custom_field_log cfl on (l.id = cfl.log_id and cfl.status = 1)".
 
 272           " left join tt_custom_field_options cfo on (cfl.option_id = cfo.id)";
 
 275     if ($includeCost && MODE_TIME != $trackingMode)
 
 276       $left_joins .= " left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id)";
 
 278     // Prepare sql query part for inner joins.
 
 280     if ($user->isPluginEnabled('ts')) {
 
 281       $timesheet_option = $options['timesheet'];
 
 282       if ($timesheet_option == TIMESHEET_PENDING)
 
 283         $inner_joins .= " inner join tt_timesheets ts on (l.timesheet_id = ts.id and ts.submit_status = 1 and ts.approve_status is null)";
 
 284       else if ($timesheet_option == TIMESHEET_APPROVED)
 
 285         $inner_joins .= " inner join tt_timesheets ts on (l.timesheet_id = ts.id and ts.approve_status = 1)";
 
 286       else if ($timesheet_option == TIMESHEET_NOT_APPROVED)
 
 287         $inner_joins .= " inner join tt_timesheets ts on (l.timesheet_id = ts.id and ts.approve_status = 0)";
 
 288       else if ($options['show_timesheet'])
 
 289         $inner_joins .= " left join tt_timesheets ts on (l.timesheet_id = ts.id)"; // Left join for timesheet nme.
 
 292     $where = ttReportHelper::getWhere($options);
 
 294     // Construct sql query for tt_log items.
 
 295     $sql = "select ".join(', ', $fields)." from tt_log l $left_joins $inner_joins $where";
 
 296     // If we don't have expense items (such as when the Expenses plugin is disabled), the above is all sql we need,
 
 297     // with an exception of sorting part, that is added in the end.
 
 299     // However, when we have expenses, we need to do a union with a separate query for expense items from tt_expense_items table.
 
 300     if ($options['show_cost'] && $user->isPluginEnabled('ex')) { // if ex(penses) plugin is enabled
 
 302       $fields = array(); // An array of fields for database query.
 
 303       array_push($fields, 'ei.id');
 
 304       array_push($fields, 'ei.user_id');
 
 305       array_push($fields, '2 as type'); // Type 2 is for tt_expense_items entries.
 
 306       array_push($fields, 'ei.date');
 
 307       if($canViewReports || $isClient)
 
 308         array_push($fields, 'u.name as user');
 
 309       // Add client name if it is selected.
 
 310       if ($options['show_client'] || $grouping_by_client)
 
 311         array_push($fields, 'c.name as client');
 
 312       // Add project name if it is selected.
 
 313       if ($options['show_project'] || $grouping_by_project)
 
 314         array_push($fields, 'p.name as project');
 
 315       if ($options['show_task'] || $grouping_by_task)
 
 316         array_push($fields, 'null'); // null for task name. We need to match column count for union.
 
 317       if ($options['show_custom_field_1'] || $grouping_by_cf_1)
 
 318         array_push($fields, 'null'); // null for cf_1.
 
 319       if ($options['show_start']) {
 
 320         array_push($fields, 'null'); // null for unformatted_start.
 
 321         array_push($fields, 'null'); // null for start.
 
 323       if ($options['show_end'])
 
 324         array_push($fields, 'null'); // null for finish.
 
 325       if ($options['show_duration'])
 
 326         array_push($fields, 'null'); // null for duration.
 
 327       if ($options['show_work_units'])
 
 328         array_push($fields, 'null as units'); // null for work units.
 
 329       // Use the note field to print item name.
 
 330       if ($options['show_note'])
 
 331         array_push($fields, 'ei.name as note');
 
 332       array_push($fields, 'ei.cost as cost');
 
 333       array_push($fields, 'ei.cost as expense');
 
 335       if ($options['show_approved'])
 
 336         array_push($fields, 'ei.approved');
 
 338       if ($canViewReports && $options['show_paid'])
 
 339         array_push($fields, 'ei.paid');
 
 341       if ($canViewReports && $options['show_ip']) {
 
 342         array_push($fields, 'ei.created');
 
 343         array_push($fields, 'ei.created_ip');
 
 344         array_push($fields, 'ei.modified');
 
 345         array_push($fields, 'ei.modified_ip');
 
 347       // Add invoice name if it is selected.
 
 348       if (($canViewReports || $isClient) && $options['show_invoice'])
 
 349         array_push($fields, 'i.name as invoice');
 
 350       if ($options['show_timesheet'])
 
 351         array_push($fields, 'null as timesheet_name');
 
 353       // Prepare sql query part for left joins.
 
 355       if ($canViewReports || $isClient)
 
 356         $left_joins .= " left join tt_users u on (u.id = ei.user_id)";
 
 357       if ($options['show_client'] || $grouping_by_client)
 
 358         $left_joins .= " left join tt_clients c on (c.id = ei.client_id)";
 
 359       if ($options['show_project'] || $grouping_by_project)
 
 360         $left_joins .= " left join tt_projects p on (p.id = ei.project_id)";
 
 361       if (($canViewReports || $isClient) && $options['show_invoice'])
 
 362         $left_joins .= " left join tt_invoices i on (i.id = ei.invoice_id and i.status = 1)";
 
 364       $where = ttReportHelper::getExpenseWhere($options);
 
 366       // Construct sql query for expense items.
 
 367       $sql_for_expense_items = "select ".join(', ', $fields)." from tt_expense_items ei $left_joins $where";
 
 369       // Construct a union.
 
 370       $sql = "($sql) union all ($sql_for_expense_items)";
 
 373     // Determine sort part.
 
 374     $sort_part = ' order by ';
 
 376       $sort_part2 .= ($options['group_by1'] != null && $options['group_by1'] != 'no_grouping') ? ', '.$options['group_by1'] : '';
 
 377       $sort_part2 .= ($options['group_by2'] != null && $options['group_by2'] != 'no_grouping') ? ', '.$options['group_by2'] : '';
 
 378       $sort_part2 .= ($options['group_by3'] != null && $options['group_by3'] != 'no_grouping') ? ', '.$options['group_by3'] : '';
 
 379       if (!$grouping_by_date) $sort_part2 .= ', date';
 
 380       $sort_part .= ltrim($sort_part2, ', '); // Remove leading comma and space.
 
 382       $sort_part .= 'date';
 
 384     if (($canViewReports || $isClient) && $options['users'] && !$grouping_by_user)
 
 385       $sort_part .= ', user, type';
 
 386     if ($options['show_start'])
 
 387       $sort_part .= ', unformatted_start';
 
 388     $sort_part .= ', id';
 
 391     // By now we are ready with sql.
 
 393     // Obtain items for report.
 
 394     $res = $mdb2->query($sql);
 
 395     if (is_a($res, 'PEAR_Error')) die($res->getMessage());
 
 397     while ($val = $res->fetchRow()) {
 
 398       if ($convertTo12Hour) {
 
 399         if($val['start'] != '')
 
 400           $val['start'] = ttTimeHelper::to12HourFormat($val['start']);
 
 401         if($val['finish'] != '')
 
 402           $val['finish'] = ttTimeHelper::to12HourFormat($val['finish']);
 
 404       if (isset($val['cost'])) {
 
 405         if ('.' != $decimalMark)
 
 406           $val['cost'] = str_replace('.', $decimalMark, $val['cost']);
 
 408       if (isset($val['expense'])) {
 
 409         if ('.' != $decimalMark)
 
 410           $val['expense'] = str_replace('.', $decimalMark, $val['expense']);
 
 413       if ($grouping) $val['grouped_by'] = ttReportHelper::makeGroupByKey($options, $val);
 
 414       $val['date'] = ttDateToUserFormat($val['date']);
 
 416       $report_items[] = $val;
 
 419     return $report_items;
 
 422   // putInSession stores tt_log and tt_expense_items ids from a report in user session
 
 423   // as 2 comma-separated lists.
 
 424   static function putInSession($report_items) {
 
 425     unset($_SESSION['report_item_ids']);
 
 426     unset($_SESSION['report_item_expense_ids']);
 
 428     // Iterate through records and build 2 comma-separated lists.
 
 429     foreach($report_items as $item) {
 
 430       if ($item['type'] == 1)
 
 431         $report_item_ids .= ','.$item['id'];
 
 432       else if ($item['type'] == 2)
 
 433          $report_item_expense_ids .= ','.$item['id'];
 
 435     $report_item_ids = trim($report_item_ids, ',');
 
 436     $report_item_expense_ids = trim($report_item_expense_ids, ',');
 
 438     // The lists are reqdy. Put them in session.
 
 439     if ($report_item_ids) $_SESSION['report_item_ids'] = $report_item_ids;
 
 440     if ($report_item_expense_ids) $_SESSION['report_item_expense_ids'] = $report_item_expense_ids;
 
 443   // getFromSession obtains tt_log and tt_expense_items ids stored in user session.
 
 444   static function getFromSession() {
 
 446     $report_item_ids = $_SESSION['report_item_ids'];
 
 447     if ($report_item_ids)
 
 448       $items['report_item_ids'] = explode(',', $report_item_ids);
 
 449     $report_item_expense_ids = $_SESSION['report_item_expense_ids'];
 
 450     if ($report_item_expense_ids)
 
 451       $items['report_item_expense_ids'] = explode(',', $report_item_expense_ids);
 
 455   // getSubtotals calculates report items subtotals when a report is grouped by.
 
 456   // Without expenses, it's a simple select with group by.
 
 457   // With expenses, it becomes a select with group by from a combined set of records obtained with "union all".
 
 458   static function getSubtotals($options) {
 
 460     $mdb2 = getConnection();
 
 462     $concat_part = ttReportHelper::makeConcatPart($options);
 
 463     $work_unit_part = ttReportHelper::makeWorkUnitPart($options);
 
 464     $join_part = ttReportHelper::makeJoinPart($options);
 
 465     $cost_part = ttReportHelper::makeCostPart($options);
 
 466     $where = ttReportHelper::getWhere($options);
 
 467     $group_by_part = ttReportHelper::makeGroupByPart($options);
 
 469     $parts = "$concat_part, sum(time_to_sec(l.duration)) as time, null as expenses".$work_unit_part.$cost_part;
 
 470     $sql = "select $parts from tt_log l $join_part $where $group_by_part";
 
 471     // By now we have sql for time items.
 
 473     // However, when we have expenses, we need to do a union with a separate query for expense items from tt_expense_items table.
 
 474     if ($options['show_cost'] && $user->isPluginEnabled('ex')) { // if ex(penses) plugin is enabled
 
 476       $concat_part = ttReportHelper::makeConcatExpensesPart($options);
 
 477       $join_part = ttReportHelper::makeJoinExpensesPart($options);
 
 478       $where = ttReportHelper::getExpenseWhere($options);
 
 479       $group_by_expenses_part = ttReportHelper::makeGroupByExpensesPart($options);
 
 480       $sql_for_expenses = "select $concat_part, null as time";
 
 481       if ($options['show_work_units']) $sql_for_expenses .= ", null as units";
 
 482       $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";
 
 484       // Create a combined query.
 
 485       $fields = ttReportHelper::makeCombinedSelectPart($options);
 
 486       $combined = "select $fields, sum(time) as time";
 
 487       if ($options['show_work_units']) $combined .= ", sum(units) as units";
 
 488       $combined .= ", sum(cost) as cost, sum(expenses) as expenses from (($sql) union all ($sql_for_expenses)) t group by $fields";
 
 493     $res = $mdb2->query($sql);
 
 494     if (is_a($res, 'PEAR_Error')) die($res->getMessage());
 
 495     while ($val = $res->fetchRow()) {
 
 496       $time = $val['time'] ? sec_to_time_fmt_hm($val['time']) : null;
 
 497       $rowLabel = ttReportHelper::makeGroupByLabel($val['group_field'], $options);
 
 498       if ($options['show_cost']) {
 
 499         $decimalMark = $user->getDecimalMark();
 
 500         if ('.' != $decimalMark) {
 
 501           $val['cost'] = str_replace('.', $decimalMark, $val['cost']);
 
 502           $val['expenses'] = str_replace('.', $decimalMark, $val['expenses']);
 
 504         $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']);
 
 506         $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']);
 
 512   // getTotals calculates total hours and cost for all report items.
 
 513   static function getTotals($options)
 
 516     $mdb2 = getConnection();
 
 518     $trackingMode = $user->getTrackingMode();
 
 519     $decimalMark = $user->getDecimalMark();
 
 520     $where = ttReportHelper::getWhere($options);
 
 523     $time_part = "sum(time_to_sec(l.duration)) as time";
 
 524     if ($options['show_work_units']) {
 
 525       $unitTotalsOnly = $user->getConfigOption('unit_totals_only');
 
 526       $firstUnitThreshold = $user->getConfigInt('1st_unit_threshold', 0);
 
 527       $minutesInUnit = $user->getConfigInt('minutes_in_unit', 15);
 
 528       $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";
 
 530     if ($options['show_cost']) {
 
 531       if (MODE_TIME == $trackingMode)
 
 532         $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";
 
 534         $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";
 
 536       $cost_part = ", null as cost, null as expenses";
 
 538     if ($options['show_cost']) {
 
 539       if (MODE_TIME == $trackingMode) {
 
 540         $left_joins = "left join tt_users u on (l.user_id = u.id)";
 
 542         $left_joins = "left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id)";
 
 545     // Prepare sql query part for inner joins.
 
 547     if ($user->isPluginEnabled('ts') && $options['timesheet']) {
 
 548       $timesheet_option = $options['timesheet'];
 
 549       if ($timesheet_option == TIMESHEET_PENDING)
 
 550         $inner_joins .= " inner join tt_timesheets ts on (l.timesheet_id = ts.id and ts.submit_status = 1 and ts.approve_status is null)";
 
 551       else if ($timesheet_option == TIMESHEET_APPROVED)
 
 552         $inner_joins .= " inner join tt_timesheets ts on (l.timesheet_id = ts.id and ts.approve_status = 1)";
 
 553       else if ($timesheet_option == TIMESHEET_NOT_APPROVED)
 
 554         $inner_joins .= " inner join tt_timesheets ts on (l.timesheet_id = ts.id and ts.approve_status = 0)";
 
 556     // Prepare a query for time items.
 
 557     $sql = "select $time_part $units_part $cost_part from tt_log l $left_joins $inner_joins $where";
 
 559     // If we have expenses, query becomes a bit more complex.
 
 560     if ($options['show_cost'] && $user->isPluginEnabled('ex')) {
 
 561       $where = ttReportHelper::getExpenseWhere($options);
 
 562       $sql_for_expenses = "select null as time";
 
 563       if ($options['show_work_units']) $sql_for_expenses .= ", null as units";
 
 564       $sql_for_expenses .= ", sum(cost) as cost, sum(cost) as expenses from tt_expense_items ei $where";
 
 566       // Create a combined query.
 
 567       $combined = "select sum(time) as time";
 
 568       if ($options['show_work_units']) $combined .= ", sum(units) as units";
 
 569       $combined .= ", sum(cost) as cost, sum(expenses) as expenses from (($sql) union all ($sql_for_expenses)) t";
 
 574     $res = $mdb2->query($sql);
 
 575     if (is_a($res, 'PEAR_Error')) die($res->getMessage());
 
 577     $val = $res->fetchRow();
 
 578     $total_time = $val['time'] ? sec_to_time_fmt_hm($val['time']) : null;
 
 579     if ($options['show_cost']) {
 
 580       $total_cost = $val['cost'];
 
 581       if (!$total_cost) $total_cost = '0.00';
 
 582       if ('.' != $decimalMark)
 
 583         $total_cost = str_replace('.', $decimalMark, $total_cost);
 
 584       $total_expenses = $val['expenses'];
 
 585       if (!$total_expenses) $total_expenses = '0.00';
 
 586       if ('.' != $decimalMark)
 
 587         $total_expenses = str_replace('.', $decimalMark, $total_expenses);
 
 590     $dateFormat = $user->getDateFormat();
 
 591     if ($options['period'])
 
 592       $period = new Period($options['period'], new DateAndTime($dateFormat));
 
 594       $period = new Period();
 
 596         new DateAndTime($dateFormat, $options['period_start']),
 
 597         new DateAndTime($dateFormat, $options['period_end']));
 
 600     $totals['start_date'] = $period->getStartDate();
 
 601     $totals['end_date'] = $period->getEndDate();
 
 602     $totals['time'] = $total_time;
 
 603     $totals['units'] = $val['units'];
 
 604     $totals['cost'] = $total_cost;
 
 605     $totals['expenses'] = $total_expenses;
 
 610   // The assignToInvoice assigns a set of records to a specific invoice.
 
 611   static function assignToInvoice($invoice_id, $time_log_ids, $expense_item_ids) {
 
 613     $mdb2 = getConnection();
 
 615     $group_id = $user->getGroup();
 
 616     $org_id = $user->org_id;
 
 619       $sql = "update tt_log set invoice_id = ".$mdb2->quote($invoice_id).
 
 620         " where id in(".join(', ', $time_log_ids).") and group_id = $group_id and org_id = $org_id";
 
 621       $affected = $mdb2->exec($sql);
 
 622       if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
 
 624     if ($expense_item_ids) {
 
 625       $sql = "update tt_expense_items set invoice_id = ".$mdb2->quote($invoice_id).
 
 626         " where id in(".join(', ', $expense_item_ids).") and group_id = $group_id and org_id = $org_id";
 
 627       $affected = $mdb2->exec($sql);
 
 628       if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
 
 632   // The markApproved marks a set of records as either approved or unapproved.
 
 633   static function markApproved($time_log_ids, $expense_item_ids, $approved = true) {
 
 635     $mdb2 = getConnection();
 
 637     $group_id = $user->getGroup();
 
 638     $org_id = $user->org_id;
 
 640     $approved_val = (int) $approved;
 
 642       $sql = "update tt_log set approved = $approved_val".
 
 643         " where id in(".join(', ', $time_log_ids).") and group_id = $group_id and org_id = $org_id";
 
 644       $affected = $mdb2->exec($sql);
 
 645       if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
 
 647     if ($expense_item_ids) {
 
 648       $sql = "update tt_expense_items set approved = $approved_val".
 
 649         " where id in(".join(', ', $expense_item_ids).") and group_id = $group_id and org_id = $org_id";
 
 650       $affected = $mdb2->exec($sql);
 
 651       if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
 
 655   // The markPaid marks a set of records as either paid or unpaid.
 
 656   static function markPaid($time_log_ids, $expense_item_ids, $paid = true) {
 
 658     $mdb2 = getConnection();
 
 660     $group_id = $user->getGroup();
 
 661     $org_id = $user->org_id;
 
 663     $paid_val = (int) $paid;
 
 665       $sql = "update tt_log set paid = $paid_val".
 
 666         " where id in(".join(', ', $time_log_ids).") and group_id = $group_id and org_id = $org_id";
 
 667       $affected = $mdb2->exec($sql);
 
 668       if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
 
 670     if ($expense_item_ids) {
 
 671       $sql = "update tt_expense_items set paid = $paid_val".
 
 672         " where id in(".join(', ', $expense_item_ids).") and group_id = $group_id and org_id = $org_id";
 
 673       $affected = $mdb2->exec($sql);
 
 674       if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
 
 678   // prepareReportBody - prepares an email body for report.
 
 679   static function prepareReportBody($options, $comment = null)
 
 684     // Determine these once as they are used in multiple places in this function.
 
 685     $canViewReports = $user->can('view_reports') || $user->can('view_all_reports');
 
 686     $isClient = $user->isClient();
 
 688     $items = ttReportHelper::getItems($options);
 
 689     $grouping = ttReportHelper::grouping($options);
 
 691       $subtotals = ttReportHelper::getSubtotals($options);
 
 692     $totals = ttReportHelper::getTotals($options);
 
 694     // Use custom fields plugin if it is enabled.
 
 695     if ($user->isPluginEnabled('cf'))
 
 696       $custom_fields = new CustomFields();
 
 698     // Define some styles to use in email.
 
 699     $style_title = 'text-align: center; font-size: 15pt; font-family: Arial, Helvetica, sans-serif;';
 
 700     $tableHeader = 'font-weight: bold; background-color: #a6ccf7; text-align: left;';
 
 701     $tableHeaderCentered = 'font-weight: bold; background-color: #a6ccf7; text-align: center;';
 
 702     $rowItem = 'background-color: #ffffff;';
 
 703     $rowItemAlt = 'background-color: #f5f5f5;';
 
 704     $rowSubtotal = 'background-color: #e0e0e0;';
 
 705     $cellLeftAligned = 'text-align: left; vertical-align: top;';
 
 706     $cellRightAligned = 'text-align: right; vertical-align: top;';
 
 707     $cellLeftAlignedSubtotal = 'font-weight: bold; text-align: left; vertical-align: top;';
 
 708     $cellRightAlignedSubtotal = 'font-weight: bold; text-align: right; vertical-align: top;';
 
 710     // Start creating email body.
 
 712     $body .= '<head><meta http-equiv="content-type" content="text/html; charset='.CHARSET.'"></head>';
 
 716     $body .= '<p style="'.$style_title.'">'.$i18n->get('form.mail.report_subject').': '.$totals['start_date'].' - '.$totals['end_date'].'</p>';
 
 719     if ($comment) $body .= '<p>'.htmlspecialchars($comment).'</p>';
 
 721     if ($options['show_totals_only']) {
 
 722       // Totals only report. Output subtotals.
 
 723       $group_by_header = ttReportHelper::makeGroupByHeader($options);
 
 725       $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
 
 727       $body .= '<td style="'.$tableHeader.'">'.$group_by_header.'</td>';
 
 728       if ($options['show_duration'])
 
 729         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.duration').'</td>';
 
 730       if ($options['show_work_units'])
 
 731         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.work_units_short').'</td>';
 
 732       if ($options['show_cost'])
 
 733         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.cost').'</td>';
 
 735       foreach($subtotals as $subtotal) {
 
 736         $body .= '<tr style="'.$rowSubtotal.'">';
 
 737         $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($subtotal['name'] ? htmlspecialchars($subtotal['name']) : ' ').'</td>';
 
 738         if ($options['show_duration']) {
 
 739           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
 
 740           if ($subtotal['time'] <> '0:00') $body .= $subtotal['time'];
 
 743         if ($options['show_work_units']) {
 
 744           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
 
 745           $body .= $subtotal['units'];
 
 748         if ($options['show_cost']) {
 
 749           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
 
 750           $body .= ($canViewReports || $isClient) ? $subtotal['cost'] : $subtotal['expenses'];
 
 757       $body .= '<tr><td> </td></tr>';
 
 758       $body .= '<tr style="'.$rowSubtotal.'">';
 
 759       $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.total').'</td>';
 
 760       if ($options['show_duration']) {
 
 761         $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
 
 762         if ($totals['time'] <> '0:00') $body .= $totals['time'];
 
 765       if ($options['show_work_units']) {
 
 766         $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
 
 767         $body .= $totals['units'];
 
 770       if ($options['show_cost']) {
 
 771         $body .= '<td nowrap style="'.$cellRightAlignedSubtotal.'">'.htmlspecialchars($user->currency).' ';
 
 772         $body .= ($canViewReports || $isClient) ? $totals['cost'] : $totals['expenses'];
 
 781       // Print table header.
 
 782       $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
 
 784       $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.date').'</td>';
 
 785       if ($canViewReports || $isClient)
 
 786         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.user').'</td>';
 
 787       if ($options['show_client'])
 
 788         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.client').'</td>';
 
 789       if ($options['show_project'])
 
 790         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.project').'</td>';
 
 791       if ($options['show_task'])
 
 792         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.task').'</td>';
 
 793       if ($options['show_custom_field_1'])
 
 794         $body .= '<td style="'.$tableHeader.'">'.htmlspecialchars($custom_fields->fields[0]['label']).'</td>';
 
 795       if ($options['show_start'])
 
 796         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.start').'</td>';
 
 797       if ($options['show_end'])
 
 798         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.finish').'</td>';
 
 799       if ($options['show_duration'])
 
 800         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.duration').'</td>';
 
 801       if ($options['show_work_units'])
 
 802         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.work_units_short').'</td>';
 
 803       if ($options['show_note'])
 
 804         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.note').'</td>';
 
 805       if ($options['show_cost'])
 
 806         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.cost').'</td>';
 
 807       if ($options['show_approved'])
 
 808         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.approved').'</td>';
 
 809       if ($options['show_paid'])
 
 810         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.paid').'</td>';
 
 811       if ($options['show_ip'])
 
 812         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.ip').'</td>';
 
 813       if ($options['show_invoice'])
 
 814         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.invoice').'</td>';
 
 815       if ($options['show_timesheet'])
 
 816         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.timesheet').'</td>';
 
 819       // Initialize variables to print subtotals.
 
 820       if ($items && $grouping) {
 
 821         $print_subtotals = true;
 
 823         $prev_grouped_by = '';
 
 824         $cur_grouped_by = '';
 
 826       // Initialize variables to alternate color of rows for different dates.
 
 829       $row_style = $rowItem;
 
 831       // Print report items.
 
 832       if (is_array($items)) {
 
 833         foreach ($items as $record) {
 
 834           $cur_date = $record['date'];
 
 835           // Print a subtotal row after a block of grouped items.
 
 836           if ($print_subtotals) {
 
 837             $cur_grouped_by = $record['grouped_by'];
 
 838             if ($cur_grouped_by != $prev_grouped_by && !$first_pass) {
 
 839               $body .= '<tr style="'.$rowSubtotal.'">';
 
 840               $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.subtotal').'</td>';
 
 841               $subtotal_name = htmlspecialchars($subtotals[$prev_grouped_by]['name']);
 
 842               if ($canViewReports || $isClient) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['user'].'</td>';
 
 843               if ($options['show_client']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['client'].'</td>';
 
 844               if ($options['show_project']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['project'].'</td>';
 
 845               if ($options['show_task']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['task'].'</td>';
 
 846               if ($options['show_custom_field_1']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['cf_1'].'</td>';
 
 847               if ($options['show_start']) $body .= '<td></td>';
 
 848               if ($options['show_end']) $body .= '<td></td>';
 
 849               if ($options['show_duration']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['time'].'</td>';
 
 850               if ($options['show_work_units']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['units'].'</td>';
 
 851               if ($options['show_note']) $body .= '<td></td>';
 
 852               if ($options['show_cost']) {
 
 853                 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
 
 854                 $body .= ($canViewReports || $isClient) ? $subtotals[$prev_grouped_by]['cost'] : $subtotals[$prev_grouped_by]['expenses'];
 
 857               if ($options['show_approved']) $body .= '<td></td>';
 
 858               if ($options['show_paid']) $body .= '<td></td>';
 
 859               if ($options['show_ip']) $body .= '<td></td>';
 
 860               if ($options['show_invoice']) $body .= '<td></td>';
 
 861               if ($options['show_timesheet']) $body .= '<td></td>';
 
 863               $body .= '<tr><td> </td></tr>';
 
 868           // Print a regular row.
 
 869           if ($cur_date != $prev_date)
 
 870             $row_style = ($row_style == $rowItem) ? $rowItemAlt : $rowItem;
 
 871           $body .= '<tr style="'.$row_style.'">';
 
 872           $body .= '<td style="'.$cellLeftAligned.'">'.$record['date'].'</td>';
 
 873           if ($canViewReports || $isClient)
 
 874             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['user']).'</td>';
 
 875           if ($options['show_client'])
 
 876             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['client']).'</td>';
 
 877           if ($options['show_project'])
 
 878             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['project']).'</td>';
 
 879           if ($options['show_task'])
 
 880             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['task']).'</td>';
 
 881           if ($options['show_custom_field_1'])
 
 882             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['cf_1']).'</td>';
 
 883           if ($options['show_start'])
 
 884             $body .= '<td nowrap style="'.$cellRightAligned.'">'.$record['start'].'</td>';
 
 885           if ($options['show_end'])
 
 886             $body .= '<td nowrap style="'.$cellRightAligned.'">'.$record['finish'].'</td>';
 
 887           if ($options['show_duration'])
 
 888             $body .= '<td style="'.$cellRightAligned.'">'.$record['duration'].'</td>';
 
 889           if ($options['show_work_units'])
 
 890             $body .= '<td style="'.$cellRightAligned.'">'.$record['units'].'</td>';
 
 891           if ($options['show_note'])
 
 892             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['note']).'</td>';
 
 893           if ($options['show_cost'])
 
 894             $body .= '<td style="'.$cellRightAligned.'">'.$record['cost'].'</td>';
 
 895           if ($options['show_approved']) {
 
 896             $body .= '<td style="'.$cellRightAligned.'">';
 
 897             $body .= $record['approved'] == 1 ? $i18n->get('label.yes') : $i18n->get('label.no');
 
 900           if ($options['show_paid']) {
 
 901             $body .= '<td style="'.$cellRightAligned.'">';
 
 902             $body .= $record['paid'] == 1 ? $i18n->get('label.yes') : $i18n->get('label.no');
 
 905           if ($options['show_ip']) {
 
 906             $body .= '<td style="'.$cellRightAligned.'">';
 
 907             $body .= $record['modified'] ? $record['modified_ip'].' '.$record['modified'] : $record['created_ip'].' '.$record['created'];
 
 910           if ($options['show_invoice'])
 
 911             $body .= '<td style="'.$cellRightAligned.'">'.htmlspecialchars($record['invoice']).'</td>';
 
 912           if ($options['show_timesheet'])
 
 913             $body .= '<td style="'.$cellRightAligned.'">'.htmlspecialchars($record['timesheet']).'</td>';
 
 916           $prev_date = $record['date'];
 
 917           if ($print_subtotals)
 
 918             $prev_grouped_by = $record['grouped_by'];
 
 922       // Print a terminating subtotal.
 
 923       if ($print_subtotals) {
 
 924         $body .= '<tr style="'.$rowSubtotal.'">';
 
 925         $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.subtotal').'</td>';
 
 926         $subtotal_name = htmlspecialchars($subtotals[$cur_grouped_by]['name']);
 
 927         if ($canViewReports || $isClient) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['user'].'</td>';
 
 928         if ($options['show_client']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['client'].'</td>';
 
 929         if ($options['show_project']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['project'].'</td>';
 
 930         if ($options['show_task']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['task'].'</td>';
 
 931         if ($options['show_custom_field_1']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['cf_1'].'</td>';
 
 932         if ($options['show_start']) $body .= '<td></td>';
 
 933         if ($options['show_end']) $body .= '<td></td>';
 
 934         if ($options['show_duration']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$cur_grouped_by]['time'].'</td>';
 
 935         if ($options['show_work_units']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$cur_grouped_by]['units'].'</td>';
 
 936         if ($options['show_note']) $body .= '<td></td>';
 
 937         if ($options['show_cost']) {
 
 938           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
 
 939           $body .= ($canViewReports || $isClient) ? $subtotals[$cur_grouped_by]['cost'] : $subtotals[$cur_grouped_by]['expenses'];
 
 942         if ($options['show_approved']) $body .= '<td></td>';
 
 943         if ($options['show_paid']) $body .= '<td></td>';
 
 944         if ($options['show_ip']) $body .= '<td></td>';
 
 945         if ($options['show_invoice']) $body .= '<td></td>';
 
 946         if ($options['show_timesheet']) $body .= '<td></td>';
 
 951       $body .= '<tr><td> </td></tr>';
 
 952       $body .= '<tr style="'.$rowSubtotal.'">';
 
 953       $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.total').'</td>';
 
 954       if ($canViewReports || $isClient) $body .= '<td></td>';
 
 955       if ($options['show_client']) $body .= '<td></td>';
 
 956       if ($options['show_project']) $body .= '<td></td>';
 
 957       if ($options['show_task']) $body .= '<td></td>';
 
 958       if ($options['show_custom_field_1']) $body .= '<td></td>';
 
 959       if ($options['show_start']) $body .= '<td></td>';
 
 960       if ($options['show_end']) $body .= '<td></td>';
 
 961       if ($options['show_duration']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$totals['time'].'</td>';
 
 962       if ($options['show_work_units']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$totals['units'].'</td>';
 
 963       if ($options['show_note']) $body .= '<td></td>';
 
 964       if ($options['show_cost']) {
 
 965         $body .= '<td nowrap style="'.$cellRightAlignedSubtotal.'">'.htmlspecialchars($user->currency).' ';
 
 966         $body .= ($canViewReports || $isClient) ? $totals['cost'] : $totals['expenses'];
 
 969       if ($options['show_approved']) $body .= '<td></td>';
 
 970       if ($options['show_paid']) $body .= '<td></td>';
 
 971       if ($options['show_ip']) $body .= '<td></td>';
 
 972       if ($options['show_invoice']) $body .= '<td></td>';
 
 973       if ($options['show_timesheet']) $body .= '<td></td>';
 
 980     if (!defined('REPORT_FOOTER') || !(REPORT_FOOTER == false))
 
 981       $body .= '<p style="text-align: center;">'.$i18n->get('form.mail.footer').'</p>';
 
 983     // Finish creating email body.
 
 984     $body .= '</body></html>';
 
 989   // checkFavReportCondition - checks whether it is okay to send fav report.
 
 990   static function checkFavReportCondition($options, $condition)
 
 992     $items = ttReportHelper::getItems($options);
 
 994     $condition = trim(str_replace('count', '', $condition));
 
 996     $greater_or_equal = ttStartsWith($condition, '>=');
 
 997     if ($greater_or_equal) $condition = trim(str_replace('>=', '', $condition));
 
 999     $less_or_equal = ttStartsWith($condition, '<=');
 
1000     if ($less_or_equal) $condition = trim(str_replace('<=', '', $condition));
 
1002     $not_equal = ttStartsWith($condition, '<>');
 
1003     if ($not_equal) $condition = trim(str_replace('<>', '', $condition));
 
1005     $greater = ttStartsWith($condition, '>');
 
1006     if ($greater) $condition = trim(str_replace('>', '', $condition));
 
1008     $less = ttStartsWith($condition, '<');
 
1009     if ($less) $condition = trim(str_replace('<', '', $condition));
 
1011     $equal = ttStartsWith($condition, '=');
 
1012     if ($equal) $condition = trim(str_replace('=', '', $condition));
 
1014     $count_required = (int) $condition;
 
1016     if ($greater && count($items) > $count_required) return true;
 
1017     if ($greater_or_equal && count($items) >= $count_required) return true;
 
1018     if ($less && count($items) < $count_required) return true;
 
1019     if ($less_or_equal && count($items) <= $count_required) return true;
 
1020     if ($equal && count($items) == $count_required) return true;
 
1021     if ($not_equal && count($items) <> $count_required) return true;
 
1026   // sendFavReport - sends a favorite report to a specified email, called from cron.php
 
1027   static function sendFavReport($options, $subject, $email, $cc) {
 
1028     // We are called from cron.php, we have no $bean in session.
 
1029     // cron.php sets global $user and $i18n objects to match our favorite report user.
 
1033     // Prepare report body.
 
1034     $body = ttReportHelper::prepareReportBody($options);
 
1036     import('mail.Mailer');
 
1037     $mailer = new Mailer();
 
1038     $mailer->setCharSet(CHARSET);
 
1039     $mailer->setContentType('text/html');
 
1040     $mailer->setSender(SENDER);
 
1042       $mailer->setReceiverCC($cc);
 
1043     if (!empty($user->bcc_email))
 
1044       $mailer->setReceiverBCC($user->bcc_email);
 
1045     $mailer->setReceiver($email);
 
1046     $mailer->setMailMode(MAIL_MODE);
 
1047     if (empty($subject)) $subject = $options['name'];
 
1048     if (!$mailer->send($subject, $body))
 
1054   // getReportOptions - returns an array of report options constructed from session bean.
 
1056   // Note: similarly to ttFavReportHelper::getReportOptions, this function is a part of
 
1057   // refactoring to simplify maintenance of report generating functions, as we currently
 
1058   // have 2 sets: normal reporting (from bean), and fav report emailing (from db fields).
 
1059   // Using options obtained from either db or bean shall allow us to use only one set of functions.
 
1060   static function getReportOptions($bean) {
 
1063     // Prepare an array of report options.
 
1066     // Construct one by one.
 
1067     $options['name'] = null; // No name required.
 
1068     $options['user_id'] = $user->id; // Not sure if we need user_id here. Fav reports use it to recycle $user object in cron.php.
 
1069     $options['client_id'] = $bean->getAttribute('client');
 
1070     $options['cf_1_option_id'] = $bean->getAttribute('option');
 
1071     $options['project_id'] = $bean->getAttribute('project');
 
1072     $options['task_id'] = $bean->getAttribute('task');
 
1073     $options['billable'] = $bean->getAttribute('include_records');
 
1074     $options['invoice'] = $bean->getAttribute('invoice');
 
1075     $options['paid_status'] = $bean->getAttribute('paid_status');
 
1076     $options['approved'] = $bean->getAttribute('approved');
 
1077     if ($user->isPluginEnabled('ap') && $user->isClient() && !$user->can('view_client_unapproved'))
 
1078       $options['approved'] = 1; // Restrict clients to approved records only.
 
1079     $options['timesheet'] = $bean->getAttribute('timesheet');
 
1080     if (is_array($bean->getAttribute('users'))) $options['users'] = join(',', $bean->getAttribute('users'));
 
1081     $options['period'] = $bean->getAttribute('period');
 
1082     $options['period_start'] = $bean->getAttribute('start_date');
 
1083     $options['period_end'] = $bean->getAttribute('end_date');
 
1084     $options['show_client'] = $bean->getAttribute('chclient');
 
1085     $options['show_invoice'] = $bean->getAttribute('chinvoice');
 
1086     $options['show_approved'] = $bean->getAttribute('chapproved');
 
1087     $options['show_paid'] = $bean->getAttribute('chpaid');
 
1088     $options['show_ip'] = $bean->getAttribute('chip');
 
1089     $options['show_project'] = $bean->getAttribute('chproject');
 
1090     $options['show_start'] = $bean->getAttribute('chstart');
 
1091     $options['show_duration'] = $bean->getAttribute('chduration');
 
1092     $options['show_cost'] = $bean->getAttribute('chcost');
 
1093     $options['show_task'] = $bean->getAttribute('chtask');
 
1094     $options['show_end'] = $bean->getAttribute('chfinish');
 
1095     $options['show_note'] = $bean->getAttribute('chnote');
 
1096     $options['show_custom_field_1'] = $bean->getAttribute('chcf_1');
 
1097     $options['show_work_units'] = $bean->getAttribute('chunits');
 
1098     $options['show_timesheet'] = $bean->getAttribute('chtimesheet');
 
1099     $options['show_totals_only'] = $bean->getAttribute('chtotalsonly');
 
1100     $options['group_by1'] = $bean->getAttribute('group_by1');
 
1101     $options['group_by2'] = $bean->getAttribute('group_by2');
 
1102     $options['group_by3'] = $bean->getAttribute('group_by3');
 
1106   // verifyBean is a security function to make sure data in bean makes sense for a group.
 
1107   static function verifyBean($bean) {
 
1111     $users_in_bean = $bean->getAttribute('users');
 
1112     if (is_array($users_in_bean)) {
 
1113       $users_in_group = ttGroupHelper::getUsers();
 
1114       foreach ($users_in_group as $user_in_group) {
 
1115         $valid_ids[] = $user_in_group['id'];
 
1117       foreach ($users_in_bean as $user_in_bean) {
 
1118         if (!in_array($user_in_bean, $valid_ids)) {
 
1124     // TODO: add additional checks here. Perhaps do it before saving the bean for consistency.
 
1128   // makeGroupByKey builds a combined group by key from group_by1, group_by2 and group_by3 values
 
1129   // (passed in $options) and a row of data ($row obtained from a db query).
 
1130   static function makeGroupByKey($options, $row) {
 
1131     if ($options['group_by1'] != null && $options['group_by1'] != 'no_grouping') {
 
1132       // We have group_by1.
 
1133       $group_by1 = $options['group_by1'];
 
1134       $group_by1_value = $row[$group_by1];
 
1135       //if ($group_by1 == 'date') $group_by1_value = ttDateToUserFormat($group_by1_value);
 
1136       if (empty($group_by1_value)) $group_by1_value = 'Null'; // To match what comes out of makeConcatPart.
 
1137       $group_by_key .= ' - '.$group_by1_value;
 
1139     if ($options['group_by2'] != null && $options['group_by2'] != 'no_grouping') {
 
1140       // We have group_by2.
 
1141       $group_by2 = $options['group_by2'];
 
1142       $group_by2_value = $row[$group_by2];
 
1143       //if ($group_by2 == 'date') $group_by2_value = ttDateToUserFormat($group_by2_value);
 
1144       if (empty($group_by2_value)) $group_by2_value = 'Null'; // To match what comes out of makeConcatPart.
 
1145       $group_by_key .= ' - '.$group_by2_value;
 
1147     if ($options['group_by3'] != null && $options['group_by3'] != 'no_grouping') {
 
1148       // We have group_by3.
 
1149       $group_by3 = $options['group_by3'];
 
1150       $group_by3_value = $row[$group_by3];
 
1151       //if ($group_by3 == 'date') $group_by3_value = ttDateToUserFormat($group_by3_value);
 
1152       if (empty($group_by3_value)) $group_by3_value = 'Null'; // To match what comes out of makeConcatPart.
 
1153       $group_by_key .= ' - '.$group_by3_value;
 
1155     $group_by_key = trim($group_by_key, ' -');
 
1156     return $group_by_key;
 
1159   // makeGroupByPart builds a combined group by part for sql query for time items using group_by1,
 
1160   // group_by2, and group_by3 values passed in $options.
 
1161   static function makeGroupByPart($options) {
 
1162     if (!ttReportHelper::grouping($options)) return null;
 
1164     $group_by1 = $options['group_by1'];
 
1165     $group_by2 = $options['group_by2'];
 
1166     $group_by3 = $options['group_by3'];
 
1168     switch ($group_by1) {
 
1170         $group_by_parts .= ', l.date';
 
1173         $group_by_parts .= ', u.name';
 
1176         $group_by_parts .= ', c.name';
 
1179         $group_by_parts .= ', p.name';
 
1182         $group_by_parts .= ', t.name';
 
1185         $group_by_parts .= ', cfo.value';
 
1188     switch ($group_by2) {
 
1190         $group_by_parts .= ', l.date';
 
1193         $group_by_parts .= ', u.name';
 
1196         $group_by_parts .= ', c.name';
 
1199         $group_by_parts .= ', p.name';
 
1202         $group_by_parts .= ', t.name';
 
1205         $group_by_parts .= ', cfo.value';
 
1208     switch ($group_by3) {
 
1210         $group_by_parts .= ', l.date';
 
1213         $group_by_parts .= ', u.name';
 
1216         $group_by_parts .= ', c.name';
 
1219         $group_by_parts .= ', p.name';
 
1222         $group_by_parts .= ', t.name';
 
1225         $group_by_parts .= ', cfo.value';
 
1228     // Remove garbage from the beginning.
 
1229     $group_by_parts = ltrim($group_by_parts, ', ');
 
1230     $group_by_part = "group by $group_by_parts";
 
1231     return $group_by_part;
 
1234   // makeGroupByExpensesPart builds a combined group by part for sql query for expense items using
 
1235   // group_by1, group_by2, and group_by3 values passed in $options.
 
1236   static function makeGroupByExpensesPart($options) {
 
1237     $no_grouping = ($options['group_by1'] == null || $options['group_by1'] == 'no_grouping') &&
 
1238       ($options['group_by2'] == null || $options['group_by2'] == 'no_grouping') &&
 
1239       ($options['group_by3'] == null || $options['group_by3'] == 'no_grouping');
 
1240     if ($no_grouping) return null;
 
1242     $group_by1 = $options['group_by1'];
 
1243     $group_by2 = $options['group_by2'];
 
1244     $group_by3 = $options['group_by3'];
 
1246     switch ($group_by1) {
 
1248         $group_by_parts .= ', ei.date';
 
1251         $group_by_parts .= ', u.name';
 
1254         $group_by_parts .= ', c.name';
 
1257         $group_by_parts .= ', p.name';
 
1260     switch ($group_by2) {
 
1262         $group_by_parts .= ', ei.date';
 
1265         $group_by_parts .= ', u.name';
 
1268         $group_by_parts .= ', c.name';
 
1271         $group_by_parts .= ', p.name';
 
1274     switch ($group_by3) {
 
1276         $group_by_parts .= ', ei.date';
 
1279         $group_by_parts .= ', u.name';
 
1282         $group_by_parts .= ', c.name';
 
1285         $group_by_parts .= ', p.name';
 
1288     // Remove garbage from the beginning.
 
1289     $group_by_parts = ltrim($group_by_parts, ', ');
 
1290     if ($group_by_parts)
 
1291       $group_by_part = "group by $group_by_parts";
 
1292     return $group_by_part;
 
1295   // makeConcatPart builds a concatenation part for getSubtotals query (for time items).
 
1296   static function makeConcatPart($options) {
 
1297     $group_by1 = $options['group_by1'];
 
1298     $group_by2 = $options['group_by2'];
 
1299     $group_by3 = $options['group_by3'];
 
1301     switch ($group_by1) {
 
1303         $what_to_concat .= ", ' - ', l.date";
 
1306         $what_to_concat .= ", ' - ', u.name";
 
1307         $fields_part .= ', u.name as user';
 
1310         $what_to_concat .= ", ' - ', coalesce(c.name, 'Null')";
 
1311         $fields_part .= ', c.name as client';
 
1314         $what_to_concat .= ", ' - ', coalesce(p.name, 'Null')";
 
1315         $fields_part .= ', p.name as project';
 
1318         $what_to_concat .= ", ' - ', coalesce(t.name, 'Null')";
 
1319         $fields_part .= ', t.name as task';
 
1322         $what_to_concat .= ", ' - ', coalesce(cfo.value, 'Null')";
 
1323         $fields_part .= ', cfo.value as cf_1';
 
1326     switch ($group_by2) {
 
1328         $what_to_concat .= ", ' - ', l.date";
 
1331         $what_to_concat .= ", ' - ', u.name";
 
1332         $fields_part .= ', u.name as user';
 
1335         $what_to_concat .= ", ' - ', coalesce(c.name, 'Null')";
 
1336         $fields_part .= ', c.name as client';
 
1339         $what_to_concat .= ", ' - ', coalesce(p.name, 'Null')";
 
1340         $fields_part .= ', p.name as project';
 
1343         $what_to_concat .= ", ' - ', coalesce(t.name, 'Null')";
 
1344         $fields_part .= ', t.name as task';
 
1347         $what_to_concat .= ", ' - ', coalesce(cfo.value, 'Null')";
 
1348         $fields_part .= ', cfo.value as cf_1';
 
1351     switch ($group_by3) {
 
1353         $what_to_concat .= ", ' - ', l.date";
 
1356         $what_to_concat .= ", ' - ', u.name";
 
1357         $fields_part .= ', u.name as user';
 
1360         $what_to_concat .= ", ' - ', coalesce(c.name, 'Null')";
 
1361         $fields_part .= ', c.name as client';
 
1364         $what_to_concat .= ", ' - ', coalesce(p.name, 'Null')";
 
1365         $fields_part .= ', p.name as project';
 
1368         $what_to_concat .= ", ' - ', coalesce(t.name, 'Null')";
 
1369         $fields_part .= ', t.name as task';
 
1372         $what_to_concat .= ", ' - ', coalesce(cfo.value, 'Null')";
 
1373         $fields_part .= ', cfo.value as cf_1';
 
1376     // Remove garbage from both ends.
 
1377     $what_to_concat = trim($what_to_concat, "', -");
 
1378     $concat_part = "concat($what_to_concat) as group_field";
 
1379     $concat_part = trim($concat_part, ' -');
 
1380     return "$concat_part $fields_part";
 
1383   // makeConcatPart builds a concatenation part for getSubtotals query (for expense items).
 
1384   static function makeConcatExpensesPart($options) {
 
1385     $group_by1 = $options['group_by1'];
 
1386     $group_by2 = $options['group_by2'];
 
1387     $group_by3 = $options['group_by3'];
 
1389     switch ($group_by1) {
 
1391         $what_to_concat .= ", ' - ', ei.date";
 
1394         $what_to_concat .= ", ' - ', u.name";
 
1395         $fields_part .= ', u.name as user';
 
1398         $what_to_concat .= ", ' - ', coalesce(c.name, 'Null')";
 
1399         $fields_part .= ', c.name as client';
 
1402         $what_to_concat .= ", ' - ', coalesce(p.name, 'Null')";
 
1403         $fields_part .= ', p.name as project';
 
1407         $what_to_concat .= ", ' - ', 'Null'";
 
1408         $fields_part .= ', null as task';
 
1412         $what_to_concat .= ", ' - ', 'Null'";
 
1413         $fields_part .= ', null as cf_1';
 
1416     switch ($group_by2) {
 
1418         $what_to_concat .= ", ' - ', ei.date";
 
1421         $what_to_concat .= ", ' - ', u.name";
 
1422         $fields_part .= ', u.name as user';
 
1425         $what_to_concat .= ", ' - ', coalesce(c.name, 'Null')";
 
1426         $fields_part .= ', c.name as client';
 
1429         $what_to_concat .= ", ' - ', coalesce(p.name, 'Null')";
 
1430         $fields_part .= ', p.name as project';
 
1434         $what_to_concat .= ", ' - ', 'Null'";
 
1435         $fields_part .= ', null as task';
 
1439         $what_to_concat .= ", ' - ', 'Null'";
 
1440         $fields_part .= ', null as cf_1';
 
1443     switch ($group_by3) {
 
1445         $what_to_concat .= ", ' - ', ei.date";
 
1448         $what_to_concat .= ", ' - ', u.name";
 
1449         $fields_part .= ', u.name as user';
 
1452         $what_to_concat .= ", ' - ', coalesce(c.name, 'Null')";
 
1453         $fields_part .= ', c.name as client';
 
1456         $what_to_concat .= ", ' - ', coalesce(p.name, 'Null')";
 
1457         $fields_part .= ', p.name as project';
 
1461         $what_to_concat .= ", ' - ', 'Null'";
 
1462         $fields_part .= ', null as task';
 
1466         $what_to_concat .= ", ' - ', 'Null'";
 
1467         $fields_part .= ', null as cf_1';
 
1470     // Remove garbage from the beginning.
 
1471     if ($what_to_concat)
 
1472         $what_to_concat = substr($what_to_concat, 8);
 
1473     $concat_part = "concat($what_to_concat) as group_field";
 
1474     return "$concat_part $fields_part";
 
1477   // makeCombinedSelectPart builds a list of fields for a combined select on a union for getSubtotals.
 
1478   // This is used when we include expenses.
 
1479   static function makeCombinedSelectPart($options) {
 
1480     $group_by1 = $options['group_by1'];
 
1481     $group_by2 = $options['group_by2'];
 
1482     $group_by3 = $options['group_by3'];
 
1484     $fields = "group_field";
 
1486     switch ($group_by1) {
 
1488         $fields .= ', user';
 
1491         $fields_part .= ', client';
 
1494         $fields .= ', project';
 
1498         $fields .= ', task';
 
1502         $fields .= ', cf_1';
 
1505     switch ($group_by2) {
 
1507         $fields .= ', user';
 
1510         $fields_part .= ', client';
 
1513         $fields .= ', project';
 
1517         $fields .= ', task';
 
1521         $fields .= ', cf_1';
 
1524     switch ($group_by3) {
 
1526         $fields .= ', user';
 
1529         $fields_part .= ', client';
 
1532         $fields .= ', project';
 
1536         $fields .= ', task';
 
1540         $fields .= ', cf_1';
 
1546   // makeJoinPart builds a left join part for getSubtotals query (for time items).
 
1547   static function makeJoinPart($options) {
 
1550     $trackingMode = $user->getTrackingMode();
 
1551     if (ttReportHelper::groupingBy('user', $options) || MODE_TIME == $trackingMode) {
 
1552       $join .= ' left join tt_users u on (l.user_id = u.id)';
 
1554     if (ttReportHelper::groupingBy('client', $options)) {
 
1555       $join .= ' left join tt_clients c on (l.client_id = c.id)';
 
1557     if (ttReportHelper::groupingBy('project', $options)) {
 
1558       $join .= ' left join tt_projects p on (l.project_id = p.id)';
 
1560     if (ttReportHelper::groupingBy('task', $options)) {
 
1561       $join .= ' left join tt_tasks t on (l.task_id = t.id)';
 
1563     if (ttReportHelper::groupingBy('cf_1', $options)) {
 
1564       $custom_fields = new CustomFields();
 
1565       if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_TEXT)
 
1566         $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)';
 
1567       elseif ($custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN)
 
1568         $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)';
 
1570     if ($options['show_cost'] && $trackingMode != MODE_TIME) {
 
1571       $join .= ' left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id)';
 
1573     // Prepare inner joins.
 
1574     $inner_joins = null;
 
1575     if ($user->isPluginEnabled('ts') && $options['timesheet']) {
 
1576       $timesheet_option = $options['timesheet'];
 
1577       if ($timesheet_option == TIMESHEET_PENDING)
 
1578         $inner_joins .= " inner join tt_timesheets ts on (l.timesheet_id = ts.id and ts.submit_status = 1 and ts.approve_status is null)";
 
1579       else if ($timesheet_option == TIMESHEET_APPROVED)
 
1580         $inner_joins .= " inner join tt_timesheets ts on (l.timesheet_id = ts.id and ts.approve_status = 1)";
 
1581       else if ($timesheet_option == TIMESHEET_NOT_APPROVED)
 
1582         $inner_joins .= " inner join tt_timesheets ts on (l.timesheet_id = ts.id and ts.approve_status = 0)";
 
1584     $join .= $inner_joins;
 
1588   // makeWorkUnitPart builds an sql part for work units for time items.
 
1589   static function makeWorkUnitPart($options) {
 
1592     $workUnits = $options['show_work_units'];
 
1594       $unitTotalsOnly = $user->getConfigOption('unit_totals_only');
 
1595       $firstUnitThreshold = $user->getConfigInt('1st_unit_threshold', 0);
 
1596       $minutesInUnit = $user->getConfigInt('minutes_in_unit', 15);
 
1597       if ($unitTotalsOnly)
 
1598         $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";
 
1600         $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";
 
1602     return $work_unit_part;
 
1605   // makeCostPart builds a cost part for time items.
 
1606   static function makeCostPart($options) {
 
1609     if ($options['show_cost']) {
 
1610       if (MODE_TIME == $user->getTrackingMode())
 
1611         $cost_part = ", sum(cast(l.billable * coalesce(u.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10, 2))) as cost";
 
1613         $cost_part .= ", sum(cast(l.billable * coalesce(upb.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10,2))) as cost";
 
1618   // makeJoinExpensesPart builds a left join part for getSubtotals query for expense items.
 
1619   static function makeJoinExpensesPart($options) {
 
1622     if (ttReportHelper::groupingBy('user', $options)) {
 
1623       $join .= ' left join tt_users u on (ei.user_id = u.id)';
 
1625     if (ttReportHelper::groupingBy('client', $options)) {
 
1626       $join .= ' left join tt_clients c on (ei.client_id = c.id)';
 
1628     if (ttReportHelper::groupingBy('project', $options)) {
 
1629       $join .= ' left join tt_projects p on (ei.project_id = p.id)';
 
1634   // grouping determines if we are grouping the report by either group_by1,
 
1635   // group_by2, or group_by3 values passed in $options.
 
1636   static function grouping($options) {
 
1637     $grouping = ($options['group_by1'] != null && $options['group_by1'] != 'no_grouping') ||
 
1638       ($options['group_by2'] != null && $options['group_by2'] != 'no_grouping') ||
 
1639       ($options['group_by3'] != null && $options['group_by3'] != 'no_grouping');
 
1643   // groupingBy determines if we are grouping a report by a value of $what
 
1644   // ('date', 'user', 'project', etc.) by checking group_by1, group_by2,
 
1645   // and group_by3 values passed in $options.
 
1646   static function groupingBy($what, $options) {
 
1647     $grouping = ($options['group_by1'] == $what) || ($options['group_by2'] == $what) || ($options['group_by3'] == $what);
 
1651   // makeGroupByHeader builds a column header for a totals-only report using group_by1,
 
1652   // group_by2, and group_by3 values passed in $options.
 
1653   static function makeGroupByHeader($options) {
 
1655     global $custom_fields;
 
1657     $no_grouping = ($options['group_by1'] == null || $options['group_by1'] == 'no_grouping') &&
 
1658       ($options['group_by2'] == null || $options['group_by2'] == 'no_grouping') &&
 
1659       ($options['group_by3'] == null || $options['group_by3'] == 'no_grouping');
 
1660     if ($no_grouping) return null;
 
1662     if ($options['group_by1'] != null && $options['group_by1'] != 'no_grouping') {
 
1663       // We have group_by1.
 
1664       $group_by1 = $options['group_by1'];
 
1665       if ('cf_1' == $group_by1)
 
1666         $group_by_header .= ' - '.$custom_fields->fields[0]['label'];
 
1668         $key = 'label.'.$group_by1;
 
1669         $group_by_header .= ' - '.$i18n->get($key);
 
1672     if ($options['group_by2'] != null && $options['group_by2'] != 'no_grouping') {
 
1673       // We have group_by2.
 
1674       $group_by2 = $options['group_by2'];
 
1675       if ('cf_1' == $group_by2)
 
1676         $group_by_header .= ' - '.$custom_fields->fields[0]['label'];
 
1678         $key = 'label.'.$group_by2;
 
1679         $group_by_header .= ' - '.$i18n->get($key);
 
1682     if ($options['group_by3'] != null && $options['group_by3'] != 'no_grouping') {
 
1683       // We have group_by3.
 
1684       $group_by3 = $options['group_by3'];
 
1685       if ('cf_1' == $group_by3)
 
1686         $group_by_header .= ' - '.$custom_fields->fields[0]['label'];
 
1688         $key = 'label.'.$group_by3;
 
1689         $group_by_header .= ' - '.$i18n->get($key);
 
1692     $group_by_header = ltrim($group_by_header, ' -');
 
1693     return $group_by_header;
 
1696   // makeGroupByXmlTag creates an xml tag for a totals only report using group_by1,
 
1697   // group_by2, and group_by3 values passed in $options.
 
1698   static function makeGroupByXmlTag($options) {
 
1699     if ($options['group_by1'] != null && $options['group_by1'] != 'no_grouping') {
 
1700       // We have group_by1.
 
1701       $tag .= '_'.$options['group_by1'];
 
1703     if ($options['group_by2'] != null && $options['group_by2'] != 'no_grouping') {
 
1704       // We have group_by2.
 
1705       $tag .= '_'.$options['group_by2'];
 
1707     if ($options['group_by3'] != null && $options['group_by3'] != 'no_grouping') {
 
1708       // We have group_by3.
 
1709       $tag .= '_'.$options['group_by3'];
 
1711     $tag = ltrim($tag, '_');
 
1715   // makeGroupByLabel builds a label for one row in a "Totals only" report of grouped by items.
 
1716   // It does one thing: if we are grouping by date, the date format is converted for user.
 
1717   static function makeGroupByLabel($key, $options) {
 
1718     if (!ttReportHelper::groupingBy('date', $options))
 
1719       return $key; // No need to format.
 
1722     if ($user->getDateFormat() == DB_DATEFORMAT)
 
1723       return $key; // No need to format.
 
1726     if (preg_match('/\d\d\d\d-\d\d-\d\d/', $key, $matches)) {
 
1727       // Replace the first found match of a date in DB_DATEFORMAT.
 
1728       // This is not entirely clean but better than nothing for a label in a row.
 
1729       $userDate = ttDateToUserFormat($matches[0]);
 
1730       $label = str_replace($matches[0], $userDate, $key);