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