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