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