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