Some more work in progress on timesheet reporting.
[timetracker.git] / WEB-INF / lib / ttReportHelper.class.php
1 <?php
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.
10 // |
11 // | There are only two ways to violate the license:
12 // |
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).
16 // |
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).
20 // |
21 // | This license applies to this document only, not any other software
22 // | that it may be combined with.
23 // |
24 // +----------------------------------------------------------------------+
25 // | Contributors:
26 // | https://www.anuko.com/time_tracker/credits.htm
27 // +----------------------------------------------------------------------+
28
29 import('ttClientHelper');
30 import('DateAndTime');
31 import('Period');
32 import('ttTimeHelper');
33
34 require_once(dirname(__FILE__).'/../../plugins/CustomFields.class.php');
35
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.
43
44 // Class ttReportHelper is used for help with reports.
45 class ttReportHelper {
46
47   // getWhere prepares a WHERE clause for a report query.
48   static function getWhere($options) {
49     global $user;
50
51     $group_id = $user->getGroup();
52     $org_id = $user->org_id;
53
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";
57       return $where;
58     }
59
60     // Prepare dropdown parts.
61     $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';
77
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)";
82     else
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";
85
86     // Prepare sql query part for where.
87     $dateFormat = $user->getDateFormat();
88     if ($options['period'])
89       $period = new Period($options['period'], new DateAndTime($dateFormat));
90     else {
91       $period = new Period();
92       $period->setPeriod(
93         new DateAndTime($dateFormat, $options['period_start']),
94         new DateAndTime($dateFormat, $options['period_end']));
95     }
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";
98     return $where;
99   }
100
101   // getExpenseWhere prepares WHERE clause for expenses query in a report.
102   static function getExpenseWhere($options) {
103     global $user;
104
105     $group_id = $user->getGroup();
106     $org_id = $user->org_id;
107
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";
111       return $where;
112     }
113
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';
127
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)";
132     else
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";
135
136     // Prepare sql query part for where.
137     $dateFormat = $user->getDateFormat();
138     if ($options['period'])
139       $period = new Period($options['period'], new DateAndTime($dateFormat));
140     else {
141       $period = new Period();
142       $period->setPeriod(
143         new DateAndTime($dateFormat, $options['period_start']),
144         new DateAndTime($dateFormat, $options['period_end']));
145     }
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";
148     return $where;
149   }
150
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) {
155     global $user;
156     $mdb2 = getConnection();
157
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();
161
162     $grouping = ttReportHelper::grouping($options);
163     if ($grouping) {
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);
170     }
171     $convertTo12Hour = ('%I:%M %p' == $user->getTimeFormat()) && ($options['show_start'] || $options['show_end']);
172     $trackingMode = $user->getTrackingMode();
173     $decimalMark = $user->getDecimalMark();
174
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');
192     // Add custom field.
193     $include_cf_1 = $options['show_custom_field_1'] || $grouping_by_cf_1;
194     if ($include_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');
201       }
202     }
203     // Add start time.
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");
207     }
208     // Add finish time.
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");
211     // Add duration.
212     if ($options['show_duration'])
213       array_push($fields, "TIME_FORMAT(l.duration, '%k:%i') as duration");
214     // Add work units.
215     if ($options['show_work_units']) {
216       if ($user->getConfigOption('unit_totals_only'))
217         array_push($fields, "null as units");
218       else {
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");
222       }
223     }
224     // Add note.
225     if ($options['show_note'])
226       array_push($fields, 'l.comment as note');
227     // Handle cost.
228     $includeCost = $options['show_cost'];
229     if ($includeCost) {
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.
232       else
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"); 
235     }
236     // Add paid status.
237     if ($canViewReports && $options['show_paid'])
238       array_push($fields, 'l.paid');
239     // Add IP address.
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');
245     }
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');
252
253     // Prepare sql query part for left joins.
254     $left_joins = null;
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)";
265     if ($include_cf_1) {
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)";
271       }
272     }
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)";
275
276     // Prepare sql query part for inner joins.
277     $inner_joins = null;
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.
288     }
289
290     $where = ttReportHelper::getWhere($options);
291
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.
296
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
299
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.
320       }
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');
332       // Add paid status.
333       if ($canViewReports && $options['show_paid'])
334         array_push($fields, 'ei.paid');
335       // Add IP address.
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');
341       }
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');
347
348       // Prepare sql query part for left joins.
349       $left_joins = null;
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)";
358
359       // Prepare sql query part for inner joins.
360       $inner_joins = null;
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.
371       }
372
373       $where = ttReportHelper::getExpenseWhere($options);
374
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";
377
378       // Construct a union.
379       $sql = "($sql) union all ($sql_for_expense_items)";
380     }
381
382     // Determine sort part.
383     $sort_part = ' order by ';
384     if ($grouping) {
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.
390     } else {
391       $sort_part .= 'date';
392     }
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';
398
399     $sql .= $sort_part;
400     // By now we are ready with sql.
401
402     // Obtain items for report.
403     $res = $mdb2->query($sql);
404     if (is_a($res, 'PEAR_Error')) die($res->getMessage());
405
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']);
412       }
413       if (isset($val['cost'])) {
414         if ('.' != $decimalMark)
415           $val['cost'] = str_replace('.', $decimalMark, $val['cost']);
416       }
417       if (isset($val['expense'])) {
418         if ('.' != $decimalMark)
419           $val['expense'] = str_replace('.', $decimalMark, $val['expense']);
420       }
421
422       if ($grouping) $val['grouped_by'] = ttReportHelper::makeGroupByKey($options, $val);
423       $val['date'] = ttDateToUserFormat($val['date']);
424
425       $report_items[] = $val;
426     }
427
428     return $report_items;
429   }
430
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']);
436
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'];
443     }
444     $report_item_ids = trim($report_item_ids, ',');
445     $report_item_expense_ids = trim($report_item_expense_ids, ',');
446
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;
450   }
451
452   // getFromSession obtains tt_log and tt_expense_items ids stored in user session.
453   static function getFromSession() {
454     $items = array();
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);
461     return $items;
462   }
463
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) {
468     global $user;
469     $mdb2 = getConnection();
470
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);
477
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.
481
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
484
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";
492
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";
498       $sql = $combined;
499     }
500
501     // Execute query.
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']);
512         }
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']);
514       } else
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']);
516     }
517
518     return $subtotals;
519   }
520
521   // getTotals calculates total hours and cost for all report items.
522   static function getTotals($options)
523   {
524     global $user;
525     $mdb2 = getConnection();
526
527     $trackingMode = $user->getTrackingMode();
528     $decimalMark = $user->getDecimalMark();
529     $where = ttReportHelper::getWhere($options);
530
531     // Prepare parts.
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";
538     }
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";
542       else
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";
544     } else {
545       $cost_part = ", null as cost, null as expenses";
546     }
547     if ($options['show_cost']) {
548       if (MODE_TIME == $trackingMode) {
549         $left_joins = "left join tt_users u on (l.user_id = u.id)";
550       } else {
551         $left_joins = "left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id)";
552       }
553     }
554     // Prepare sql query part for inner joins.
555     $inner_joins = null;
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)";
564     }
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";
567
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.
571       $inner_joins = null;
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)";
580       }
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";
585
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";
590       $sql = $combined;
591     }
592
593     // Execute query.
594     $res = $mdb2->query($sql);
595     if (is_a($res, 'PEAR_Error')) die($res->getMessage());
596
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);
608     }
609
610     $dateFormat = $user->getDateFormat();
611     if ($options['period'])
612       $period = new Period($options['period'], new DateAndTime($dateFormat));
613     else {
614       $period = new Period();
615       $period->setPeriod(
616         new DateAndTime($dateFormat, $options['period_start']),
617         new DateAndTime($dateFormat, $options['period_end']));
618     }
619
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;
626
627     return $totals;
628   }
629
630   // The assignToInvoice assigns a set of records to a specific invoice.
631   static function assignToInvoice($invoice_id, $time_log_ids, $expense_item_ids) {
632     global $user;
633     $mdb2 = getConnection();
634
635     $group_id = $user->getGroup();
636     $org_id = $user->org_id;
637
638     if ($time_log_ids) {
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());
643     }
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());
649     }
650   }
651
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) {
654     global $user;
655     $mdb2 = getConnection();
656
657     $group_id = $user->getGroup();
658     $org_id = $user->org_id;
659
660     $paid_val = (int) $paid;
661     if ($time_log_ids) {
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());
666     }
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());
672     }
673   }
674
675   // prepareReportBody - prepares an email body for report.
676   static function prepareReportBody($options, $comment = null)
677   {
678     global $user;
679     global $i18n;
680
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();
684
685     $items = ttReportHelper::getItems($options);
686     $grouping = ttReportHelper::grouping($options);
687     if ($grouping)
688       $subtotals = ttReportHelper::getSubtotals($options);
689     $totals = ttReportHelper::getTotals($options);
690
691     // Use custom fields plugin if it is enabled.
692     if ($user->isPluginEnabled('cf'))
693       $custom_fields = new CustomFields();
694
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;';
706
707     // Start creating email body.
708     $body = '<html>';
709     $body .= '<head><meta http-equiv="content-type" content="text/html; charset='.CHARSET.'"></head>';
710     $body .= '<body>';
711
712     // Output title.
713     $body .= '<p style="'.$style_title.'">'.$i18n->get('form.mail.report_subject').': '.$totals['start_date'].' - '.$totals['end_date'].'</p>';
714
715     // Output comment.
716     if ($comment) $body .= '<p>'.htmlspecialchars($comment).'</p>';
717
718     if ($options['show_totals_only']) {
719       // Totals only report. Output subtotals.
720       $group_by_header = ttReportHelper::makeGroupByHeader($options);
721
722       $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
723       $body .= '<tr>';
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>';
731       $body .= '</tr>';
732       foreach($subtotals as $subtotal) {
733         $body .= '<tr style="'.$rowSubtotal.'">';
734         $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($subtotal['name'] ? htmlspecialchars($subtotal['name']) : '&nbsp;').'</td>';
735         if ($options['show_duration']) {
736           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
737           if ($subtotal['time'] <> '0:00') $body .= $subtotal['time'];
738           $body .= '</td>';
739         }
740         if ($options['show_work_units']) {
741           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
742           $body .= $subtotal['units'];
743           $body .= '</td>';
744         }
745         if ($options['show_cost']) {
746           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
747           $body .= ($canViewReports || $isClient) ? $subtotal['cost'] : $subtotal['expenses'];
748           $body .= '</td>';
749         }
750         $body .= '</tr>';
751       }
752
753       // Print totals.
754       $body .= '<tr><td>&nbsp;</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'];
760         $body .= '</td>';
761       }
762       if ($options['show_work_units']) {
763         $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
764         $body .= $totals['units'];
765         $body .= '</td>';
766       }
767       if ($options['show_cost']) {
768         $body .= '<td nowrap style="'.$cellRightAlignedSubtotal.'">'.htmlspecialchars($user->currency).' ';
769         $body .= ($canViewReports || $isClient) ? $totals['cost'] : $totals['expenses'];
770         $body .= '</td>';
771       }
772       $body .= '</tr>';
773
774       $body .= '</table>';
775     } else {
776       // Regular report.
777
778       // Print table header.
779       $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
780       $body .= '<tr>';
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>';
810       $body .= '</tr>';
811
812       // Initialize variables to print subtotals.
813       if ($items && $grouping) {
814         $print_subtotals = true;
815         $first_pass = true;
816         $prev_grouped_by = '';
817         $cur_grouped_by = '';
818       }
819       // Initialize variables to alternate color of rows for different dates.
820       $prev_date = '';
821       $cur_date = '';
822       $row_style = $rowItem;
823
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'];
848                 $body .= '</td>';
849               }
850               if ($options['show_paid']) $body .= '<td></td>';
851               if ($options['show_ip']) $body .= '<td></td>';
852               if ($options['show_invoice']) $body .= '<td></td>';
853               $body .= '</tr>';
854               $body .= '<tr><td>&nbsp;</td></tr>';
855             }
856             $first_pass = false;
857           }
858
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');
889             $body .= '</td>';
890           }
891           if ($options['show_ip']) {
892             $body .= '<td style="'.$cellRightAligned.'">';
893             $body .= $record['modified'] ? $record['modified_ip'].' '.$record['modified'] : $record['created_ip'].' '.$record['created'];
894             $body .= '</td>';
895           }
896           if ($options['show_invoice'])
897             $body .= '<td style="'.$cellRightAligned.'">'.htmlspecialchars($record['invoice']).'</td>';
898           $body .= '</tr>';
899
900           $prev_date = $record['date'];
901           if ($print_subtotals)
902             $prev_grouped_by = $record['grouped_by'];
903         }
904       }
905
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'];
924           $body .= '</td>';
925         }
926         if ($options['show_paid']) $body .= '<td></td>';
927         if ($options['show_ip']) $body .= '<td></td>';
928         if ($options['show_invoice']) $body .= '<td></td>';
929         $body .= '</tr>';
930       }
931
932       // Print totals.
933       $body .= '<tr><td>&nbsp;</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'];
949         $body .= '</td>';
950       }
951       if ($options['show_paid']) $body .= '<td></td>';
952       if ($options['show_ip']) $body .= '<td></td>';
953       if ($options['show_invoice']) $body .= '<td></td>';
954       $body .= '</tr>';
955
956       $body .= '</table>';
957     }
958
959     // Output footer.
960     if (!defined('REPORT_FOOTER') || !(REPORT_FOOTER == false))
961       $body .= '<p style="text-align: center;">'.$i18n->get('form.mail.footer').'</p>';
962
963     // Finish creating email body.
964     $body .= '</body></html>';
965
966     return $body;
967   }
968
969   // checkFavReportCondition - checks whether it is okay to send fav report.
970   static function checkFavReportCondition($options, $condition)
971   {
972     $items = ttReportHelper::getItems($options);
973
974     $condition = trim(str_replace('count', '', $condition));
975
976     $greater_or_equal = ttStartsWith($condition, '>=');
977     if ($greater_or_equal) $condition = trim(str_replace('>=', '', $condition));
978
979     $less_or_equal = ttStartsWith($condition, '<=');
980     if ($less_or_equal) $condition = trim(str_replace('<=', '', $condition));
981
982     $not_equal = ttStartsWith($condition, '<>');
983     if ($not_equal) $condition = trim(str_replace('<>', '', $condition));
984
985     $greater = ttStartsWith($condition, '>');
986     if ($greater) $condition = trim(str_replace('>', '', $condition));
987
988     $less = ttStartsWith($condition, '<');
989     if ($less) $condition = trim(str_replace('<', '', $condition));
990
991     $equal = ttStartsWith($condition, '=');
992     if ($equal) $condition = trim(str_replace('=', '', $condition));
993
994     $count_required = (int) $condition;
995
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;
1002
1003     return false;
1004   }
1005
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.
1010     global $user;
1011     global $i18n;
1012
1013     // Prepare report body.
1014     $body = ttReportHelper::prepareReportBody($options);
1015
1016     import('mail.Mailer');
1017     $mailer = new Mailer();
1018     $mailer->setCharSet(CHARSET);
1019     $mailer->setContentType('text/html');
1020     $mailer->setSender(SENDER);
1021     if (!empty($cc))
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))
1029       return false;
1030
1031     return true;
1032   }
1033
1034   // getReportOptions - returns an array of report options constructed from session bean.
1035   //
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) {
1041     global $user;
1042
1043     // Prepare an array of report options.
1044     $options = array();
1045
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 (is_array($bean->getAttribute('users'))) $options['users'] = join(',', $bean->getAttribute('users'));
1058     $options['period'] = $bean->getAttribute('period');
1059     $options['period_start'] = $bean->getAttribute('start_date');
1060     $options['period_end'] = $bean->getAttribute('end_date');
1061     $options['show_client'] = $bean->getAttribute('chclient');
1062     $options['show_invoice'] = $bean->getAttribute('chinvoice');
1063     $options['show_paid'] = $bean->getAttribute('chpaid');
1064     $options['show_ip'] = $bean->getAttribute('chip');
1065     $options['show_project'] = $bean->getAttribute('chproject');
1066     $options['show_start'] = $bean->getAttribute('chstart');
1067     $options['show_duration'] = $bean->getAttribute('chduration');
1068     $options['show_cost'] = $bean->getAttribute('chcost');
1069     $options['show_task'] = $bean->getAttribute('chtask');
1070     $options['show_end'] = $bean->getAttribute('chfinish');
1071     $options['show_note'] = $bean->getAttribute('chnote');
1072     $options['show_custom_field_1'] = $bean->getAttribute('chcf_1');
1073     $options['show_work_units'] = $bean->getAttribute('chunits');
1074     $options['show_timesheet'] = $bean->getAttribute('chtimesheet');
1075     $options['show_totals_only'] = $bean->getAttribute('chtotalsonly');
1076     $options['group_by1'] = $bean->getAttribute('group_by1');
1077     $options['group_by2'] = $bean->getAttribute('group_by2');
1078     $options['group_by3'] = $bean->getAttribute('group_by3');
1079     return $options;
1080   }
1081
1082   // verifyBean is a security function to make sure data in bean makes sense for a group.
1083   static function verifyBean($bean) {
1084     global $user;
1085
1086     // Check users.
1087     $users_in_bean = $bean->getAttribute('users');
1088     if (is_array($users_in_bean)) {
1089       $users_in_group = ttGroupHelper::getUsers();
1090       foreach ($users_in_group as $user_in_group) {
1091         $valid_ids[] = $user_in_group['id'];
1092       }
1093       foreach ($users_in_bean as $user_in_bean) {
1094         if (!in_array($user_in_bean, $valid_ids)) {
1095           return false;
1096         }
1097       }
1098     }
1099
1100     // TODO: add additional checks here. Perhaps do it before saving the bean for consistency.
1101     return true;
1102   }
1103
1104   // makeGroupByKey builds a combined group by key from group_by1, group_by2 and group_by3 values
1105   // (passed in $options) and a row of data ($row obtained from a db query).
1106   static function makeGroupByKey($options, $row) {
1107     if ($options['group_by1'] != null && $options['group_by1'] != 'no_grouping') {
1108       // We have group_by1.
1109       $group_by1 = $options['group_by1'];
1110       $group_by1_value = $row[$group_by1];
1111       //if ($group_by1 == 'date') $group_by1_value = ttDateToUserFormat($group_by1_value);
1112       if (empty($group_by1_value)) $group_by1_value = 'Null'; // To match what comes out of makeConcatPart.
1113       $group_by_key .= ' - '.$group_by1_value;
1114     }
1115     if ($options['group_by2'] != null && $options['group_by2'] != 'no_grouping') {
1116       // We have group_by2.
1117       $group_by2 = $options['group_by2'];
1118       $group_by2_value = $row[$group_by2];
1119       //if ($group_by2 == 'date') $group_by2_value = ttDateToUserFormat($group_by2_value);
1120       if (empty($group_by2_value)) $group_by2_value = 'Null'; // To match what comes out of makeConcatPart.
1121       $group_by_key .= ' - '.$group_by2_value;
1122     }
1123     if ($options['group_by3'] != null && $options['group_by3'] != 'no_grouping') {
1124       // We have group_by3.
1125       $group_by3 = $options['group_by3'];
1126       $group_by3_value = $row[$group_by3];
1127       //if ($group_by3 == 'date') $group_by3_value = ttDateToUserFormat($group_by3_value);
1128       if (empty($group_by3_value)) $group_by3_value = 'Null'; // To match what comes out of makeConcatPart.
1129       $group_by_key .= ' - '.$group_by3_value;
1130     }
1131     $group_by_key = trim($group_by_key, ' -');
1132     return $group_by_key;
1133   }
1134
1135   // makeGroupByPart builds a combined group by part for sql query for time items using group_by1,
1136   // group_by2, and group_by3 values passed in $options.
1137   static function makeGroupByPart($options) {
1138     if (!ttReportHelper::grouping($options)) return null;
1139
1140     $group_by1 = $options['group_by1'];
1141     $group_by2 = $options['group_by2'];
1142     $group_by3 = $options['group_by3'];
1143
1144     switch ($group_by1) {
1145       case 'date':
1146         $group_by_parts .= ', l.date';
1147         break;
1148       case 'user':
1149         $group_by_parts .= ', u.name';
1150         break;
1151       case 'client':
1152         $group_by_parts .= ', c.name';
1153         break;
1154       case 'project':
1155         $group_by_parts .= ', p.name';
1156         break;
1157       case 'task':
1158         $group_by_parts .= ', t.name';
1159         break;
1160       case 'cf_1':
1161         $group_by_parts .= ', cfo.value';
1162         break;
1163     }
1164     switch ($group_by2) {
1165       case 'date':
1166         $group_by_parts .= ', l.date';
1167         break;
1168       case 'user':
1169         $group_by_parts .= ', u.name';
1170         break;
1171       case 'client':
1172         $group_by_parts .= ', c.name';
1173         break;
1174       case 'project':
1175         $group_by_parts .= ', p.name';
1176         break;
1177       case 'task':
1178         $group_by_parts .= ', t.name';
1179         break;
1180       case 'cf_1':
1181         $group_by_parts .= ', cfo.value';
1182         break;
1183     }
1184     switch ($group_by3) {
1185       case 'date':
1186         $group_by_parts .= ', l.date';
1187         break;
1188       case 'user':
1189         $group_by_parts .= ', u.name';
1190         break;
1191       case 'client':
1192         $group_by_parts .= ', c.name';
1193         break;
1194       case 'project':
1195         $group_by_parts .= ', p.name';
1196         break;
1197       case 'task':
1198         $group_by_parts .= ', t.name';
1199         break;
1200       case 'cf_1':
1201         $group_by_parts .= ', cfo.value';
1202         break;
1203     }
1204     // Remove garbage from the beginning.
1205     $group_by_parts = ltrim($group_by_parts, ', ');
1206     $group_by_part = "group by $group_by_parts";
1207     return $group_by_part;
1208   }
1209
1210   // makeGroupByExpensesPart builds a combined group by part for sql query for expense items using
1211   // group_by1, group_by2, and group_by3 values passed in $options.
1212   static function makeGroupByExpensesPart($options) {
1213     $no_grouping = ($options['group_by1'] == null || $options['group_by1'] == 'no_grouping') &&
1214       ($options['group_by2'] == null || $options['group_by2'] == 'no_grouping') &&
1215       ($options['group_by3'] == null || $options['group_by3'] == 'no_grouping');
1216     if ($no_grouping) return null;
1217
1218     $group_by1 = $options['group_by1'];
1219     $group_by2 = $options['group_by2'];
1220     $group_by3 = $options['group_by3'];
1221
1222     switch ($group_by1) {
1223       case 'date':
1224         $group_by_parts .= ', ei.date';
1225         break;
1226       case 'user':
1227         $group_by_parts .= ', u.name';
1228         break;
1229       case 'client':
1230         $group_by_parts .= ', c.name';
1231         break;
1232       case 'project':
1233         $group_by_parts .= ', p.name';
1234         break;
1235     }
1236     switch ($group_by2) {
1237       case 'date':
1238         $group_by_parts .= ', ei.date';
1239         break;
1240       case 'user':
1241         $group_by_parts .= ', u.name';
1242         break;
1243       case 'client':
1244         $group_by_parts .= ', c.name';
1245         break;
1246       case 'project':
1247         $group_by_parts .= ', p.name';
1248         break;
1249     }
1250     switch ($group_by3) {
1251       case 'date':
1252         $group_by_parts .= ', ei.date';
1253         break;
1254       case 'user':
1255         $group_by_parts .= ', u.name';
1256         break;
1257       case 'client':
1258         $group_by_parts .= ', c.name';
1259         break;
1260       case 'project':
1261         $group_by_parts .= ', p.name';
1262         break;
1263     }
1264     // Remove garbage from the beginning.
1265     $group_by_parts = ltrim($group_by_parts, ', ');
1266     if ($group_by_parts)
1267       $group_by_part = "group by $group_by_parts";
1268     return $group_by_part;
1269   }
1270
1271   // makeConcatPart builds a concatenation part for getSubtotals query (for time items).
1272   static function makeConcatPart($options) {
1273     $group_by1 = $options['group_by1'];
1274     $group_by2 = $options['group_by2'];
1275     $group_by3 = $options['group_by3'];
1276
1277     switch ($group_by1) {
1278       case 'date':
1279         $what_to_concat .= ", ' - ', l.date";
1280         break;
1281       case 'user':
1282         $what_to_concat .= ", ' - ', u.name";
1283         $fields_part .= ', u.name as user';
1284         break;
1285       case 'client':
1286         $what_to_concat .= ", ' - ', coalesce(c.name, 'Null')";
1287         $fields_part .= ', c.name as client';
1288         break;
1289       case 'project':
1290         $what_to_concat .= ", ' - ', coalesce(p.name, 'Null')";
1291         $fields_part .= ', p.name as project';
1292         break;
1293       case 'task':
1294         $what_to_concat .= ", ' - ', coalesce(t.name, 'Null')";
1295         $fields_part .= ', t.name as task';
1296         break;
1297       case 'cf_1':
1298         $what_to_concat .= ", ' - ', coalesce(cfo.value, 'Null')";
1299         $fields_part .= ', cfo.value as cf_1';
1300         break;
1301     }
1302     switch ($group_by2) {
1303       case 'date':
1304         $what_to_concat .= ", ' - ', l.date";
1305         break;
1306       case 'user':
1307         $what_to_concat .= ", ' - ', u.name";
1308         $fields_part .= ', u.name as user';
1309         break;
1310       case 'client':
1311         $what_to_concat .= ", ' - ', coalesce(c.name, 'Null')";
1312         $fields_part .= ', c.name as client';
1313         break;
1314       case 'project':
1315         $what_to_concat .= ", ' - ', coalesce(p.name, 'Null')";
1316         $fields_part .= ', p.name as project';
1317         break;
1318       case 'task':
1319         $what_to_concat .= ", ' - ', coalesce(t.name, 'Null')";
1320         $fields_part .= ', t.name as task';
1321         break;
1322       case 'cf_1':
1323         $what_to_concat .= ", ' - ', coalesce(cfo.value, 'Null')";
1324         $fields_part .= ', cfo.value as cf_1';
1325         break;
1326     }
1327     switch ($group_by3) {
1328       case 'date':
1329         $what_to_concat .= ", ' - ', l.date";
1330         break;
1331       case 'user':
1332         $what_to_concat .= ", ' - ', u.name";
1333         $fields_part .= ', u.name as user';
1334         break;
1335       case 'client':
1336         $what_to_concat .= ", ' - ', coalesce(c.name, 'Null')";
1337         $fields_part .= ', c.name as client';
1338         break;
1339       case 'project':
1340         $what_to_concat .= ", ' - ', coalesce(p.name, 'Null')";
1341         $fields_part .= ', p.name as project';
1342         break;
1343       case 'task':
1344         $what_to_concat .= ", ' - ', coalesce(t.name, 'Null')";
1345         $fields_part .= ', t.name as task';
1346         break;
1347       case 'cf_1':
1348         $what_to_concat .= ", ' - ', coalesce(cfo.value, 'Null')";
1349         $fields_part .= ', cfo.value as cf_1';
1350         break;
1351     }
1352     // Remove garbage from both ends.
1353     $what_to_concat = trim($what_to_concat, "', -");
1354     $concat_part = "concat($what_to_concat) as group_field";
1355     $concat_part = trim($concat_part, ' -');
1356     return "$concat_part $fields_part";
1357   }
1358
1359   // makeConcatPart builds a concatenation part for getSubtotals query (for expense items).
1360   static function makeConcatExpensesPart($options) {
1361     $group_by1 = $options['group_by1'];
1362     $group_by2 = $options['group_by2'];
1363     $group_by3 = $options['group_by3'];
1364
1365     switch ($group_by1) {
1366       case 'date':
1367         $what_to_concat .= ", ' - ', ei.date";
1368         break;
1369       case 'user':
1370         $what_to_concat .= ", ' - ', u.name";
1371         $fields_part .= ', u.name as user';
1372         break;
1373       case 'client':
1374         $what_to_concat .= ", ' - ', coalesce(c.name, 'Null')";
1375         $fields_part .= ', c.name as client';
1376         break;
1377       case 'project':
1378         $what_to_concat .= ", ' - ', coalesce(p.name, 'Null')";
1379         $fields_part .= ', p.name as project';
1380         break;
1381
1382       case 'task':
1383         $what_to_concat .= ", ' - ', 'Null'";
1384         $fields_part .= ', null as task';
1385         break;
1386
1387       case 'cf_1':
1388         $what_to_concat .= ", ' - ', 'Null'";
1389         $fields_part .= ', null as cf_1';
1390         break;
1391     }
1392     switch ($group_by2) {
1393       case 'date':
1394         $what_to_concat .= ", ' - ', ei.date";
1395         break;
1396       case 'user':
1397         $what_to_concat .= ", ' - ', u.name";
1398         $fields_part .= ', u.name as user';
1399         break;
1400       case 'client':
1401         $what_to_concat .= ", ' - ', coalesce(c.name, 'Null')";
1402         $fields_part .= ', c.name as client';
1403         break;
1404       case 'project':
1405         $what_to_concat .= ", ' - ', coalesce(p.name, 'Null')";
1406         $fields_part .= ', p.name as project';
1407         break;
1408
1409       case 'task':
1410         $what_to_concat .= ", ' - ', 'Null'";
1411         $fields_part .= ', null as task';
1412         break;
1413
1414       case 'cf_1':
1415         $what_to_concat .= ", ' - ', 'Null'";
1416         $fields_part .= ', null as cf_1';
1417         break;
1418     }
1419     switch ($group_by3) {
1420       case 'date':
1421         $what_to_concat .= ", ' - ', ei.date";
1422         break;
1423       case 'user':
1424         $what_to_concat .= ", ' - ', u.name";
1425         $fields_part .= ', u.name as user';
1426         break;
1427       case 'client':
1428         $what_to_concat .= ", ' - ', coalesce(c.name, 'Null')";
1429         $fields_part .= ', c.name as client';
1430         break;
1431       case 'project':
1432         $what_to_concat .= ", ' - ', coalesce(p.name, 'Null')";
1433         $fields_part .= ', p.name as project';
1434         break;
1435
1436       case 'task':
1437         $what_to_concat .= ", ' - ', 'Null'";
1438         $fields_part .= ', null as task';
1439         break;
1440
1441       case 'cf_1':
1442         $what_to_concat .= ", ' - ', 'Null'";
1443         $fields_part .= ', null as cf_1';
1444         break;
1445     }
1446     // Remove garbage from the beginning.
1447     if ($what_to_concat)
1448         $what_to_concat = substr($what_to_concat, 8);
1449     $concat_part = "concat($what_to_concat) as group_field";
1450     return "$concat_part $fields_part";
1451   }
1452
1453   // makeCombinedSelectPart builds a list of fields for a combined select on a union for getSubtotals.
1454   // This is used when we include expenses.
1455   static function makeCombinedSelectPart($options) {
1456     $group_by1 = $options['group_by1'];
1457     $group_by2 = $options['group_by2'];
1458     $group_by3 = $options['group_by3'];
1459
1460     $fields = "group_field";
1461
1462     switch ($group_by1) {
1463       case 'user':
1464         $fields .= ', user';
1465         break;
1466       case 'client':
1467         $fields_part .= ', client';
1468         break;
1469       case 'project':
1470         $fields .= ', project';
1471         break;
1472
1473       case 'task':
1474         $fields .= ', task';
1475         break;
1476
1477       case 'cf_1':
1478         $fields .= ', cf_1';
1479         break;
1480     }
1481     switch ($group_by2) {
1482       case 'user':
1483         $fields .= ', user';
1484         break;
1485       case 'client':
1486         $fields_part .= ', client';
1487         break;
1488       case 'project':
1489         $fields .= ', project';
1490         break;
1491
1492       case 'task':
1493         $fields .= ', task';
1494         break;
1495
1496       case 'cf_1':
1497         $fields .= ', cf_1';
1498         break;
1499     }
1500     switch ($group_by3) {
1501       case 'user':
1502         $fields .= ', user';
1503         break;
1504       case 'client':
1505         $fields_part .= ', client';
1506         break;
1507       case 'project':
1508         $fields .= ', project';
1509         break;
1510
1511       case 'task':
1512         $fields .= ', task';
1513         break;
1514
1515       case 'cf_1':
1516         $fields .= ', cf_1';
1517         break;
1518     }
1519     return $fields;
1520   }
1521
1522   // makeJoinPart builds a left join part for getSubtotals query (for time items).
1523   static function makeJoinPart($options) {
1524     global $user;
1525
1526     $trackingMode = $user->getTrackingMode();
1527     if (ttReportHelper::groupingBy('user', $options) || MODE_TIME == $trackingMode) {
1528       $join .= ' left join tt_users u on (l.user_id = u.id)';
1529     }
1530     if (ttReportHelper::groupingBy('client', $options)) {
1531       $join .= ' left join tt_clients c on (l.client_id = c.id)';
1532     }
1533     if (ttReportHelper::groupingBy('project', $options)) {
1534       $join .= ' left join tt_projects p on (l.project_id = p.id)';
1535     }
1536     if (ttReportHelper::groupingBy('task', $options)) {
1537       $join .= ' left join tt_tasks t on (l.task_id = t.id)';
1538     }
1539     if (ttReportHelper::groupingBy('cf_1', $options)) {
1540       $custom_fields = new CustomFields();
1541       if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_TEXT)
1542         $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)';
1543       elseif ($custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN)
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.option_id = cfo.id)';
1545     }
1546     if ($options['show_cost'] && $trackingMode != MODE_TIME) {
1547       $join .= ' left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id)';
1548     }
1549     return $join;
1550   }
1551
1552   // makeWorkUnitPart builds an sql part for work units for time items.
1553   static function makeWorkUnitPart($options) {
1554     global $user;
1555
1556     $workUnits = $options['show_work_units'];
1557     if ($workUnits) {
1558       $unitTotalsOnly = $user->getConfigOption('unit_totals_only');
1559       $firstUnitThreshold = $user->getConfigInt('1st_unit_threshold', 0);
1560       $minutesInUnit = $user->getConfigInt('minutes_in_unit', 15);
1561       if ($unitTotalsOnly)
1562         $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";
1563       else
1564         $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";
1565     }
1566     return $work_unit_part;
1567   }
1568
1569   // makeCostPart builds a cost part for time items.
1570   static function makeCostPart($options) {
1571     global $user;
1572
1573     if ($options['show_cost']) {
1574       if (MODE_TIME == $user->getTrackingMode())
1575         $cost_part = ", sum(cast(l.billable * coalesce(u.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10, 2))) as cost";
1576       else
1577         $cost_part .= ", sum(cast(l.billable * coalesce(upb.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10,2))) as cost";
1578     }
1579     return $cost_part;
1580   }
1581
1582   // makeJoinExpensesPart builds a left join part for getSubtotals query for expense items.
1583   static function makeJoinExpensesPart($options) {
1584     if (ttReportHelper::groupingBy('user', $options)) {
1585       $join .= ' left join tt_users u on (ei.user_id = u.id)';
1586     }
1587     if (ttReportHelper::groupingBy('client', $options)) {
1588       $join .= ' left join tt_clients c on (ei.client_id = c.id)';
1589     }
1590     if (ttReportHelper::groupingBy('project', $options)) {
1591       $join .= ' left join tt_projects p on (ei.project_id = p.id)';
1592     }
1593     return $join;
1594   }
1595
1596   // grouping determines if we are grouping the report by either group_by1,
1597   // group_by2, or group_by3 values passed in $options.
1598   static function grouping($options) {
1599     $grouping = ($options['group_by1'] != null && $options['group_by1'] != 'no_grouping') ||
1600       ($options['group_by2'] != null && $options['group_by2'] != 'no_grouping') ||
1601       ($options['group_by3'] != null && $options['group_by3'] != 'no_grouping');
1602     return $grouping;
1603   }
1604
1605   // groupingBy determines if we are grouping a report by a value of $what
1606   // ('date', 'user', 'project', etc.) by checking group_by1, group_by2,
1607   // and group_by3 values passed in $options.
1608   static function groupingBy($what, $options) {
1609     $grouping = ($options['group_by1'] == $what) || ($options['group_by2'] == $what) || ($options['group_by3'] == $what);
1610     return $grouping;
1611   }
1612
1613   // makeGroupByHeader builds a column header for a totals-only report using group_by1,
1614   // group_by2, and group_by3 values passed in $options.
1615   static function makeGroupByHeader($options) {
1616     global $i18n;
1617     global $custom_fields;
1618
1619     $no_grouping = ($options['group_by1'] == null || $options['group_by1'] == 'no_grouping') &&
1620       ($options['group_by2'] == null || $options['group_by2'] == 'no_grouping') &&
1621       ($options['group_by3'] == null || $options['group_by3'] == 'no_grouping');
1622     if ($no_grouping) return null;
1623
1624     if ($options['group_by1'] != null && $options['group_by1'] != 'no_grouping') {
1625       // We have group_by1.
1626       $group_by1 = $options['group_by1'];
1627       if ('cf_1' == $group_by1)
1628         $group_by_header .= ' - '.$custom_fields->fields[0]['label'];
1629       else {
1630         $key = 'label.'.$group_by1;
1631         $group_by_header .= ' - '.$i18n->get($key);
1632       }
1633     }
1634     if ($options['group_by2'] != null && $options['group_by2'] != 'no_grouping') {
1635       // We have group_by2.
1636       $group_by2 = $options['group_by2'];
1637       if ('cf_1' == $group_by2)
1638         $group_by_header .= ' - '.$custom_fields->fields[0]['label'];
1639       else {
1640         $key = 'label.'.$group_by2;
1641         $group_by_header .= ' - '.$i18n->get($key);
1642       }
1643     }
1644     if ($options['group_by3'] != null && $options['group_by3'] != 'no_grouping') {
1645       // We have group_by3.
1646       $group_by3 = $options['group_by3'];
1647       if ('cf_1' == $group_by3)
1648         $group_by_header .= ' - '.$custom_fields->fields[0]['label'];
1649       else {
1650         $key = 'label.'.$group_by3;
1651         $group_by_header .= ' - '.$i18n->get($key);
1652       }
1653     }
1654     $group_by_header = ltrim($group_by_header, ' -');
1655     return $group_by_header;
1656   }
1657
1658   // makeGroupByXmlTag creates an xml tag for a totals only report using group_by1,
1659   // group_by2, and group_by3 values passed in $options.
1660   static function makeGroupByXmlTag($options) {
1661     if ($options['group_by1'] != null && $options['group_by1'] != 'no_grouping') {
1662       // We have group_by1.
1663       $tag .= '_'.$options['group_by1'];
1664     }
1665     if ($options['group_by2'] != null && $options['group_by2'] != 'no_grouping') {
1666       // We have group_by2.
1667       $tag .= '_'.$options['group_by2'];
1668     }
1669     if ($options['group_by3'] != null && $options['group_by3'] != 'no_grouping') {
1670       // We have group_by3.
1671       $tag .= '_'.$options['group_by3'];
1672     }
1673     $tag = ltrim($tag, '_');
1674     return $tag;
1675   }
1676
1677   // makeGroupByLabel builds a label for one row in a "Totals only" report of grouped by items.
1678   // It does one thing: if we are grouping by date, the date format is converted for user.
1679   static function makeGroupByLabel($key, $options) {
1680     if (!ttReportHelper::groupingBy('date', $options))
1681       return $key; // No need to format.
1682
1683     global $user;
1684     if ($user->getDateFormat() == DB_DATEFORMAT)
1685       return $key; // No need to format.
1686
1687     $label = $key;
1688     if (preg_match('/\d\d\d\d-\d\d-\d\d/', $key, $matches)) {
1689       // Replace the first found match of a date in DB_DATEFORMAT.
1690       // This is not entirely clean but better than nothing for a label in a row.
1691       $userDate = ttDateToUserFormat($matches[0]);
1692       $label = str_replace($matches[0], $userDate, $key);
1693     }
1694     return $label;
1695   }
1696 }