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