Some more work in progress on multiple grouping by.
[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 // Class ttReportHelper is used for help with reports.
37 class ttReportHelper {
38
39   // getWhere prepares a WHERE clause for a report query.
40   static function getWhere($options) {
41     global $user;
42
43     // Prepare dropdown parts.
44     $dropdown_parts = '';
45     if ($options['client_id'])
46       $dropdown_parts .= ' and l.client_id = '.$options['client_id'];
47     elseif ($user->isClient() && $user->client_id)
48       $dropdown_parts .= ' and l.client_id = '.$user->client_id;
49     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'].')';
50     if ($options['project_id']) $dropdown_parts .= ' and l.project_id = '.$options['project_id'];
51     if ($options['task_id']) $dropdown_parts .= ' and l.task_id = '.$options['task_id'];
52     if ($options['billable']=='1') $dropdown_parts .= ' and l.billable = 1';
53     if ($options['billable']=='2') $dropdown_parts .= ' and l.billable = 0';
54     if ($options['invoice']=='1') $dropdown_parts .= ' and l.invoice_id is not NULL';
55     if ($options['invoice']=='2') $dropdown_parts .= ' and l.invoice_id is NULL';
56     if ($options['paid_status']=='1') $dropdown_parts .= ' and l.paid = 1';
57     if ($options['paid_status']=='2') $dropdown_parts .= ' and l.paid = 0';
58
59     // Prepare sql query part for user list.
60     $userlist = $options['users'] ? $options['users'] : '-1';
61     if ($user->can('view_reports') || $user->can('view_all_reports') || $user->isClient())
62       $user_list_part = " and l.user_id in ($userlist)";
63     else
64       $user_list_part = " and l.user_id = ".$user->id;
65     $user_list_part .= " and l.group_id = ".$user->getActiveGroup();
66
67     // Prepare sql query part for where.
68     if ($options['period'])
69       $period = new Period($options['period'], new DateAndTime($user->date_format));
70     else {
71       $period = new Period();
72       $period->setPeriod(
73         new DateAndTime($user->date_format, $options['period_start']),
74         new DateAndTime($user->date_format, $options['period_end']));
75     }
76     $where = " where l.status = 1 and l.date >= '".$period->getStartDate(DB_DATEFORMAT)."' and l.date <= '".$period->getEndDate(DB_DATEFORMAT)."'".
77       " $user_list_part $dropdown_parts";
78     return $where;
79   }
80
81   // getExpenseWhere prepares WHERE clause for expenses query in a report.
82   static function getExpenseWhere($options) {
83     global $user;
84
85     // Prepare dropdown parts.
86     $dropdown_parts = '';
87     if ($options['client_id'])
88       $dropdown_parts .= ' and ei.client_id = '.$options['client_id'];
89     elseif ($user->isClient() && $user->client_id)
90       $dropdown_parts .= ' and ei.client_id = '.$user->client_id;
91     if ($options['project_id']) $dropdown_parts .= ' and ei.project_id = '.$options['project_id'];
92     if ($options['invoice']=='1') $dropdown_parts .= ' and ei.invoice_id is not NULL';
93     if ($options['invoice']=='2') $dropdown_parts .= ' and ei.invoice_id is NULL';
94     if ($options['paid_status']=='1') $dropdown_parts .= ' and ei.paid = 1';
95     if ($options['paid_status']=='2') $dropdown_parts .= ' and ei.paid = 0';
96
97     // Prepare sql query part for user list.
98     $userlist = $options['users'] ? $options['users'] : '-1';
99     if ($user->can('view_reports') || $user->can('view_all_reports') || $user->isClient())
100       $user_list_part = " and ei.user_id in ($userlist)";
101     else
102       $user_list_part = " and ei.user_id = ".$user->id;
103     $user_list_part .= " and ei.group_id = ".$user->getActiveGroup();
104
105     // Prepare sql query part for where.
106     if ($options['period'])
107       $period = new Period($options['period'], new DateAndTime($user->date_format));
108     else {
109       $period = new Period();
110       $period->setPeriod(
111         new DateAndTime($user->date_format, $options['period_start']),
112         new DateAndTime($user->date_format, $options['period_end']));
113     }
114     $where = " where ei.status = 1 and ei.date >= '".$period->getStartDate(DB_DATEFORMAT)."' and ei.date <= '".$period->getEndDate(DB_DATEFORMAT)."'".
115       " $user_list_part $dropdown_parts";
116     return $where;
117   }
118
119   // getItems retrieves all items associated with a report.
120   // It combines tt_log and tt_expense_items in one array for presentation in one table using mysql union all.
121   // Expense items use the "note" field for item name.
122   static function getItems($options) {
123     global $user;
124     $mdb2 = getConnection();
125
126     // Determine these once as they are used in multiple places in this function.
127     $canViewReports = $user->can('view_reports') || $user->can('view_all_reports');
128     $isClient = $user->isClient();
129
130     $no_grouping = ($options['group_by1'] == null || $options['group_by1'] == 'no_grouping') &&
131                    ($options['group_by2'] == null || $options['group_by2'] == 'no_grouping') &&
132                    ($options['group_by3'] == null || $options['group_by3'] == 'no_grouping');
133     $grouping_by_date = ($options['group_by1'] == 'date'|| $options['group_by2'] == 'date' || $options['group_by3'] == 'date');
134     $grouping_by_client = ($options['group_by1'] == 'client'|| $options['group_by2'] == 'client' || $options['group_by3'] == 'client');
135     $grouping_by_project = ($options['group_by1'] == 'project'|| $options['group_by2'] == 'project' || $options['group_by3'] == 'project');
136     $grouping_by_task = ($options['group_by1'] == 'task'|| $options['group_by2'] == 'task' || $options['group_by3'] == 'task');
137     $grouping_by_user = ($options['group_by1'] == 'user'|| $options['group_by2'] == 'user' || $options['group_by3'] == 'user');
138     $grouping_by_cf_1 = ($options['group_by1'] == 'cf_1'|| $options['group_by2'] == 'cf_1' || $options['group_by3'] == 'cf_1');
139
140     $group_by_option = $options['group_by1'];
141     $convertTo12Hour = ('%I:%M %p' == $user->time_format) && ($options['show_start'] || $options['show_end']);
142
143     // Prepare a query for time items in tt_log table.
144     $fields = array(); // An array of fields for database query.
145     array_push($fields, 'l.id as id');
146     array_push($fields, '1 as type'); // Type 1 is for tt_log entries.
147     array_push($fields, 'l.date as date');
148     if($canViewReports || $isClient)
149       array_push($fields, 'u.name as user');
150     // Add client name if it is selected.
151     if ($options['show_client'] || $grouping_by_client)
152       array_push($fields, 'c.name as client');
153     // Add project name if it is selected.
154     if ($options['show_project'] || $grouping_by_project)
155       array_push($fields, 'p.name as project');
156     // Add task name if it is selected.
157     if ($options['show_task'] || $grouping_by_task)
158       array_push($fields, 't.name as task');
159     // Add custom field.
160     $include_cf_1 = $options['show_custom_field_1'] || $grouping_by_cf_1;
161     if ($include_cf_1) {
162       $custom_fields = new CustomFields($user->group_id);
163       $cf_1_type = $custom_fields->fields[0]['type'];
164       if ($cf_1_type == CustomFields::TYPE_TEXT) {
165         array_push($fields, 'cfl.value as cf_1');
166       } elseif ($cf_1_type == CustomFields::TYPE_DROPDOWN) {
167         array_push($fields, 'cfo.value as cf_1');
168       }
169     }
170     // Add start time.
171     if ($options['show_start']) {
172       array_push($fields, "l.start as unformatted_start");
173       array_push($fields, "TIME_FORMAT(l.start, '%k:%i') as start");
174     }
175     // Add finish time.
176     if ($options['show_end'])
177       array_push($fields, "TIME_FORMAT(sec_to_time(time_to_sec(l.start) + time_to_sec(l.duration)), '%k:%i') as finish");
178     // Add duration.
179     if ($options['show_duration'])
180       array_push($fields, "TIME_FORMAT(l.duration, '%k:%i') as duration");
181     // Add work units.
182     if ($options['show_work_units']) {
183       if ($user->unit_totals_only)
184         array_push($fields, "null as units");
185       else
186         array_push($fields, "if(l.billable = 0 or time_to_sec(l.duration)/60 < $user->first_unit_threshold, 0, ceil(time_to_sec(l.duration)/60/$user->minutes_in_unit)) as units");
187     }
188     // Add note.
189     if ($options['show_note'])
190       array_push($fields, 'l.comment as note');
191     // Handle cost.
192     $includeCost = $options['show_cost'];
193     if ($includeCost) {
194       if (MODE_TIME == $user->tracking_mode)
195         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.
196       else
197         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.
198       array_push($fields, "null as expense"); 
199     }
200     // Add paid status.
201     if ($canViewReports && $options['show_paid'])
202       array_push($fields, 'l.paid as paid');
203     // Add IP address.
204     if ($canViewReports && $options['show_ip']) {
205       array_push($fields, 'l.created as created');
206       array_push($fields, 'l.created_ip as created_ip');
207       array_push($fields, 'l.modified as modified');
208       array_push($fields, 'l.modified_ip as modified_ip');
209     }
210     // Add invoice name if it is selected.
211     if (($canViewReports || $isClient) && $options['show_invoice'])
212       array_push($fields, 'i.name as invoice');
213
214     // Prepare sql query part for left joins.
215     $left_joins = null;
216     if ($options['show_client'] || $grouping_by_client)
217       $left_joins .= " left join tt_clients c on (c.id = l.client_id)";
218     if (($canViewReports || $isClient) && $options['show_invoice'])
219       $left_joins .= " left join tt_invoices i on (i.id = l.invoice_id and i.status = 1)";
220     if ($canViewReports || $isClient || $user->isPluginEnabled('ex'))
221        $left_joins .= " left join tt_users u on (u.id = l.user_id)";
222     if ($options['show_project'] || $grouping_by_project)
223       $left_joins .= " left join tt_projects p on (p.id = l.project_id)";
224     if ($options['show_task'] || $grouping_by_task)
225       $left_joins .= " left join tt_tasks t on (t.id = l.task_id)";
226     if ($include_cf_1) {
227       if ($cf_1_type == CustomFields::TYPE_TEXT)
228         $left_joins .= " left join tt_custom_field_log cfl on (l.id = cfl.log_id and cfl.status = 1)";
229       elseif ($cf_1_type == CustomFields::TYPE_DROPDOWN) {
230         $left_joins .=  " left join tt_custom_field_log cfl on (l.id = cfl.log_id and cfl.status = 1)".
231           " left join tt_custom_field_options cfo on (cfl.option_id = cfo.id)";
232       }
233     }
234     if ($includeCost && MODE_TIME != $user->tracking_mode)
235       $left_joins .= " left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id)";
236
237     $where = ttReportHelper::getWhere($options);
238
239     // Construct sql query for tt_log items.
240     $sql = "select ".join(', ', $fields)." from tt_log l $left_joins $where";
241     // If we don't have expense items (such as when the Expenses plugin is disabled), the above is all sql we need,
242     // with an exception of sorting part, that is added in the end.
243
244     // However, when we have expenses, we need to do a union with a separate query for expense items from tt_expense_items table.
245     if ($options['show_cost'] && $user->isPluginEnabled('ex')) { // if ex(penses) plugin is enabled
246
247       $fields = array(); // An array of fields for database query.
248       array_push($fields, 'ei.id');
249       array_push($fields, '2 as type'); // Type 2 is for tt_expense_items entries.
250       array_push($fields, 'ei.date');
251       if($canViewReports || $isClient)
252         array_push($fields, 'u.name as user');
253       // Add client name if it is selected.
254       if ($options['show_client'] || $grouping_by_client)
255         array_push($fields, 'c.name as client');
256       // Add project name if it is selected.
257       if ($options['show_project'] || $grouping_by_project)
258         array_push($fields, 'p.name as project');
259       if ($options['show_task'] || $grouping_by_task)
260         array_push($fields, 'null'); // null for task name. We need to match column count for union.
261       if ($options['show_custom_field_1'] || $grouping_by_cf_1)
262         array_push($fields, 'null'); // null for cf_1.
263       if ($options['show_start']) {
264         array_push($fields, 'null'); // null for unformatted_start.
265         array_push($fields, 'null'); // null for start.
266       }
267       if ($options['show_end'])
268         array_push($fields, 'null'); // null for finish.
269       if ($options['show_duration'])
270         array_push($fields, 'null'); // null for duration.
271       if ($options['show_work_units'])
272         array_push($fields, 'null as units'); // null for work units.
273       // Use the note field to print item name.
274       if ($options['show_note'])
275         array_push($fields, 'ei.name as note');
276       array_push($fields, 'ei.cost as cost');
277       array_push($fields, 'ei.cost as expense');
278       // Add paid status.
279       if ($canViewReports && $options['show_paid'])
280         array_push($fields, 'ei.paid as paid');
281       // Add IP address.
282       if ($canViewReports && $options['show_ip']) {
283         array_push($fields, 'ei.created as created');
284         array_push($fields, 'ei.created_ip as created_ip');
285         array_push($fields, 'ei.modified as modified');
286         array_push($fields, 'ei.modified_ip as modified_ip');
287       }
288       // Add invoice name if it is selected.
289       if (($canViewReports || $isClient) && $options['show_invoice'])
290         array_push($fields, 'i.name as invoice');
291
292       // Prepare sql query part for left joins.
293       $left_joins = null;
294       if ($canViewReports || $isClient)
295         $left_joins .= " left join tt_users u on (u.id = ei.user_id)";
296       if ($options['show_client'] || $grouping_by_client)
297         $left_joins .= " left join tt_clients c on (c.id = ei.client_id)";
298       if ($options['show_project'] || $grouping_by_project)
299         $left_joins .= " left join tt_projects p on (p.id = ei.project_id)";
300       if (($canViewReports || $isClient) && $options['show_invoice'])
301         $left_joins .= " left join tt_invoices i on (i.id = ei.invoice_id and i.status = 1)";
302
303       $where = ttReportHelper::getExpenseWhere($options);
304
305       // Construct sql query for expense items.
306       $sql_for_expense_items = "select ".join(', ', $fields)." from tt_expense_items ei $left_joins $where";
307
308       // Construct a union.
309       $sql = "($sql) union all ($sql_for_expense_items)";
310     }
311
312     // Determine sort part.
313     $sort_part = ' order by ';
314     if ($no_grouping)
315       $sort_part .= 'date';
316     else {
317       $sort_part2 .= ($options['group_by1'] != null && $options['group_by1'] != 'no_grouping') ? ', '.$options['group_by1'] : '';
318       $sort_part2 .= ($options['group_by2'] != null && $options['group_by2'] != 'no_grouping') ? ', '.$options['group_by2'] : '';
319       $sort_part2 .= ($options['group_by3'] != null && $options['group_by3'] != 'no_grouping') ? ', '.$options['group_by3'] : '';
320       if (!$grouping_by_date) $sort_part2 .= ', date';
321       $sort_part .= ltrim($sort_part2, ', '); // Remove leading comma and space.
322     }
323     if (($canViewReports || $isClient) && $options['users'] && !$grouping_by_user)
324       $sort_part .= ', user, type';
325     if ($options['show_start'])
326       $sort_part .= ', unformatted_start';
327     $sort_part .= ', id';
328
329     $sql .= $sort_part;
330     // By now we are ready with sql.
331
332     // Obtain items for report.
333     $res = $mdb2->query($sql);
334     if (is_a($res, 'PEAR_Error')) die($res->getMessage());
335
336     while ($val = $res->fetchRow()) {
337       if ($convertTo12Hour) {
338         if($val['start'] != '')
339           $val['start'] = ttTimeHelper::to12HourFormat($val['start']);
340         if($val['finish'] != '')
341           $val['finish'] = ttTimeHelper::to12HourFormat($val['finish']);
342       }
343       if (isset($val['cost'])) {
344         if ('.' != $user->decimal_mark)
345           $val['cost'] = str_replace('.', $user->decimal_mark, $val['cost']);
346       }
347       if (isset($val['expense'])) {
348         if ('.' != $user->decimal_mark)
349           $val['expense'] = str_replace('.', $user->decimal_mark, $val['expense']);
350       }
351 // CODING STOPPED RIGHT HERE replace with a combined key...
352       if ('no_grouping' != $group_by_option) {
353         $val['grouped_by'] = $val[$group_by_option];
354         if ('date' == $group_by_option) {
355           // This is needed to get the date in user date format.
356           //$o_date = new DateAndTime(DB_DATEFORMAT, $val['grouped_by']);
357           //$val['grouped_by'] = $o_date->toString($user->date_format);
358           //unset($o_date);
359
360           $val['grouped_by'] = ttDateToUserFormat($val['grouped_by']);
361         }
362       }
363
364       // This is needed to get the date in user date format.
365       $o_date = new DateAndTime(DB_DATEFORMAT, $val['date']);
366       $val['date'] = $o_date->toString($user->date_format);
367       unset($o_date);
368
369       $row = $val;
370       $report_items[] = $row;
371     }
372
373     return $report_items;
374   }
375
376   // putInSession stores tt_log and tt_expense_items ids from a report in user session
377   // as 2 comma-separated lists.
378   static function putInSession($report_items) {
379     unset($_SESSION['report_item_ids']);
380     unset($_SESSION['report_item_expense_ids']);
381
382     // Iterate through records and build 2 comma-separated lists.
383     foreach($report_items as $item) {
384       if ($item['type'] == 1)
385         $report_item_ids .= ','.$item['id'];
386       else if ($item['type'] == 2)
387          $report_item_expense_ids .= ','.$item['id'];
388     }
389     $report_item_ids = trim($report_item_ids, ',');
390     $report_item_expense_ids = trim($report_item_expense_ids, ',');
391
392     // The lists are reqdy. Put them in session.
393     if ($report_item_ids) $_SESSION['report_item_ids'] = $report_item_ids;
394     if ($report_item_expense_ids) $_SESSION['report_item_expense_ids'] = $report_item_expense_ids;
395   }
396
397   // getFromSession obtains tt_log and tt_expense_items ids stored in user session.
398   static function getFromSession() {
399     $items = array();
400     $report_item_ids = $_SESSION['report_item_ids'];
401     if ($report_item_ids)
402       $items['report_item_ids'] = explode(',', $report_item_ids);
403     $report_item_expense_ids = $_SESSION['report_item_expense_ids'];
404     if ($report_item_expense_ids)
405       $items['report_item_expense_ids'] = explode(',', $report_item_expense_ids);
406     return $items;
407   }
408
409   // getSubtotals calculates report items subtotals when a report is grouped by.
410   // Without expenses, it's a simple select with group by.
411   // With expenses, it becomes a select with group by from a combined set of records obtained with "union all".
412   static function getSubtotals($options) {
413     global $user;
414
415     $group_by_option = $options['group_by1'];
416     if ('no_grouping' == $group_by_option) return null;
417
418     $mdb2 = getConnection();
419
420     // Start with sql to obtain subtotals for time items. This simple sql will be used when we have no expenses.
421
422     // Determine group by field and a required join.
423     switch ($group_by_option) {
424       case 'date':
425         $group_field = 'l.date';
426         $group_join = '';
427         break;
428       case 'user':
429         $group_field = 'u.name';
430         $group_join = 'left join tt_users u on (l.user_id = u.id) ';
431         break;
432       case 'client':
433         $group_field = 'c.name';
434         $group_join = 'left join tt_clients c on (l.client_id = c.id) ';
435         break;
436       case 'project':
437         $group_field = 'p.name';
438         $group_join = 'left join tt_projects p on (l.project_id = p.id) ';
439         break;
440       case 'task':
441         $group_field = 't.name';
442         $group_join = 'left join tt_tasks t on (l.task_id = t.id) ';
443         break;
444       case 'cf_1':
445         $group_field = 'cfo.value';
446         $custom_fields = new CustomFields($user->group_id);
447         if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_TEXT)
448           $group_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) ';
449         elseif ($custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN)
450           $group_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) ';
451         break;
452     }
453
454     $where = ttReportHelper::getWhere($options);
455     if ($options['show_cost']) {
456       if (MODE_TIME == $user->tracking_mode) {
457         if ($group_by_option != 'user')
458           $left_join = 'left join tt_users u on (l.user_id = u.id)';
459         $sql = "select $group_field as group_field, sum(time_to_sec(l.duration)) as time";
460         if ($options['show_work_units']) {
461           if ($user->unit_totals_only)
462             $sql .= ", if (sum(l.billable * time_to_sec(l.duration)/60) < $user->first_unit_threshold, 0, ceil(sum(l.billable * time_to_sec(l.duration)/60/$user->minutes_in_unit))) as units";
463           else
464             $sql .= ", sum(if(l.billable = 0 or time_to_sec(l.duration)/60 < $user->first_unit_threshold, 0, ceil(time_to_sec(l.duration)/60/$user->minutes_in_unit))) as units";
465         }
466         $sql .= ", sum(cast(l.billable * coalesce(u.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10, 2))) as cost,
467           null as expenses from tt_log l
468           $group_join $left_join $where group by $group_field";
469       } else {
470         // If we are including cost and tracking projects, our query (the same as above) needs to join the tt_user_project_binds table.
471         $sql = "select $group_field as group_field, sum(time_to_sec(l.duration)) as time";
472         if ($options['show_work_units']) {
473           if ($user->unit_totals_only)
474             $sql .= ", if (sum(l.billable * time_to_sec(l.duration)/60) < $user->first_unit_threshold, 0, ceil(sum(l.billable * time_to_sec(l.duration)/60/$user->minutes_in_unit))) as units";
475           else
476             $sql .= ", sum(if(l.billable = 0 or time_to_sec(l.duration)/60 < $user->first_unit_threshold, 0, ceil(time_to_sec(l.duration)/60/$user->minutes_in_unit))) as units";
477         }
478         $sql .= ", sum(cast(l.billable * coalesce(upb.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10,2))) as cost,
479           null as expenses from tt_log l 
480           $group_join
481           left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id) $where group by $group_field";
482       }
483     } else {
484       $sql = "select $group_field as group_field, sum(time_to_sec(l.duration)) as time";
485       if ($options['show_work_units']) {
486         if ($user->unit_totals_only)
487           $sql .= ", if (sum(l.billable * time_to_sec(l.duration)/60) < $user->first_unit_threshold, 0, ceil(sum(l.billable * time_to_sec(l.duration)/60/$user->minutes_in_unit))) as units";
488         else
489           $sql .= ", sum(if(l.billable = 0 or time_to_sec(l.duration)/60 < $user->first_unit_threshold, 0, ceil(time_to_sec(l.duration)/60/$user->minutes_in_unit))) as units";
490       }
491       $sql .= ", null as expenses from tt_log l 
492         $group_join $where group by $group_field";
493     }
494     // By now we have sql for time items.
495
496     // However, when we have expenses, we need to do a union with a separate query for expense items from tt_expense_items table.
497     if ($options['show_cost'] && $user->isPluginEnabled('ex')) { // if ex(penses) plugin is enabled
498
499       // Determine group by field and a required join.
500       $group_join = null;
501       $group_field = 'null';
502       switch ($group_by_option) {
503         case 'date':
504           $group_field = 'ei.date';
505           $group_join = '';
506           break;
507         case 'user':
508           $group_field = 'u.name';
509           $group_join = 'left join tt_users u on (ei.user_id = u.id) ';
510           break;
511         case 'client':
512           $group_field = 'c.name';
513           $group_join = 'left join tt_clients c on (ei.client_id = c.id) ';
514           break;
515         case 'project':
516           $group_field = 'p.name';
517           $group_join = 'left join tt_projects p on (ei.project_id = p.id) ';
518           break;
519       }
520
521       $where = ttReportHelper::getExpenseWhere($options);
522       $sql_for_expenses = "select $group_field as group_field, null as time";
523       if ($options['show_work_units']) $sql_for_expenses .= ", null as units";
524       $sql_for_expenses .= ", sum(ei.cost) as cost, sum(ei.cost) as expenses from tt_expense_items ei $group_join $where";
525       // Add a "group by" clause if we are grouping.
526       if ('null' != $group_field) $sql_for_expenses .= " group by $group_field";
527
528       // Create a combined query.
529       $combined = "select group_field, sum(time) as time";
530       if ($options['show_work_units']) $combined .= ", sum(units) as units";
531       $combined .= ", sum(cost) as cost, sum(expenses) as expenses from (($sql) union all ($sql_for_expenses)) t group by group_field";
532       $sql = $combined;
533     }
534
535     // Execute query.
536     $res = $mdb2->query($sql);
537     if (is_a($res, 'PEAR_Error')) die($res->getMessage());
538
539     while ($val = $res->fetchRow()) {
540       if ('date' == $group_by_option) {
541         // This is needed to get the date in user date format.
542         $o_date = new DateAndTime(DB_DATEFORMAT, $val['group_field']);
543         $val['group_field'] = $o_date->toString($user->date_format);
544         unset($o_date);
545       }
546       $time = $val['time'] ? sec_to_time_fmt_hm($val['time']) : null;
547       if ($options['show_cost']) {
548         if ('.' != $user->decimal_mark) {
549           $val['cost'] = str_replace('.', $user->decimal_mark, $val['cost']);
550           $val['expenses'] = str_replace('.', $user->decimal_mark, $val['expenses']);
551         }
552         $subtotals[$val['group_field']] = array('name'=>$val['group_field'],'time'=>$time, 'units'=> $val['units'], 'cost'=>$val['cost'],'expenses'=>$val['expenses']);
553       } else
554         $subtotals[$val['group_field']] = array('name'=>$val['group_field'],'time'=>$time, 'units'=> $val['units']);
555     }
556
557     return $subtotals;
558   }
559
560   // getTotals calculates total hours and cost for all report items.
561   static function getTotals($options)
562   {
563     global $user;
564
565     $mdb2 = getConnection();
566
567     $where = ttReportHelper::getWhere($options);
568
569     // Prepare parts.
570     $time_part = "sum(time_to_sec(l.duration)) as time";
571     if ($options['show_work_units']) {
572       $units_part = $user->unit_totals_only ? ", null as units" : ", sum(if(l.billable = 0 or time_to_sec(l.duration)/60 < $user->first_unit_threshold, 0, ceil(time_to_sec(l.duration)/60/$user->minutes_in_unit))) as units";
573     }
574     if ($options['show_cost']) {
575       if (MODE_TIME == $user->tracking_mode)
576         $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";
577       else
578         $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";
579     } else {
580       $cost_part = ", null as cost, null as expenses";
581     }
582     if ($options['show_cost']) {
583       if (MODE_TIME == $user->tracking_mode) {
584         $left_joins = "left join tt_users u on (l.user_id = u.id)";
585       } else {
586         $left_joins = "left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id)";
587       }
588     }
589     // Prepare a query for time items.
590     $sql = "select $time_part $units_part $cost_part from tt_log l $left_joins $where";
591
592     // If we have expenses, query becomes a bit more complex.
593     if ($options['show_cost'] && $user->isPluginEnabled('ex')) {
594       $where = ttReportHelper::getExpenseWhere($options);
595       $sql_for_expenses = "select null as time";
596       if ($options['show_work_units']) $sql_for_expenses .= ", null as units";
597       $sql_for_expenses .= ", sum(cost) as cost, sum(cost) as expenses from tt_expense_items ei $where";
598
599       // Create a combined query.
600       $combined = "select sum(time) as time";
601       if ($options['show_work_units']) $combined .= ", sum(units) as units";
602       $combined .= ", sum(cost) as cost, sum(expenses) as expenses from (($sql) union all ($sql_for_expenses)) t";
603       $sql = $combined;
604     }
605
606     // Execute query.
607     $res = $mdb2->query($sql);
608     if (is_a($res, 'PEAR_Error')) die($res->getMessage());
609
610     $val = $res->fetchRow();
611     $total_time = $val['time'] ? sec_to_time_fmt_hm($val['time']) : null;
612     if ($options['show_cost']) {
613       $total_cost = $val['cost'];
614       if (!$total_cost) $total_cost = '0.00';
615       if ('.' != $user->decimal_mark)
616         $total_cost = str_replace('.', $user->decimal_mark, $total_cost);
617       $total_expenses = $val['expenses'];
618       if (!$total_expenses) $total_expenses = '0.00';
619       if ('.' != $user->decimal_mark)
620         $total_expenses = str_replace('.', $user->decimal_mark, $total_expenses);
621     }
622
623     if ($options['period'])
624       $period = new Period($options['period'], new DateAndTime($user->date_format));
625     else {
626       $period = new Period();
627       $period->setPeriod(
628         new DateAndTime($user->date_format, $options['period_start']),
629         new DateAndTime($user->date_format, $options['period_end']));
630     }
631
632     $totals['start_date'] = $period->getStartDate();
633     $totals['end_date'] = $period->getEndDate();
634     $totals['time'] = $total_time;
635     $totals['units'] = $val['units'];
636     $totals['cost'] = $total_cost;
637     $totals['expenses'] = $total_expenses;
638
639     return $totals;
640   }
641
642   // The assignToInvoice assigns a set of records to a specific invoice.
643   static function assignToInvoice($invoice_id, $time_log_ids, $expense_item_ids)
644   {
645     $mdb2 = getConnection();
646     if ($time_log_ids) {
647       $sql = "update tt_log set invoice_id = ".$mdb2->quote($invoice_id).
648         " where id in(".join(', ', $time_log_ids).")";
649       $affected = $mdb2->exec($sql);
650       if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
651     }
652     if ($expense_item_ids) {
653       $sql = "update tt_expense_items set invoice_id = ".$mdb2->quote($invoice_id).
654         " where id in(".join(', ', $expense_item_ids).")";
655       $affected = $mdb2->exec($sql);
656       if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
657     }
658   }
659
660   // The markPaid marks a set of records as either paid or unpaid.
661   static function markPaid($time_log_ids, $expense_item_ids, $paid = true)
662   {
663     $mdb2 = getConnection();
664     $paid_val = (int) $paid;
665     if ($time_log_ids) {
666       $sql = "update tt_log set paid = $paid_val where id in(".join(', ', $time_log_ids).")";
667       $affected = $mdb2->exec($sql);
668       if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
669     }
670     if ($expense_item_ids) {
671       $sql = "update tt_expense_items set paid = $paid_val where id in(".join(', ', $expense_item_ids).")";
672       $affected = $mdb2->exec($sql);
673       if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
674     }
675   }
676
677   // prepareReportBody - prepares an email body for report.
678   static function prepareReportBody($options, $comment = null)
679   {
680     global $user;
681     global $i18n;
682
683     // Determine these once as they are used in multiple places in this function.
684     $canViewReports = $user->can('view_reports') || $user->can('view_all_reports');
685     $isClient = $user->isClient();
686
687     $items = ttReportHelper::getItems($options);
688     $group_by = $options['group_by1'];
689     if ($group_by && 'no_grouping' != $group_by)
690       $subtotals = ttReportHelper::getSubtotals($options);
691     $totals = ttReportHelper::getTotals($options);
692
693     // Use custom fields plugin if it is enabled.
694     if ($user->isPluginEnabled('cf'))
695       $custom_fields = new CustomFields($user->group_id);
696
697     // Define some styles to use in email.
698     $style_title = 'text-align: center; font-size: 15pt; font-family: Arial, Helvetica, sans-serif;';
699     $tableHeader = 'font-weight: bold; background-color: #a6ccf7; text-align: left;';
700     $tableHeaderCentered = 'font-weight: bold; background-color: #a6ccf7; text-align: center;';
701     $rowItem = 'background-color: #ffffff;';
702     $rowItemAlt = 'background-color: #f5f5f5;';
703     $rowSubtotal = 'background-color: #e0e0e0;';
704     $cellLeftAligned = 'text-align: left; vertical-align: top;';
705     $cellRightAligned = 'text-align: right; vertical-align: top;';
706     $cellLeftAlignedSubtotal = 'font-weight: bold; text-align: left; vertical-align: top;';
707     $cellRightAlignedSubtotal = 'font-weight: bold; text-align: right; vertical-align: top;';
708
709     // Start creating email body.
710     $body = '<html>';
711     $body .= '<head><meta http-equiv="content-type" content="text/html; charset='.CHARSET.'"></head>';
712     $body .= '<body>';
713
714     // Output title.
715     $body .= '<p style="'.$style_title.'">'.$i18n->get('form.mail.report_subject').': '.$totals['start_date'].' - '.$totals['end_date'].'</p>';
716
717     // Output comment.
718     if ($comment) $body .= '<p>'.htmlspecialchars($comment).'</p>';
719
720     if ($options['show_totals_only']) {
721       // Totals only report. Output subtotals.
722
723       // Determine group_by header.
724       if ('cf_1' == $group_by)
725         $group_by_header = htmlspecialchars($custom_fields->fields[0]['label']);
726       else {
727         $key = 'label.'.$group_by;
728         $group_by_header = $i18n->get($key);
729       }
730
731       $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
732       $body .= '<tr>';
733       $body .= '<td style="'.$tableHeader.'">'.$group_by_header.'</td>';
734       if ($options['show_duration'])
735         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.duration').'</td>';
736       if ($options['show_work_units'])
737         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.work_units_short').'</td>';
738       if ($options['show_cost'])
739         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.cost').'</td>';
740       $body .= '</tr>';
741       foreach($subtotals as $subtotal) {
742         $body .= '<tr style="'.$rowSubtotal.'">';
743         $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($subtotal['name'] ? htmlspecialchars($subtotal['name']) : '&nbsp;').'</td>';
744         if ($options['show_duration']) {
745           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
746           if ($subtotal['time'] <> '0:00') $body .= $subtotal['time'];
747           $body .= '</td>';
748         }
749         if ($options['show_work_units']) {
750           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
751           $body .= $subtotal['units'];
752           $body .= '</td>';
753         }
754         if ($options['show_cost']) {
755           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
756           $body .= ($canViewReports || $isClient) ? $subtotal['cost'] : $subtotal['expenses'];
757           $body .= '</td>';
758         }
759         $body .= '</tr>';
760       }
761
762       // Print totals.
763       $body .= '<tr><td>&nbsp;</td></tr>';
764       $body .= '<tr style="'.$rowSubtotal.'">';
765       $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.total').'</td>';
766       if ($options['show_duration']) {
767         $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
768         if ($totals['time'] <> '0:00') $body .= $totals['time'];
769         $body .= '</td>';
770       }
771       if ($options['show_work_units']) {
772         $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
773         $body .= $totals['units'];
774         $body .= '</td>';
775       }
776       if ($options['show_cost']) {
777         $body .= '<td nowrap style="'.$cellRightAlignedSubtotal.'">'.htmlspecialchars($user->currency).' ';
778         $body .= ($canViewReports || $isClient) ? $totals['cost'] : $totals['expenses'];
779         $body .= '</td>';
780       }
781       $body .= '</tr>';
782
783       $body .= '</table>';
784     } else {
785       // Regular report.
786
787       // Print table header.
788       $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
789       $body .= '<tr>';
790       $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.date').'</td>';
791       if ($canViewReports || $isClient)
792         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.user').'</td>';
793       if ($options['show_client'])
794         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.client').'</td>';
795       if ($options['show_project'])
796         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.project').'</td>';
797       if ($options['show_task'])
798         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.task').'</td>';
799       if ($options['show_custom_field_1'])
800         $body .= '<td style="'.$tableHeader.'">'.htmlspecialchars($custom_fields->fields[0]['label']).'</td>';
801       if ($options['show_start'])
802         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.start').'</td>';
803       if ($options['show_end'])
804         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.finish').'</td>';
805       if ($options['show_duration'])
806         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.duration').'</td>';
807       if ($options['show_work_units'])
808         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.work_units_short').'</td>';
809       if ($options['show_note'])
810         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.note').'</td>';
811       if ($options['show_cost'])
812         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.cost').'</td>';
813       if ($options['show_paid'])
814         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.paid').'</td>';
815       if ($options['show_ip'])
816         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.ip').'</td>';
817       if ($options['show_invoice'])
818         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.invoice').'</td>';
819       $body .= '</tr>';
820
821       // Initialize variables to print subtotals.
822       if ($items && 'no_grouping' != $group_by) {
823         $print_subtotals = true;
824         $first_pass = true;
825         $prev_grouped_by = '';
826         $cur_grouped_by = '';
827       }
828       // Initialize variables to alternate color of rows for different dates.
829       $prev_date = '';
830       $cur_date = '';
831       $row_style = $rowItem;
832
833       // Print report items.
834       if (is_array($items)) {
835         foreach ($items as $record) {
836           $cur_date = $record['date'];
837           // Print a subtotal row after a block of grouped items.
838           if ($print_subtotals) {
839             $cur_grouped_by = $record['grouped_by'];
840             if ($cur_grouped_by != $prev_grouped_by && !$first_pass) {
841               $body .= '<tr style="'.$rowSubtotal.'">';
842               $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.subtotal').'</td>';
843               $subtotal_name = htmlspecialchars($subtotals[$prev_grouped_by]['name']);
844               if ($canViewReports || $isClient) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'user' ? $subtotal_name : '').'</td>';
845               if ($options['show_client']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'client' ? $subtotal_name : '').'</td>';
846               if ($options['show_project']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'project' ? $subtotal_name : '').'</td>';
847               if ($options['show_task']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'task' ? $subtotal_name : '').'</td>';
848               if ($options['show_custom_field_1']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'cf_1' ? $subtotal_name : '').'</td>';
849               if ($options['show_start']) $body .= '<td></td>';
850               if ($options['show_end']) $body .= '<td></td>';
851               if ($options['show_duration']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['time'].'</td>';
852               if ($options['show_work_units']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['units'].'</td>';
853               if ($options['show_note']) $body .= '<td></td>';
854               if ($options['show_cost']) {
855                 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
856                 $body .= ($canViewReports || $isClient) ? $subtotals[$prev_grouped_by]['cost'] : $subtotals[$prev_grouped_by]['expenses'];
857                 $body .= '</td>';
858               }
859               if ($options['show_paid']) $body .= '<td></td>';
860               if ($options['show_ip']) $body .= '<td></td>';
861               if ($options['show_invoice']) $body .= '<td></td>';
862               $body .= '</tr>';
863               $body .= '<tr><td>&nbsp;</td></tr>';
864             }
865             $first_pass = false;
866           }
867
868           // Print a regular row.
869           if ($cur_date != $prev_date)
870             $row_style = ($row_style == $rowItem) ? $rowItemAlt : $rowItem;
871           $body .= '<tr style="'.$row_style.'">';
872           $body .= '<td style="'.$cellLeftAligned.'">'.$record['date'].'</td>';
873           if ($canViewReports || $isClient)
874             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['user']).'</td>';
875           if ($options['show_client'])
876             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['client']).'</td>';
877           if ($options['show_project'])
878             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['project']).'</td>';
879           if ($options['show_task'])
880             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['task']).'</td>';
881           if ($options['show_custom_field_1'])
882             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['cf_1']).'</td>';
883           if ($options['show_start'])
884             $body .= '<td nowrap style="'.$cellRightAligned.'">'.$record['start'].'</td>';
885           if ($options['show_end'])
886             $body .= '<td nowrap style="'.$cellRightAligned.'">'.$record['finish'].'</td>';
887           if ($options['show_duration'])
888             $body .= '<td style="'.$cellRightAligned.'">'.$record['duration'].'</td>';
889           if ($options['show_work_units'])
890             $body .= '<td style="'.$cellRightAligned.'">'.$record['units'].'</td>';
891           if ($options['show_note'])
892             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['note']).'</td>';
893           if ($options['show_cost'])
894             $body .= '<td style="'.$cellRightAligned.'">'.$record['cost'].'</td>';
895           if ($options['show_paid']) {
896             $body .= '<td style="'.$cellRightAligned.'">';
897             $body .= $record['paid'] == 1 ? $i18n->get('label.yes') : $i18n->get('label.no');
898             $body .= '</td>';
899           }
900           if ($options['show_ip']) {
901             $body .= '<td style="'.$cellRightAligned.'">';
902             $body .= $record['modified'] ? $record['modified_ip'].' '.$record['modified'] : $record['created_ip'].' '.$record['created'];
903             $body .= '</td>';
904           }
905           if ($options['show_invoice'])
906             $body .= '<td style="'.$cellRightAligned.'">'.htmlspecialchars($record['invoice']).'</td>';
907           $body .= '</tr>';
908
909           $prev_date = $record['date'];
910           if ($print_subtotals)
911             $prev_grouped_by = $record['grouped_by'];
912         }
913       }
914
915       // Print a terminating subtotal.
916       if ($print_subtotals) {
917         $body .= '<tr style="'.$rowSubtotal.'">';
918         $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.subtotal').'</td>';
919         $subtotal_name = htmlspecialchars($subtotals[$cur_grouped_by]['name']);
920         if ($canViewReports || $isClient) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'user' ? $subtotal_name : '').'</td>';
921         if ($options['show_client']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'client' ? $subtotal_name : '').'</td>';
922         if ($options['show_project']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'project' ? $subtotal_name : '').'</td>';
923         if ($options['show_task']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'task' ? $subtotal_name : '').'</td>';
924         if ($options['show_custom_field_1']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'cf_1' ? $subtotal_name : '').'</td>';
925         if ($options['show_start']) $body .= '<td></td>';
926         if ($options['show_end']) $body .= '<td></td>';
927         if ($options['show_duration']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$cur_grouped_by]['time'].'</td>';
928         if ($options['show_work_units']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$cur_grouped_by]['units'].'</td>';
929         if ($options['show_note']) $body .= '<td></td>';
930         if ($options['show_cost']) {
931           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
932           $body .= ($canViewReports || $isClient) ? $subtotals[$cur_grouped_by]['cost'] : $subtotals[$cur_grouped_by]['expenses'];
933           $body .= '</td>';
934         }
935         if ($options['show_paid']) $body .= '<td></td>';
936         if ($options['show_ip']) $body .= '<td></td>';
937         if ($options['show_invoice']) $body .= '<td></td>';
938         $body .= '</tr>';
939       }
940
941       // Print totals.
942       $body .= '<tr><td>&nbsp;</td></tr>';
943       $body .= '<tr style="'.$rowSubtotal.'">';
944       $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.total').'</td>';
945       if ($canViewReports || $isClient) $body .= '<td></td>';
946       if ($options['show_client']) $body .= '<td></td>';
947       if ($options['show_project']) $body .= '<td></td>';
948       if ($options['show_task']) $body .= '<td></td>';
949       if ($options['show_custom_field_1']) $body .= '<td></td>';
950       if ($options['show_start']) $body .= '<td></td>';
951       if ($options['show_end']) $body .= '<td></td>';
952       if ($options['show_duration']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$totals['time'].'</td>';
953       if ($options['show_work_units']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$totals['units'].'</td>';
954       if ($options['show_note']) $body .= '<td></td>';
955       if ($options['show_cost']) {
956         $body .= '<td nowrap style="'.$cellRightAlignedSubtotal.'">'.htmlspecialchars($user->currency).' ';
957         $body .= ($canViewReports || $isClient) ? $totals['cost'] : $totals['expenses'];
958         $body .= '</td>';
959       }
960       if ($options['show_paid']) $body .= '<td></td>';
961       if ($options['show_ip']) $body .= '<td></td>';
962       if ($options['show_invoice']) $body .= '<td></td>';
963       $body .= '</tr>';
964
965       $body .= '</table>';
966     }
967
968     // Output footer.
969     if (!defined('REPORT_FOOTER') || !(REPORT_FOOTER == false))
970       $body .= '<p style="text-align: center;">'.$i18n->get('form.mail.footer').'</p>';
971
972     // Finish creating email body.
973     $body .= '</body></html>';
974
975     return $body;
976   }
977
978   // checkFavReportCondition - checks whether it is okay to send fav report.
979   static function checkFavReportCondition($options, $condition)
980   {
981     $items = ttReportHelper::getItems($options);
982
983     $condition = trim(str_replace('count', '', $condition));
984
985     $greater_or_equal = ttStartsWith($condition, '>=');
986     if ($greater_or_equal) $condition = trim(str_replace('>=', '', $condition));
987
988     $less_or_equal = ttStartsWith($condition, '<=');
989     if ($less_or_equal) $condition = trim(str_replace('<=', '', $condition));
990
991     $not_equal = ttStartsWith($condition, '<>');
992     if ($not_equal) $condition = trim(str_replace('<>', '', $condition));
993
994     $greater = ttStartsWith($condition, '>');
995     if ($greater) $condition = trim(str_replace('>', '', $condition));
996
997     $less = ttStartsWith($condition, '<');
998     if ($less) $condition = trim(str_replace('<', '', $condition));
999
1000     $equal = ttStartsWith($condition, '=');
1001     if ($equal) $condition = trim(str_replace('=', '', $condition));
1002
1003     $count_required = (int) $condition;
1004
1005     if ($greater && count($items) > $count_required) return true;
1006     if ($greater_or_equal && count($items) >= $count_required) return true;
1007     if ($less && count($items) < $count_required) return true;
1008     if ($less_or_equal && count($items) <= $count_required) return true;
1009     if ($equal && count($items) == $count_required) return true;
1010     if ($not_equal && count($items) <> $count_required) return true;
1011
1012     return false;
1013   }
1014
1015   // sendFavReport - sends a favorite report to a specified email, called from cron.php
1016   static function sendFavReport($options, $subject, $email, $cc) {
1017     // We are called from cron.php, we have no $bean in session.
1018     // cron.php sets global $user and $i18n objects to match our favorite report user.
1019     global $user;
1020     global $i18n;
1021
1022     // Prepare report body.
1023     $body = ttReportHelper::prepareReportBody($options);
1024
1025     import('mail.Mailer');
1026     $mailer = new Mailer();
1027     $mailer->setCharSet(CHARSET);
1028     $mailer->setContentType('text/html');
1029     $mailer->setSender(SENDER);
1030     if (!empty($cc))
1031       $mailer->setReceiverCC($cc);
1032     if (!empty($user->bcc_email))
1033       $mailer->setReceiverBCC($user->bcc_email);
1034     $mailer->setReceiver($email);
1035     $mailer->setMailMode(MAIL_MODE);
1036     if (empty($subject)) $subject = $options['name'];
1037     if (!$mailer->send($subject, $body))
1038       return false;
1039
1040     return true;
1041   }
1042
1043   // getReportOptions - returns an array of report options constructed from session bean.
1044   //
1045   // Note: similarly to ttFavReportHelper::getReportOptions, this function is a part of
1046   // refactoring to simplify maintenance of report generating functions, as we currently
1047   // have 2 sets: normal reporting (from bean), and fav report emailing (from db fields).
1048   // Using options obtained from either db or bean shall allow us to use only one set of functions.
1049   static function getReportOptions($bean) {
1050     global $user;
1051
1052     // Prepare an array of report options.
1053     $options = array();
1054
1055     // Construct one by one.
1056     $options['name'] = null; // No name required.
1057     $options['user_id'] = $user->id; // Not sure if we need user_id here. Fav reports use it to recycle $user object in cron.php.
1058     $options['client_id'] = $bean->getAttribute('client');
1059     $options['cf_1_option_id'] = $bean->getAttribute('option');
1060     $options['project_id'] = $bean->getAttribute('project');
1061     $options['task_id'] = $bean->getAttribute('task');
1062     $options['billable'] = $bean->getAttribute('include_records');
1063     $options['invoice'] = $bean->getAttribute('invoice');
1064     $options['paid_status'] = $bean->getAttribute('paid_status');
1065     if (is_array($bean->getAttribute('users'))) $options['users'] = join(',', $bean->getAttribute('users'));
1066     $options['period'] = $bean->getAttribute('period');
1067     $options['period_start'] = $bean->getAttribute('start_date');
1068     $options['period_end'] = $bean->getAttribute('end_date');
1069     $options['show_client'] = $bean->getAttribute('chclient');
1070     $options['show_invoice'] = $bean->getAttribute('chinvoice');
1071     $options['show_paid'] = $bean->getAttribute('chpaid');
1072     $options['show_ip'] = $bean->getAttribute('chip');
1073     $options['show_project'] = $bean->getAttribute('chproject');
1074     $options['show_start'] = $bean->getAttribute('chstart');
1075     $options['show_duration'] = $bean->getAttribute('chduration');
1076     $options['show_cost'] = $bean->getAttribute('chcost');
1077     $options['show_task'] = $bean->getAttribute('chtask');
1078     $options['show_end'] = $bean->getAttribute('chfinish');
1079     $options['show_note'] = $bean->getAttribute('chnote');
1080     $options['show_custom_field_1'] = $bean->getAttribute('chcf_1');
1081     $options['show_work_units'] = $bean->getAttribute('chunits');
1082     $options['show_totals_only'] = $bean->getAttribute('chtotalsonly');
1083     $options['group_by1'] = $bean->getAttribute('group_by1');
1084     $options['group_by2'] = $bean->getAttribute('group_by2');
1085     $options['group_by3'] = $bean->getAttribute('group_by3');
1086     return $options;
1087   }
1088
1089   // verifyBean is a security function to make sure data in bean makes sense for a group.
1090   static function verifyBean($bean) {
1091     global $user;
1092
1093     // Check users.
1094     $users_in_bean = $bean->getAttribute('users');
1095     if (is_array($users_in_bean)) {
1096       $users_in_group = ttTeamHelper::getUsers();
1097       foreach ($users_in_group as $user_in_group) {
1098         $valid_ids[] = $user_in_group['id'];
1099       }
1100       foreach ($users_in_bean as $user_in_bean) {
1101         if (!in_array($user_in_bean, $valid_ids)) {
1102           return false;
1103         }
1104       }
1105     }
1106
1107     // TODO: add additional checks here. Perhaps do it before saving the bean for consistency.
1108     return true;
1109   }
1110 }