Improved safety of timesheet assignment by adding an inner join.
[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['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';
79
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)";
84     else
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";
87
88     // Prepare sql query part for where.
89     $dateFormat = $user->getDateFormat();
90     if ($options['period'])
91       $period = new Period($options['period'], new DateAndTime($dateFormat));
92     else {
93       $period = new Period();
94       $period->setPeriod(
95         new DateAndTime($dateFormat, $options['period_start']),
96         new DateAndTime($dateFormat, $options['period_end']));
97     }
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";
100     return $where;
101   }
102
103   // getExpenseWhere prepares WHERE clause for expenses query in a report.
104   static function getExpenseWhere($options) {
105     global $user;
106
107     $group_id = $user->getGroup();
108     $org_id = $user->org_id;
109
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.
121     }
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';
126
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)";
131     else
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";
134
135     // Prepare sql query part for where.
136     $dateFormat = $user->getDateFormat();
137     if ($options['period'])
138       $period = new Period($options['period'], new DateAndTime($dateFormat));
139     else {
140       $period = new Period();
141       $period->setPeriod(
142         new DateAndTime($dateFormat, $options['period_start']),
143         new DateAndTime($dateFormat, $options['period_end']));
144     }
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";
147     return $where;
148   }
149
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) {
154     global $user;
155     $mdb2 = getConnection();
156
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();
160
161     $grouping = ttReportHelper::grouping($options);
162     if ($grouping) {
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);
169     }
170     $convertTo12Hour = ('%I:%M %p' == $user->getTimeFormat()) && ($options['show_start'] || $options['show_end']);
171     $trackingMode = $user->getTrackingMode();
172     $decimalMark = $user->getDecimalMark();
173
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');
191     // Add custom field.
192     $include_cf_1 = $options['show_custom_field_1'] || $grouping_by_cf_1;
193     if ($include_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');
200       }
201     }
202     // Add start time.
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");
206     }
207     // Add finish time.
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");
210     // Add duration.
211     if ($options['show_duration'])
212       array_push($fields, "TIME_FORMAT(l.duration, '%k:%i') as duration");
213     // Add work units.
214     if ($options['show_work_units']) {
215       if ($user->getConfigOption('unit_totals_only'))
216         array_push($fields, "null as units");
217       else {
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");
221       }
222     }
223     // Add note.
224     if ($options['show_note'])
225       array_push($fields, 'l.comment as note');
226     // Handle cost.
227     $includeCost = $options['show_cost'];
228     if ($includeCost) {
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.
231       else
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"); 
234     }
235     // Add approved.
236     if ($options['show_approved'])
237       array_push($fields, 'l.approved');
238     // Add paid status.
239     if ($canViewReports && $options['show_paid'])
240       array_push($fields, 'l.paid');
241     // Add IP address.
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');
247     }
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');
254
255     // Prepare sql query part for left joins.
256     $left_joins = null;
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)";
267     if ($include_cf_1) {
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)";
273       }
274     }
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)";
277
278     // Prepare sql query part for inner joins.
279     $inner_joins = null;
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.
290     }
291
292     $where = ttReportHelper::getWhere($options);
293
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.
298
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
301
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.
322       }
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');
334       // Add approved.
335       if ($options['show_approved'])
336         array_push($fields, 'ei.approved');
337       // Add paid status.
338       if ($canViewReports && $options['show_paid'])
339         array_push($fields, 'ei.paid');
340       // Add IP address.
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');
346       }
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');
352
353       // Prepare sql query part for left joins.
354       $left_joins = null;
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)";
363
364       $where = ttReportHelper::getExpenseWhere($options);
365
366       // Construct sql query for expense items.
367       $sql_for_expense_items = "select ".join(', ', $fields)." from tt_expense_items ei $left_joins $where";
368
369       // Construct a union.
370       $sql = "($sql) union all ($sql_for_expense_items)";
371     }
372
373     // Determine sort part.
374     $sort_part = ' order by ';
375     if ($grouping) {
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.
381     } else {
382       $sort_part .= 'date';
383     }
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';
389
390     $sql .= $sort_part;
391     // By now we are ready with sql.
392
393     // Obtain items for report.
394     $res = $mdb2->query($sql);
395     if (is_a($res, 'PEAR_Error')) die($res->getMessage());
396
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']);
403       }
404       if (isset($val['cost'])) {
405         if ('.' != $decimalMark)
406           $val['cost'] = str_replace('.', $decimalMark, $val['cost']);
407       }
408       if (isset($val['expense'])) {
409         if ('.' != $decimalMark)
410           $val['expense'] = str_replace('.', $decimalMark, $val['expense']);
411       }
412
413       if ($grouping) $val['grouped_by'] = ttReportHelper::makeGroupByKey($options, $val);
414       $val['date'] = ttDateToUserFormat($val['date']);
415
416       $report_items[] = $val;
417     }
418
419     return $report_items;
420   }
421
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']);
427
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'];
434     }
435     $report_item_ids = trim($report_item_ids, ',');
436     $report_item_expense_ids = trim($report_item_expense_ids, ',');
437
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;
441   }
442
443   // getFromSession obtains tt_log and tt_expense_items ids stored in user session.
444   static function getFromSession() {
445     $items = array();
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);
452     return $items;
453   }
454
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) {
459     global $user;
460     $mdb2 = getConnection();
461
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);
468
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.
472
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
475
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";
483
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";
489       $sql = $combined;
490     }
491
492     // Execute query.
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']);
503         }
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']);
505       } else
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']);
507     }
508
509     return $subtotals;
510   }
511
512   // getTotals calculates total hours and cost for all report items.
513   static function getTotals($options)
514   {
515     global $user;
516     $mdb2 = getConnection();
517
518     $trackingMode = $user->getTrackingMode();
519     $decimalMark = $user->getDecimalMark();
520     $where = ttReportHelper::getWhere($options);
521
522     // Prepare parts.
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";
529     }
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";
533       else
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";
535     } else {
536       $cost_part = ", null as cost, null as expenses";
537     }
538     if ($options['show_cost']) {
539       if (MODE_TIME == $trackingMode) {
540         $left_joins = "left join tt_users u on (l.user_id = u.id)";
541       } else {
542         $left_joins = "left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id)";
543       }
544     }
545     // Prepare sql query part for inner joins.
546     $inner_joins = null;
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)";
555     }
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";
558
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";
565
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";
570       $sql = $combined;
571     }
572
573     // Execute query.
574     $res = $mdb2->query($sql);
575     if (is_a($res, 'PEAR_Error')) die($res->getMessage());
576
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);
588     }
589
590     $dateFormat = $user->getDateFormat();
591     if ($options['period'])
592       $period = new Period($options['period'], new DateAndTime($dateFormat));
593     else {
594       $period = new Period();
595       $period->setPeriod(
596         new DateAndTime($dateFormat, $options['period_start']),
597         new DateAndTime($dateFormat, $options['period_end']));
598     }
599
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;
606
607     return $totals;
608   }
609
610   // The assignToInvoice assigns a set of records to a specific invoice.
611   static function assignToInvoice($invoice_id, $time_log_ids, $expense_item_ids) {
612     global $user;
613     $mdb2 = getConnection();
614
615     $group_id = $user->getGroup();
616     $org_id = $user->org_id;
617
618     if ($time_log_ids) {
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());
623     }
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());
629     }
630   }
631
632   // The assignToTimesheet assigns a set of tt_log records to a specific timesheet.
633   static function assignToTimesheet($timesheet_id, $time_log_ids) {
634     global $user;
635     $mdb2 = getConnection();
636
637     $user_id = $user->getUser();
638     $group_id = $user->getGroup();
639     $org_id = $user->org_id;
640
641     if ($time_log_ids) {
642       if ($timesheet_id)
643         $inner_join = " inner join tt_timesheets ts on (ts.id = $timesheet_id and ts.approve_status is null)";
644
645       $sql = "update tt_log l $inner_join".
646         " set l.timesheet_id = ".$mdb2->quote($timesheet_id).
647         " where l.id in(".join(', ', $time_log_ids).") and l.user_id = $user_id and l.group_id = $group_id and l.org_id = $org_id";
648       $affected = $mdb2->exec($sql);
649       if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
650     }
651   }
652
653   // The markApproved marks a set of records as either approved or unapproved.
654   static function markApproved($time_log_ids, $expense_item_ids, $approved = true) {
655     global $user;
656     $mdb2 = getConnection();
657
658     $group_id = $user->getGroup();
659     $org_id = $user->org_id;
660
661     $approved_val = (int) $approved;
662     if ($time_log_ids) {
663       $sql = "update tt_log set approved = $approved_val".
664         " where id in(".join(', ', $time_log_ids).") and group_id = $group_id and org_id = $org_id";
665       $affected = $mdb2->exec($sql);
666       if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
667     }
668     if ($expense_item_ids) {
669       $sql = "update tt_expense_items set approved = $approved_val".
670         " where id in(".join(', ', $expense_item_ids).") and group_id = $group_id and org_id = $org_id";
671       $affected = $mdb2->exec($sql);
672       if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
673     }
674   }
675
676   // The markPaid marks a set of records as either paid or unpaid.
677   static function markPaid($time_log_ids, $expense_item_ids, $paid = true) {
678     global $user;
679     $mdb2 = getConnection();
680
681     $group_id = $user->getGroup();
682     $org_id = $user->org_id;
683
684     $paid_val = (int) $paid;
685     if ($time_log_ids) {
686       $sql = "update tt_log set paid = $paid_val".
687         " where id in(".join(', ', $time_log_ids).") and group_id = $group_id and org_id = $org_id";
688       $affected = $mdb2->exec($sql);
689       if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
690     }
691     if ($expense_item_ids) {
692       $sql = "update tt_expense_items set paid = $paid_val".
693         " where id in(".join(', ', $expense_item_ids).") and group_id = $group_id and org_id = $org_id";
694       $affected = $mdb2->exec($sql);
695       if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
696     }
697   }
698
699   // prepareReportBody - prepares an email body for report.
700   static function prepareReportBody($options, $comment = null)
701   {
702     global $user;
703     global $i18n;
704
705     // Determine these once as they are used in multiple places in this function.
706     $canViewReports = $user->can('view_reports') || $user->can('view_all_reports');
707     $isClient = $user->isClient();
708
709     $items = ttReportHelper::getItems($options);
710     $grouping = ttReportHelper::grouping($options);
711     if ($grouping)
712       $subtotals = ttReportHelper::getSubtotals($options);
713     $totals = ttReportHelper::getTotals($options);
714
715     // Use custom fields plugin if it is enabled.
716     if ($user->isPluginEnabled('cf'))
717       $custom_fields = new CustomFields();
718
719     // Define some styles to use in email.
720     $style_title = 'text-align: center; font-size: 15pt; font-family: Arial, Helvetica, sans-serif;';
721     $tableHeader = 'font-weight: bold; background-color: #a6ccf7; text-align: left;';
722     $tableHeaderCentered = 'font-weight: bold; background-color: #a6ccf7; text-align: center;';
723     $rowItem = 'background-color: #ffffff;';
724     $rowItemAlt = 'background-color: #f5f5f5;';
725     $rowSubtotal = 'background-color: #e0e0e0;';
726     $cellLeftAligned = 'text-align: left; vertical-align: top;';
727     $cellRightAligned = 'text-align: right; vertical-align: top;';
728     $cellLeftAlignedSubtotal = 'font-weight: bold; text-align: left; vertical-align: top;';
729     $cellRightAlignedSubtotal = 'font-weight: bold; text-align: right; vertical-align: top;';
730
731     // Start creating email body.
732     $body = '<html>';
733     $body .= '<head><meta http-equiv="content-type" content="text/html; charset='.CHARSET.'"></head>';
734     $body .= '<body>';
735
736     // Output title.
737     $body .= '<p style="'.$style_title.'">'.$i18n->get('form.mail.report_subject').': '.$totals['start_date'].' - '.$totals['end_date'].'</p>';
738
739     // Output comment.
740     if ($comment) $body .= '<p>'.htmlspecialchars($comment).'</p>';
741
742     if ($options['show_totals_only']) {
743       // Totals only report. Output subtotals.
744       $group_by_header = ttReportHelper::makeGroupByHeader($options);
745
746       $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
747       $body .= '<tr>';
748       $body .= '<td style="'.$tableHeader.'">'.$group_by_header.'</td>';
749       if ($options['show_duration'])
750         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.duration').'</td>';
751       if ($options['show_work_units'])
752         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.work_units_short').'</td>';
753       if ($options['show_cost'])
754         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.cost').'</td>';
755       $body .= '</tr>';
756       foreach($subtotals as $subtotal) {
757         $body .= '<tr style="'.$rowSubtotal.'">';
758         $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($subtotal['name'] ? htmlspecialchars($subtotal['name']) : '&nbsp;').'</td>';
759         if ($options['show_duration']) {
760           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
761           if ($subtotal['time'] <> '0:00') $body .= $subtotal['time'];
762           $body .= '</td>';
763         }
764         if ($options['show_work_units']) {
765           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
766           $body .= $subtotal['units'];
767           $body .= '</td>';
768         }
769         if ($options['show_cost']) {
770           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
771           $body .= ($canViewReports || $isClient) ? $subtotal['cost'] : $subtotal['expenses'];
772           $body .= '</td>';
773         }
774         $body .= '</tr>';
775       }
776
777       // Print totals.
778       $body .= '<tr><td>&nbsp;</td></tr>';
779       $body .= '<tr style="'.$rowSubtotal.'">';
780       $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.total').'</td>';
781       if ($options['show_duration']) {
782         $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
783         if ($totals['time'] <> '0:00') $body .= $totals['time'];
784         $body .= '</td>';
785       }
786       if ($options['show_work_units']) {
787         $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
788         $body .= $totals['units'];
789         $body .= '</td>';
790       }
791       if ($options['show_cost']) {
792         $body .= '<td nowrap style="'.$cellRightAlignedSubtotal.'">'.htmlspecialchars($user->currency).' ';
793         $body .= ($canViewReports || $isClient) ? $totals['cost'] : $totals['expenses'];
794         $body .= '</td>';
795       }
796       $body .= '</tr>';
797
798       $body .= '</table>';
799     } else {
800       // Regular report.
801
802       // Print table header.
803       $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
804       $body .= '<tr>';
805       $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.date').'</td>';
806       if ($canViewReports || $isClient)
807         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.user').'</td>';
808       if ($options['show_client'])
809         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.client').'</td>';
810       if ($options['show_project'])
811         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.project').'</td>';
812       if ($options['show_task'])
813         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.task').'</td>';
814       if ($options['show_custom_field_1'])
815         $body .= '<td style="'.$tableHeader.'">'.htmlspecialchars($custom_fields->fields[0]['label']).'</td>';
816       if ($options['show_start'])
817         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.start').'</td>';
818       if ($options['show_end'])
819         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.finish').'</td>';
820       if ($options['show_duration'])
821         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.duration').'</td>';
822       if ($options['show_work_units'])
823         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.work_units_short').'</td>';
824       if ($options['show_note'])
825         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.note').'</td>';
826       if ($options['show_cost'])
827         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.cost').'</td>';
828       if ($options['show_approved'])
829         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.approved').'</td>';
830       if ($options['show_paid'])
831         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.paid').'</td>';
832       if ($options['show_ip'])
833         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.ip').'</td>';
834       if ($options['show_invoice'])
835         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.invoice').'</td>';
836       if ($options['show_timesheet'])
837         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.timesheet').'</td>';
838       $body .= '</tr>';
839
840       // Initialize variables to print subtotals.
841       if ($items && $grouping) {
842         $print_subtotals = true;
843         $first_pass = true;
844         $prev_grouped_by = '';
845         $cur_grouped_by = '';
846       }
847       // Initialize variables to alternate color of rows for different dates.
848       $prev_date = '';
849       $cur_date = '';
850       $row_style = $rowItem;
851
852       // Print report items.
853       if (is_array($items)) {
854         foreach ($items as $record) {
855           $cur_date = $record['date'];
856           // Print a subtotal row after a block of grouped items.
857           if ($print_subtotals) {
858             $cur_grouped_by = $record['grouped_by'];
859             if ($cur_grouped_by != $prev_grouped_by && !$first_pass) {
860               $body .= '<tr style="'.$rowSubtotal.'">';
861               $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.subtotal').'</td>';
862               $subtotal_name = htmlspecialchars($subtotals[$prev_grouped_by]['name']);
863               if ($canViewReports || $isClient) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['user'].'</td>';
864               if ($options['show_client']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['client'].'</td>';
865               if ($options['show_project']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['project'].'</td>';
866               if ($options['show_task']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['task'].'</td>';
867               if ($options['show_custom_field_1']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['cf_1'].'</td>';
868               if ($options['show_start']) $body .= '<td></td>';
869               if ($options['show_end']) $body .= '<td></td>';
870               if ($options['show_duration']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['time'].'</td>';
871               if ($options['show_work_units']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['units'].'</td>';
872               if ($options['show_note']) $body .= '<td></td>';
873               if ($options['show_cost']) {
874                 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
875                 $body .= ($canViewReports || $isClient) ? $subtotals[$prev_grouped_by]['cost'] : $subtotals[$prev_grouped_by]['expenses'];
876                 $body .= '</td>';
877               }
878               if ($options['show_approved']) $body .= '<td></td>';
879               if ($options['show_paid']) $body .= '<td></td>';
880               if ($options['show_ip']) $body .= '<td></td>';
881               if ($options['show_invoice']) $body .= '<td></td>';
882               if ($options['show_timesheet']) $body .= '<td></td>';
883               $body .= '</tr>';
884               $body .= '<tr><td>&nbsp;</td></tr>';
885             }
886             $first_pass = false;
887           }
888
889           // Print a regular row.
890           if ($cur_date != $prev_date)
891             $row_style = ($row_style == $rowItem) ? $rowItemAlt : $rowItem;
892           $body .= '<tr style="'.$row_style.'">';
893           $body .= '<td style="'.$cellLeftAligned.'">'.$record['date'].'</td>';
894           if ($canViewReports || $isClient)
895             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['user']).'</td>';
896           if ($options['show_client'])
897             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['client']).'</td>';
898           if ($options['show_project'])
899             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['project']).'</td>';
900           if ($options['show_task'])
901             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['task']).'</td>';
902           if ($options['show_custom_field_1'])
903             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['cf_1']).'</td>';
904           if ($options['show_start'])
905             $body .= '<td nowrap style="'.$cellRightAligned.'">'.$record['start'].'</td>';
906           if ($options['show_end'])
907             $body .= '<td nowrap style="'.$cellRightAligned.'">'.$record['finish'].'</td>';
908           if ($options['show_duration'])
909             $body .= '<td style="'.$cellRightAligned.'">'.$record['duration'].'</td>';
910           if ($options['show_work_units'])
911             $body .= '<td style="'.$cellRightAligned.'">'.$record['units'].'</td>';
912           if ($options['show_note'])
913             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['note']).'</td>';
914           if ($options['show_cost'])
915             $body .= '<td style="'.$cellRightAligned.'">'.$record['cost'].'</td>';
916           if ($options['show_approved']) {
917             $body .= '<td style="'.$cellRightAligned.'">';
918             $body .= $record['approved'] == 1 ? $i18n->get('label.yes') : $i18n->get('label.no');
919             $body .= '</td>';
920           }
921           if ($options['show_paid']) {
922             $body .= '<td style="'.$cellRightAligned.'">';
923             $body .= $record['paid'] == 1 ? $i18n->get('label.yes') : $i18n->get('label.no');
924             $body .= '</td>';
925           }
926           if ($options['show_ip']) {
927             $body .= '<td style="'.$cellRightAligned.'">';
928             $body .= $record['modified'] ? $record['modified_ip'].' '.$record['modified'] : $record['created_ip'].' '.$record['created'];
929             $body .= '</td>';
930           }
931           if ($options['show_invoice'])
932             $body .= '<td style="'.$cellRightAligned.'">'.htmlspecialchars($record['invoice']).'</td>';
933           if ($options['show_timesheet'])
934             $body .= '<td style="'.$cellRightAligned.'">'.htmlspecialchars($record['timesheet']).'</td>';
935           $body .= '</tr>';
936
937           $prev_date = $record['date'];
938           if ($print_subtotals)
939             $prev_grouped_by = $record['grouped_by'];
940         }
941       }
942
943       // Print a terminating subtotal.
944       if ($print_subtotals) {
945         $body .= '<tr style="'.$rowSubtotal.'">';
946         $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.subtotal').'</td>';
947         $subtotal_name = htmlspecialchars($subtotals[$cur_grouped_by]['name']);
948         if ($canViewReports || $isClient) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['user'].'</td>';
949         if ($options['show_client']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['client'].'</td>';
950         if ($options['show_project']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['project'].'</td>';
951         if ($options['show_task']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['task'].'</td>';
952         if ($options['show_custom_field_1']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['cf_1'].'</td>';
953         if ($options['show_start']) $body .= '<td></td>';
954         if ($options['show_end']) $body .= '<td></td>';
955         if ($options['show_duration']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$cur_grouped_by]['time'].'</td>';
956         if ($options['show_work_units']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$cur_grouped_by]['units'].'</td>';
957         if ($options['show_note']) $body .= '<td></td>';
958         if ($options['show_cost']) {
959           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
960           $body .= ($canViewReports || $isClient) ? $subtotals[$cur_grouped_by]['cost'] : $subtotals[$cur_grouped_by]['expenses'];
961           $body .= '</td>';
962         }
963         if ($options['show_approved']) $body .= '<td></td>';
964         if ($options['show_paid']) $body .= '<td></td>';
965         if ($options['show_ip']) $body .= '<td></td>';
966         if ($options['show_invoice']) $body .= '<td></td>';
967         if ($options['show_timesheet']) $body .= '<td></td>';
968         $body .= '</tr>';
969       }
970
971       // Print totals.
972       $body .= '<tr><td>&nbsp;</td></tr>';
973       $body .= '<tr style="'.$rowSubtotal.'">';
974       $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.total').'</td>';
975       if ($canViewReports || $isClient) $body .= '<td></td>';
976       if ($options['show_client']) $body .= '<td></td>';
977       if ($options['show_project']) $body .= '<td></td>';
978       if ($options['show_task']) $body .= '<td></td>';
979       if ($options['show_custom_field_1']) $body .= '<td></td>';
980       if ($options['show_start']) $body .= '<td></td>';
981       if ($options['show_end']) $body .= '<td></td>';
982       if ($options['show_duration']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$totals['time'].'</td>';
983       if ($options['show_work_units']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$totals['units'].'</td>';
984       if ($options['show_note']) $body .= '<td></td>';
985       if ($options['show_cost']) {
986         $body .= '<td nowrap style="'.$cellRightAlignedSubtotal.'">'.htmlspecialchars($user->currency).' ';
987         $body .= ($canViewReports || $isClient) ? $totals['cost'] : $totals['expenses'];
988         $body .= '</td>';
989       }
990       if ($options['show_approved']) $body .= '<td></td>';
991       if ($options['show_paid']) $body .= '<td></td>';
992       if ($options['show_ip']) $body .= '<td></td>';
993       if ($options['show_invoice']) $body .= '<td></td>';
994       if ($options['show_timesheet']) $body .= '<td></td>';
995       $body .= '</tr>';
996
997       $body .= '</table>';
998     }
999
1000     // Output footer.
1001     if (!defined('REPORT_FOOTER') || !(REPORT_FOOTER == false))
1002       $body .= '<p style="text-align: center;">'.$i18n->get('form.mail.footer').'</p>';
1003
1004     // Finish creating email body.
1005     $body .= '</body></html>';
1006
1007     return $body;
1008   }
1009
1010   // checkFavReportCondition - checks whether it is okay to send fav report.
1011   static function checkFavReportCondition($options, $condition)
1012   {
1013     $items = ttReportHelper::getItems($options);
1014
1015     $condition = trim(str_replace('count', '', $condition));
1016
1017     $greater_or_equal = ttStartsWith($condition, '>=');
1018     if ($greater_or_equal) $condition = trim(str_replace('>=', '', $condition));
1019
1020     $less_or_equal = ttStartsWith($condition, '<=');
1021     if ($less_or_equal) $condition = trim(str_replace('<=', '', $condition));
1022
1023     $not_equal = ttStartsWith($condition, '<>');
1024     if ($not_equal) $condition = trim(str_replace('<>', '', $condition));
1025
1026     $greater = ttStartsWith($condition, '>');
1027     if ($greater) $condition = trim(str_replace('>', '', $condition));
1028
1029     $less = ttStartsWith($condition, '<');
1030     if ($less) $condition = trim(str_replace('<', '', $condition));
1031
1032     $equal = ttStartsWith($condition, '=');
1033     if ($equal) $condition = trim(str_replace('=', '', $condition));
1034
1035     $count_required = (int) $condition;
1036
1037     if ($greater && count($items) > $count_required) return true;
1038     if ($greater_or_equal && count($items) >= $count_required) return true;
1039     if ($less && count($items) < $count_required) return true;
1040     if ($less_or_equal && count($items) <= $count_required) return true;
1041     if ($equal && count($items) == $count_required) return true;
1042     if ($not_equal && count($items) <> $count_required) return true;
1043
1044     return false;
1045   }
1046
1047   // sendFavReport - sends a favorite report to a specified email, called from cron.php
1048   static function sendFavReport($options, $subject, $email, $cc) {
1049     // We are called from cron.php, we have no $bean in session.
1050     // cron.php sets global $user and $i18n objects to match our favorite report user.
1051     global $user;
1052     global $i18n;
1053
1054     // Prepare report body.
1055     $body = ttReportHelper::prepareReportBody($options);
1056
1057     import('mail.Mailer');
1058     $mailer = new Mailer();
1059     $mailer->setCharSet(CHARSET);
1060     $mailer->setContentType('text/html');
1061     $mailer->setSender(SENDER);
1062     if (!empty($cc))
1063       $mailer->setReceiverCC($cc);
1064     if (!empty($user->bcc_email))
1065       $mailer->setReceiverBCC($user->bcc_email);
1066     $mailer->setReceiver($email);
1067     $mailer->setMailMode(MAIL_MODE);
1068     if (empty($subject)) $subject = $options['name'];
1069     if (!$mailer->send($subject, $body))
1070       return false;
1071
1072     return true;
1073   }
1074
1075   // getReportOptions - returns an array of report options constructed from session bean.
1076   //
1077   // Note: similarly to ttFavReportHelper::getReportOptions, this function is a part of
1078   // refactoring to simplify maintenance of report generating functions, as we currently
1079   // have 2 sets: normal reporting (from bean), and fav report emailing (from db fields).
1080   // Using options obtained from either db or bean shall allow us to use only one set of functions.
1081   static function getReportOptions($bean) {
1082     global $user;
1083
1084     // Prepare an array of report options.
1085     $options = array();
1086
1087     // Construct one by one.
1088     $options['name'] = null; // No name required.
1089     $options['user_id'] = $user->id; // Not sure if we need user_id here. Fav reports use it to recycle $user object in cron.php.
1090     $options['client_id'] = $bean->getAttribute('client');
1091     $options['cf_1_option_id'] = $bean->getAttribute('option');
1092     $options['project_id'] = $bean->getAttribute('project');
1093     $options['task_id'] = $bean->getAttribute('task');
1094     $options['billable'] = $bean->getAttribute('include_records');
1095     $options['invoice'] = $bean->getAttribute('invoice');
1096     $options['paid_status'] = $bean->getAttribute('paid_status');
1097     $options['approved'] = $bean->getAttribute('approved');
1098     if ($user->isPluginEnabled('ap') && $user->isClient() && !$user->can('view_client_unapproved'))
1099       $options['approved'] = 1; // Restrict clients to approved records only.
1100     $options['timesheet'] = $bean->getAttribute('timesheet');
1101     if (is_array($bean->getAttribute('users'))) $options['users'] = join(',', $bean->getAttribute('users'));
1102     $options['period'] = $bean->getAttribute('period');
1103     $options['period_start'] = $bean->getAttribute('start_date');
1104     $options['period_end'] = $bean->getAttribute('end_date');
1105     $options['show_client'] = $bean->getAttribute('chclient');
1106     $options['show_invoice'] = $bean->getAttribute('chinvoice');
1107     $options['show_approved'] = $bean->getAttribute('chapproved');
1108     $options['show_paid'] = $bean->getAttribute('chpaid');
1109     $options['show_ip'] = $bean->getAttribute('chip');
1110     $options['show_project'] = $bean->getAttribute('chproject');
1111     $options['show_start'] = $bean->getAttribute('chstart');
1112     $options['show_duration'] = $bean->getAttribute('chduration');
1113     $options['show_cost'] = $bean->getAttribute('chcost');
1114     $options['show_task'] = $bean->getAttribute('chtask');
1115     $options['show_end'] = $bean->getAttribute('chfinish');
1116     $options['show_note'] = $bean->getAttribute('chnote');
1117     $options['show_custom_field_1'] = $bean->getAttribute('chcf_1');
1118     $options['show_work_units'] = $bean->getAttribute('chunits');
1119     $options['show_timesheet'] = $bean->getAttribute('chtimesheet');
1120     $options['show_totals_only'] = $bean->getAttribute('chtotalsonly');
1121     $options['group_by1'] = $bean->getAttribute('group_by1');
1122     $options['group_by2'] = $bean->getAttribute('group_by2');
1123     $options['group_by3'] = $bean->getAttribute('group_by3');
1124     return $options;
1125   }
1126
1127   // verifyBean is a security function to make sure data in bean makes sense for a group.
1128   static function verifyBean($bean) {
1129     global $user;
1130
1131     // Check users.
1132     $users_in_bean = $bean->getAttribute('users');
1133     if (is_array($users_in_bean)) {
1134       $users_in_group = ttGroupHelper::getUsers();
1135       foreach ($users_in_group as $user_in_group) {
1136         $valid_ids[] = $user_in_group['id'];
1137       }
1138       foreach ($users_in_bean as $user_in_bean) {
1139         if (!in_array($user_in_bean, $valid_ids)) {
1140           return false;
1141         }
1142       }
1143     }
1144
1145     // TODO: add additional checks here. Perhaps do it before saving the bean for consistency.
1146     return true;
1147   }
1148
1149   // makeGroupByKey builds a combined group by key from group_by1, group_by2 and group_by3 values
1150   // (passed in $options) and a row of data ($row obtained from a db query).
1151   static function makeGroupByKey($options, $row) {
1152     if ($options['group_by1'] != null && $options['group_by1'] != 'no_grouping') {
1153       // We have group_by1.
1154       $group_by1 = $options['group_by1'];
1155       $group_by1_value = $row[$group_by1];
1156       //if ($group_by1 == 'date') $group_by1_value = ttDateToUserFormat($group_by1_value);
1157       if (empty($group_by1_value)) $group_by1_value = 'Null'; // To match what comes out of makeConcatPart.
1158       $group_by_key .= ' - '.$group_by1_value;
1159     }
1160     if ($options['group_by2'] != null && $options['group_by2'] != 'no_grouping') {
1161       // We have group_by2.
1162       $group_by2 = $options['group_by2'];
1163       $group_by2_value = $row[$group_by2];
1164       //if ($group_by2 == 'date') $group_by2_value = ttDateToUserFormat($group_by2_value);
1165       if (empty($group_by2_value)) $group_by2_value = 'Null'; // To match what comes out of makeConcatPart.
1166       $group_by_key .= ' - '.$group_by2_value;
1167     }
1168     if ($options['group_by3'] != null && $options['group_by3'] != 'no_grouping') {
1169       // We have group_by3.
1170       $group_by3 = $options['group_by3'];
1171       $group_by3_value = $row[$group_by3];
1172       //if ($group_by3 == 'date') $group_by3_value = ttDateToUserFormat($group_by3_value);
1173       if (empty($group_by3_value)) $group_by3_value = 'Null'; // To match what comes out of makeConcatPart.
1174       $group_by_key .= ' - '.$group_by3_value;
1175     }
1176     $group_by_key = trim($group_by_key, ' -');
1177     return $group_by_key;
1178   }
1179
1180   // makeGroupByPart builds a combined group by part for sql query for time items using group_by1,
1181   // group_by2, and group_by3 values passed in $options.
1182   static function makeGroupByPart($options) {
1183     if (!ttReportHelper::grouping($options)) return null;
1184
1185     $group_by1 = $options['group_by1'];
1186     $group_by2 = $options['group_by2'];
1187     $group_by3 = $options['group_by3'];
1188
1189     switch ($group_by1) {
1190       case 'date':
1191         $group_by_parts .= ', l.date';
1192         break;
1193       case 'user':
1194         $group_by_parts .= ', u.name';
1195         break;
1196       case 'client':
1197         $group_by_parts .= ', c.name';
1198         break;
1199       case 'project':
1200         $group_by_parts .= ', p.name';
1201         break;
1202       case 'task':
1203         $group_by_parts .= ', t.name';
1204         break;
1205       case 'cf_1':
1206         $group_by_parts .= ', cfo.value';
1207         break;
1208     }
1209     switch ($group_by2) {
1210       case 'date':
1211         $group_by_parts .= ', l.date';
1212         break;
1213       case 'user':
1214         $group_by_parts .= ', u.name';
1215         break;
1216       case 'client':
1217         $group_by_parts .= ', c.name';
1218         break;
1219       case 'project':
1220         $group_by_parts .= ', p.name';
1221         break;
1222       case 'task':
1223         $group_by_parts .= ', t.name';
1224         break;
1225       case 'cf_1':
1226         $group_by_parts .= ', cfo.value';
1227         break;
1228     }
1229     switch ($group_by3) {
1230       case 'date':
1231         $group_by_parts .= ', l.date';
1232         break;
1233       case 'user':
1234         $group_by_parts .= ', u.name';
1235         break;
1236       case 'client':
1237         $group_by_parts .= ', c.name';
1238         break;
1239       case 'project':
1240         $group_by_parts .= ', p.name';
1241         break;
1242       case 'task':
1243         $group_by_parts .= ', t.name';
1244         break;
1245       case 'cf_1':
1246         $group_by_parts .= ', cfo.value';
1247         break;
1248     }
1249     // Remove garbage from the beginning.
1250     $group_by_parts = ltrim($group_by_parts, ', ');
1251     $group_by_part = "group by $group_by_parts";
1252     return $group_by_part;
1253   }
1254
1255   // makeGroupByExpensesPart builds a combined group by part for sql query for expense items using
1256   // group_by1, group_by2, and group_by3 values passed in $options.
1257   static function makeGroupByExpensesPart($options) {
1258     $no_grouping = ($options['group_by1'] == null || $options['group_by1'] == 'no_grouping') &&
1259       ($options['group_by2'] == null || $options['group_by2'] == 'no_grouping') &&
1260       ($options['group_by3'] == null || $options['group_by3'] == 'no_grouping');
1261     if ($no_grouping) return null;
1262
1263     $group_by1 = $options['group_by1'];
1264     $group_by2 = $options['group_by2'];
1265     $group_by3 = $options['group_by3'];
1266
1267     switch ($group_by1) {
1268       case 'date':
1269         $group_by_parts .= ', ei.date';
1270         break;
1271       case 'user':
1272         $group_by_parts .= ', u.name';
1273         break;
1274       case 'client':
1275         $group_by_parts .= ', c.name';
1276         break;
1277       case 'project':
1278         $group_by_parts .= ', p.name';
1279         break;
1280     }
1281     switch ($group_by2) {
1282       case 'date':
1283         $group_by_parts .= ', ei.date';
1284         break;
1285       case 'user':
1286         $group_by_parts .= ', u.name';
1287         break;
1288       case 'client':
1289         $group_by_parts .= ', c.name';
1290         break;
1291       case 'project':
1292         $group_by_parts .= ', p.name';
1293         break;
1294     }
1295     switch ($group_by3) {
1296       case 'date':
1297         $group_by_parts .= ', ei.date';
1298         break;
1299       case 'user':
1300         $group_by_parts .= ', u.name';
1301         break;
1302       case 'client':
1303         $group_by_parts .= ', c.name';
1304         break;
1305       case 'project':
1306         $group_by_parts .= ', p.name';
1307         break;
1308     }
1309     // Remove garbage from the beginning.
1310     $group_by_parts = ltrim($group_by_parts, ', ');
1311     if ($group_by_parts)
1312       $group_by_part = "group by $group_by_parts";
1313     return $group_by_part;
1314   }
1315
1316   // makeConcatPart builds a concatenation part for getSubtotals query (for time items).
1317   static function makeConcatPart($options) {
1318     $group_by1 = $options['group_by1'];
1319     $group_by2 = $options['group_by2'];
1320     $group_by3 = $options['group_by3'];
1321
1322     switch ($group_by1) {
1323       case 'date':
1324         $what_to_concat .= ", ' - ', l.date";
1325         break;
1326       case 'user':
1327         $what_to_concat .= ", ' - ', u.name";
1328         $fields_part .= ', u.name as user';
1329         break;
1330       case 'client':
1331         $what_to_concat .= ", ' - ', coalesce(c.name, 'Null')";
1332         $fields_part .= ', c.name as client';
1333         break;
1334       case 'project':
1335         $what_to_concat .= ", ' - ', coalesce(p.name, 'Null')";
1336         $fields_part .= ', p.name as project';
1337         break;
1338       case 'task':
1339         $what_to_concat .= ", ' - ', coalesce(t.name, 'Null')";
1340         $fields_part .= ', t.name as task';
1341         break;
1342       case 'cf_1':
1343         $what_to_concat .= ", ' - ', coalesce(cfo.value, 'Null')";
1344         $fields_part .= ', cfo.value as cf_1';
1345         break;
1346     }
1347     switch ($group_by2) {
1348       case 'date':
1349         $what_to_concat .= ", ' - ', l.date";
1350         break;
1351       case 'user':
1352         $what_to_concat .= ", ' - ', u.name";
1353         $fields_part .= ', u.name as user';
1354         break;
1355       case 'client':
1356         $what_to_concat .= ", ' - ', coalesce(c.name, 'Null')";
1357         $fields_part .= ', c.name as client';
1358         break;
1359       case 'project':
1360         $what_to_concat .= ", ' - ', coalesce(p.name, 'Null')";
1361         $fields_part .= ', p.name as project';
1362         break;
1363       case 'task':
1364         $what_to_concat .= ", ' - ', coalesce(t.name, 'Null')";
1365         $fields_part .= ', t.name as task';
1366         break;
1367       case 'cf_1':
1368         $what_to_concat .= ", ' - ', coalesce(cfo.value, 'Null')";
1369         $fields_part .= ', cfo.value as cf_1';
1370         break;
1371     }
1372     switch ($group_by3) {
1373       case 'date':
1374         $what_to_concat .= ", ' - ', l.date";
1375         break;
1376       case 'user':
1377         $what_to_concat .= ", ' - ', u.name";
1378         $fields_part .= ', u.name as user';
1379         break;
1380       case 'client':
1381         $what_to_concat .= ", ' - ', coalesce(c.name, 'Null')";
1382         $fields_part .= ', c.name as client';
1383         break;
1384       case 'project':
1385         $what_to_concat .= ", ' - ', coalesce(p.name, 'Null')";
1386         $fields_part .= ', p.name as project';
1387         break;
1388       case 'task':
1389         $what_to_concat .= ", ' - ', coalesce(t.name, 'Null')";
1390         $fields_part .= ', t.name as task';
1391         break;
1392       case 'cf_1':
1393         $what_to_concat .= ", ' - ', coalesce(cfo.value, 'Null')";
1394         $fields_part .= ', cfo.value as cf_1';
1395         break;
1396     }
1397     // Remove garbage from both ends.
1398     $what_to_concat = trim($what_to_concat, "', -");
1399     $concat_part = "concat($what_to_concat) as group_field";
1400     $concat_part = trim($concat_part, ' -');
1401     return "$concat_part $fields_part";
1402   }
1403
1404   // makeConcatPart builds a concatenation part for getSubtotals query (for expense items).
1405   static function makeConcatExpensesPart($options) {
1406     $group_by1 = $options['group_by1'];
1407     $group_by2 = $options['group_by2'];
1408     $group_by3 = $options['group_by3'];
1409
1410     switch ($group_by1) {
1411       case 'date':
1412         $what_to_concat .= ", ' - ', ei.date";
1413         break;
1414       case 'user':
1415         $what_to_concat .= ", ' - ', u.name";
1416         $fields_part .= ', u.name as user';
1417         break;
1418       case 'client':
1419         $what_to_concat .= ", ' - ', coalesce(c.name, 'Null')";
1420         $fields_part .= ', c.name as client';
1421         break;
1422       case 'project':
1423         $what_to_concat .= ", ' - ', coalesce(p.name, 'Null')";
1424         $fields_part .= ', p.name as project';
1425         break;
1426
1427       case 'task':
1428         $what_to_concat .= ", ' - ', 'Null'";
1429         $fields_part .= ', null as task';
1430         break;
1431
1432       case 'cf_1':
1433         $what_to_concat .= ", ' - ', 'Null'";
1434         $fields_part .= ', null as cf_1';
1435         break;
1436     }
1437     switch ($group_by2) {
1438       case 'date':
1439         $what_to_concat .= ", ' - ', ei.date";
1440         break;
1441       case 'user':
1442         $what_to_concat .= ", ' - ', u.name";
1443         $fields_part .= ', u.name as user';
1444         break;
1445       case 'client':
1446         $what_to_concat .= ", ' - ', coalesce(c.name, 'Null')";
1447         $fields_part .= ', c.name as client';
1448         break;
1449       case 'project':
1450         $what_to_concat .= ", ' - ', coalesce(p.name, 'Null')";
1451         $fields_part .= ', p.name as project';
1452         break;
1453
1454       case 'task':
1455         $what_to_concat .= ", ' - ', 'Null'";
1456         $fields_part .= ', null as task';
1457         break;
1458
1459       case 'cf_1':
1460         $what_to_concat .= ", ' - ', 'Null'";
1461         $fields_part .= ', null as cf_1';
1462         break;
1463     }
1464     switch ($group_by3) {
1465       case 'date':
1466         $what_to_concat .= ", ' - ', ei.date";
1467         break;
1468       case 'user':
1469         $what_to_concat .= ", ' - ', u.name";
1470         $fields_part .= ', u.name as user';
1471         break;
1472       case 'client':
1473         $what_to_concat .= ", ' - ', coalesce(c.name, 'Null')";
1474         $fields_part .= ', c.name as client';
1475         break;
1476       case 'project':
1477         $what_to_concat .= ", ' - ', coalesce(p.name, 'Null')";
1478         $fields_part .= ', p.name as project';
1479         break;
1480
1481       case 'task':
1482         $what_to_concat .= ", ' - ', 'Null'";
1483         $fields_part .= ', null as task';
1484         break;
1485
1486       case 'cf_1':
1487         $what_to_concat .= ", ' - ', 'Null'";
1488         $fields_part .= ', null as cf_1';
1489         break;
1490     }
1491     // Remove garbage from the beginning.
1492     if ($what_to_concat)
1493         $what_to_concat = substr($what_to_concat, 8);
1494     $concat_part = "concat($what_to_concat) as group_field";
1495     return "$concat_part $fields_part";
1496   }
1497
1498   // makeCombinedSelectPart builds a list of fields for a combined select on a union for getSubtotals.
1499   // This is used when we include expenses.
1500   static function makeCombinedSelectPart($options) {
1501     $group_by1 = $options['group_by1'];
1502     $group_by2 = $options['group_by2'];
1503     $group_by3 = $options['group_by3'];
1504
1505     $fields = "group_field";
1506
1507     switch ($group_by1) {
1508       case 'user':
1509         $fields .= ', user';
1510         break;
1511       case 'client':
1512         $fields_part .= ', client';
1513         break;
1514       case 'project':
1515         $fields .= ', project';
1516         break;
1517
1518       case 'task':
1519         $fields .= ', task';
1520         break;
1521
1522       case 'cf_1':
1523         $fields .= ', cf_1';
1524         break;
1525     }
1526     switch ($group_by2) {
1527       case 'user':
1528         $fields .= ', user';
1529         break;
1530       case 'client':
1531         $fields_part .= ', client';
1532         break;
1533       case 'project':
1534         $fields .= ', project';
1535         break;
1536
1537       case 'task':
1538         $fields .= ', task';
1539         break;
1540
1541       case 'cf_1':
1542         $fields .= ', cf_1';
1543         break;
1544     }
1545     switch ($group_by3) {
1546       case 'user':
1547         $fields .= ', user';
1548         break;
1549       case 'client':
1550         $fields_part .= ', client';
1551         break;
1552       case 'project':
1553         $fields .= ', project';
1554         break;
1555
1556       case 'task':
1557         $fields .= ', task';
1558         break;
1559
1560       case 'cf_1':
1561         $fields .= ', cf_1';
1562         break;
1563     }
1564     return $fields;
1565   }
1566
1567   // makeJoinPart builds a left join part for getSubtotals query (for time items).
1568   static function makeJoinPart($options) {
1569     global $user;
1570
1571     $trackingMode = $user->getTrackingMode();
1572     if (ttReportHelper::groupingBy('user', $options) || MODE_TIME == $trackingMode) {
1573       $join .= ' left join tt_users u on (l.user_id = u.id)';
1574     }
1575     if (ttReportHelper::groupingBy('client', $options)) {
1576       $join .= ' left join tt_clients c on (l.client_id = c.id)';
1577     }
1578     if (ttReportHelper::groupingBy('project', $options)) {
1579       $join .= ' left join tt_projects p on (l.project_id = p.id)';
1580     }
1581     if (ttReportHelper::groupingBy('task', $options)) {
1582       $join .= ' left join tt_tasks t on (l.task_id = t.id)';
1583     }
1584     if (ttReportHelper::groupingBy('cf_1', $options)) {
1585       $custom_fields = new CustomFields();
1586       if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_TEXT)
1587         $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)';
1588       elseif ($custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN)
1589         $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)';
1590     }
1591     if ($options['show_cost'] && $trackingMode != MODE_TIME) {
1592       $join .= ' left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id)';
1593     }
1594     // Prepare inner joins.
1595     $inner_joins = null;
1596     if ($user->isPluginEnabled('ts') && $options['timesheet']) {
1597       $timesheet_option = $options['timesheet'];
1598       if ($timesheet_option == TIMESHEET_PENDING)
1599         $inner_joins .= " inner join tt_timesheets ts on (l.timesheet_id = ts.id and ts.submit_status = 1 and ts.approve_status is null)";
1600       else if ($timesheet_option == TIMESHEET_APPROVED)
1601         $inner_joins .= " inner join tt_timesheets ts on (l.timesheet_id = ts.id and ts.approve_status = 1)";
1602       else if ($timesheet_option == TIMESHEET_NOT_APPROVED)
1603         $inner_joins .= " inner join tt_timesheets ts on (l.timesheet_id = ts.id and ts.approve_status = 0)";
1604     }
1605     $join .= $inner_joins;
1606     return $join;
1607   }
1608
1609   // makeWorkUnitPart builds an sql part for work units for time items.
1610   static function makeWorkUnitPart($options) {
1611     global $user;
1612
1613     $workUnits = $options['show_work_units'];
1614     if ($workUnits) {
1615       $unitTotalsOnly = $user->getConfigOption('unit_totals_only');
1616       $firstUnitThreshold = $user->getConfigInt('1st_unit_threshold', 0);
1617       $minutesInUnit = $user->getConfigInt('minutes_in_unit', 15);
1618       if ($unitTotalsOnly)
1619         $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";
1620       else
1621         $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";
1622     }
1623     return $work_unit_part;
1624   }
1625
1626   // makeCostPart builds a cost part for time items.
1627   static function makeCostPart($options) {
1628     global $user;
1629
1630     if ($options['show_cost']) {
1631       if (MODE_TIME == $user->getTrackingMode())
1632         $cost_part = ", sum(cast(l.billable * coalesce(u.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10, 2))) as cost";
1633       else
1634         $cost_part .= ", sum(cast(l.billable * coalesce(upb.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10,2))) as cost";
1635     }
1636     return $cost_part;
1637   }
1638
1639   // makeJoinExpensesPart builds a left join part for getSubtotals query for expense items.
1640   static function makeJoinExpensesPart($options) {
1641     global $user;
1642
1643     if (ttReportHelper::groupingBy('user', $options)) {
1644       $join .= ' left join tt_users u on (ei.user_id = u.id)';
1645     }
1646     if (ttReportHelper::groupingBy('client', $options)) {
1647       $join .= ' left join tt_clients c on (ei.client_id = c.id)';
1648     }
1649     if (ttReportHelper::groupingBy('project', $options)) {
1650       $join .= ' left join tt_projects p on (ei.project_id = p.id)';
1651     }
1652     return $join;
1653   }
1654
1655   // grouping determines if we are grouping the report by either group_by1,
1656   // group_by2, or group_by3 values passed in $options.
1657   static function grouping($options) {
1658     $grouping = ($options['group_by1'] != null && $options['group_by1'] != 'no_grouping') ||
1659       ($options['group_by2'] != null && $options['group_by2'] != 'no_grouping') ||
1660       ($options['group_by3'] != null && $options['group_by3'] != 'no_grouping');
1661     return $grouping;
1662   }
1663
1664   // groupingBy determines if we are grouping a report by a value of $what
1665   // ('date', 'user', 'project', etc.) by checking group_by1, group_by2,
1666   // and group_by3 values passed in $options.
1667   static function groupingBy($what, $options) {
1668     $grouping = ($options['group_by1'] == $what) || ($options['group_by2'] == $what) || ($options['group_by3'] == $what);
1669     return $grouping;
1670   }
1671
1672   // makeGroupByHeader builds a column header for a totals-only report using group_by1,
1673   // group_by2, and group_by3 values passed in $options.
1674   static function makeGroupByHeader($options) {
1675     global $i18n;
1676     global $custom_fields;
1677
1678     $no_grouping = ($options['group_by1'] == null || $options['group_by1'] == 'no_grouping') &&
1679       ($options['group_by2'] == null || $options['group_by2'] == 'no_grouping') &&
1680       ($options['group_by3'] == null || $options['group_by3'] == 'no_grouping');
1681     if ($no_grouping) return null;
1682
1683     if ($options['group_by1'] != null && $options['group_by1'] != 'no_grouping') {
1684       // We have group_by1.
1685       $group_by1 = $options['group_by1'];
1686       if ('cf_1' == $group_by1)
1687         $group_by_header .= ' - '.$custom_fields->fields[0]['label'];
1688       else {
1689         $key = 'label.'.$group_by1;
1690         $group_by_header .= ' - '.$i18n->get($key);
1691       }
1692     }
1693     if ($options['group_by2'] != null && $options['group_by2'] != 'no_grouping') {
1694       // We have group_by2.
1695       $group_by2 = $options['group_by2'];
1696       if ('cf_1' == $group_by2)
1697         $group_by_header .= ' - '.$custom_fields->fields[0]['label'];
1698       else {
1699         $key = 'label.'.$group_by2;
1700         $group_by_header .= ' - '.$i18n->get($key);
1701       }
1702     }
1703     if ($options['group_by3'] != null && $options['group_by3'] != 'no_grouping') {
1704       // We have group_by3.
1705       $group_by3 = $options['group_by3'];
1706       if ('cf_1' == $group_by3)
1707         $group_by_header .= ' - '.$custom_fields->fields[0]['label'];
1708       else {
1709         $key = 'label.'.$group_by3;
1710         $group_by_header .= ' - '.$i18n->get($key);
1711       }
1712     }
1713     $group_by_header = ltrim($group_by_header, ' -');
1714     return $group_by_header;
1715   }
1716
1717   // makeGroupByXmlTag creates an xml tag for a totals only report using group_by1,
1718   // group_by2, and group_by3 values passed in $options.
1719   static function makeGroupByXmlTag($options) {
1720     if ($options['group_by1'] != null && $options['group_by1'] != 'no_grouping') {
1721       // We have group_by1.
1722       $tag .= '_'.$options['group_by1'];
1723     }
1724     if ($options['group_by2'] != null && $options['group_by2'] != 'no_grouping') {
1725       // We have group_by2.
1726       $tag .= '_'.$options['group_by2'];
1727     }
1728     if ($options['group_by3'] != null && $options['group_by3'] != 'no_grouping') {
1729       // We have group_by3.
1730       $tag .= '_'.$options['group_by3'];
1731     }
1732     $tag = ltrim($tag, '_');
1733     return $tag;
1734   }
1735
1736   // makeGroupByLabel builds a label for one row in a "Totals only" report of grouped by items.
1737   // It does one thing: if we are grouping by date, the date format is converted for user.
1738   static function makeGroupByLabel($key, $options) {
1739     if (!ttReportHelper::groupingBy('date', $options))
1740       return $key; // No need to format.
1741
1742     global $user;
1743     if ($user->getDateFormat() == DB_DATEFORMAT)
1744       return $key; // No need to format.
1745
1746     $label = $key;
1747     if (preg_match('/\d\d\d\d-\d\d-\d\d/', $key, $matches)) {
1748       // Replace the first found match of a date in DB_DATEFORMAT.
1749       // This is not entirely clean but better than nothing for a label in a row.
1750       $userDate = ttDateToUserFormat($matches[0]);
1751       $label = str_replace($matches[0], $userDate, $key);
1752     }
1753     return $label;
1754   }
1755 }