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