A bit of refactoring.
[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           $val['grouped_by'] = ttDateToUserFormat($val['grouped_by']);
356         }
357       }
358
359       $val['date'] = ttDateToUserFormat($val['date']);
360
361       $row = $val;
362       $report_items[] = $row;
363     }
364
365     return $report_items;
366   }
367
368   // putInSession stores tt_log and tt_expense_items ids from a report in user session
369   // as 2 comma-separated lists.
370   static function putInSession($report_items) {
371     unset($_SESSION['report_item_ids']);
372     unset($_SESSION['report_item_expense_ids']);
373
374     // Iterate through records and build 2 comma-separated lists.
375     foreach($report_items as $item) {
376       if ($item['type'] == 1)
377         $report_item_ids .= ','.$item['id'];
378       else if ($item['type'] == 2)
379          $report_item_expense_ids .= ','.$item['id'];
380     }
381     $report_item_ids = trim($report_item_ids, ',');
382     $report_item_expense_ids = trim($report_item_expense_ids, ',');
383
384     // The lists are reqdy. Put them in session.
385     if ($report_item_ids) $_SESSION['report_item_ids'] = $report_item_ids;
386     if ($report_item_expense_ids) $_SESSION['report_item_expense_ids'] = $report_item_expense_ids;
387   }
388
389   // getFromSession obtains tt_log and tt_expense_items ids stored in user session.
390   static function getFromSession() {
391     $items = array();
392     $report_item_ids = $_SESSION['report_item_ids'];
393     if ($report_item_ids)
394       $items['report_item_ids'] = explode(',', $report_item_ids);
395     $report_item_expense_ids = $_SESSION['report_item_expense_ids'];
396     if ($report_item_expense_ids)
397       $items['report_item_expense_ids'] = explode(',', $report_item_expense_ids);
398     return $items;
399   }
400
401   // getSubtotals calculates report items subtotals when a report is grouped by.
402   // Without expenses, it's a simple select with group by.
403   // With expenses, it becomes a select with group by from a combined set of records obtained with "union all".
404   static function getSubtotals($options) {
405     global $user;
406
407     $group_by_option = $options['group_by1'];
408     if ('no_grouping' == $group_by_option) return null;
409
410     $mdb2 = getConnection();
411
412     // Start with sql to obtain subtotals for time items. This simple sql will be used when we have no expenses.
413
414     // Determine group by field and a required join.
415     switch ($group_by_option) {
416       case 'date':
417         $group_field = 'l.date';
418         $group_join = '';
419         break;
420       case 'user':
421         $group_field = 'u.name';
422         $group_join = 'left join tt_users u on (l.user_id = u.id) ';
423         break;
424       case 'client':
425         $group_field = 'c.name';
426         $group_join = 'left join tt_clients c on (l.client_id = c.id) ';
427         break;
428       case 'project':
429         $group_field = 'p.name';
430         $group_join = 'left join tt_projects p on (l.project_id = p.id) ';
431         break;
432       case 'task':
433         $group_field = 't.name';
434         $group_join = 'left join tt_tasks t on (l.task_id = t.id) ';
435         break;
436       case 'cf_1':
437         $group_field = 'cfo.value';
438         $custom_fields = new CustomFields($user->group_id);
439         if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_TEXT)
440           $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) ';
441         elseif ($custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN)
442           $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) ';
443         break;
444     }
445
446     $where = ttReportHelper::getWhere($options);
447     if ($options['show_cost']) {
448       if (MODE_TIME == $user->tracking_mode) {
449         if ($group_by_option != 'user')
450           $left_join = 'left join tt_users u on (l.user_id = u.id)';
451         $sql = "select $group_field as group_field, sum(time_to_sec(l.duration)) as time";
452         if ($options['show_work_units']) {
453           if ($user->unit_totals_only)
454             $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";
455           else
456             $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";
457         }
458         $sql .= ", sum(cast(l.billable * coalesce(u.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10, 2))) as cost,
459           null as expenses from tt_log l
460           $group_join $left_join $where group by $group_field";
461       } else {
462         // If we are including cost and tracking projects, our query (the same as above) needs to join the tt_user_project_binds table.
463         $sql = "select $group_field as group_field, sum(time_to_sec(l.duration)) as time";
464         if ($options['show_work_units']) {
465           if ($user->unit_totals_only)
466             $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";
467           else
468             $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";
469         }
470         $sql .= ", sum(cast(l.billable * coalesce(upb.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10,2))) as cost,
471           null as expenses from tt_log l 
472           $group_join
473           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";
474       }
475     } else {
476       $sql = "select $group_field as group_field, sum(time_to_sec(l.duration)) as time";
477       if ($options['show_work_units']) {
478         if ($user->unit_totals_only)
479           $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";
480         else
481           $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";
482       }
483       $sql .= ", null as expenses from tt_log l 
484         $group_join $where group by $group_field";
485     }
486     // By now we have sql for time items.
487
488     // However, when we have expenses, we need to do a union with a separate query for expense items from tt_expense_items table.
489     if ($options['show_cost'] && $user->isPluginEnabled('ex')) { // if ex(penses) plugin is enabled
490
491       // Determine group by field and a required join.
492       $group_join = null;
493       $group_field = 'null';
494       switch ($group_by_option) {
495         case 'date':
496           $group_field = 'ei.date';
497           $group_join = '';
498           break;
499         case 'user':
500           $group_field = 'u.name';
501           $group_join = 'left join tt_users u on (ei.user_id = u.id) ';
502           break;
503         case 'client':
504           $group_field = 'c.name';
505           $group_join = 'left join tt_clients c on (ei.client_id = c.id) ';
506           break;
507         case 'project':
508           $group_field = 'p.name';
509           $group_join = 'left join tt_projects p on (ei.project_id = p.id) ';
510           break;
511       }
512
513       $where = ttReportHelper::getExpenseWhere($options);
514       $sql_for_expenses = "select $group_field as group_field, null as time";
515       if ($options['show_work_units']) $sql_for_expenses .= ", null as units";
516       $sql_for_expenses .= ", sum(ei.cost) as cost, sum(ei.cost) as expenses from tt_expense_items ei $group_join $where";
517       // Add a "group by" clause if we are grouping.
518       if ('null' != $group_field) $sql_for_expenses .= " group by $group_field";
519
520       // Create a combined query.
521       $combined = "select group_field, sum(time) as time";
522       if ($options['show_work_units']) $combined .= ", sum(units) as units";
523       $combined .= ", sum(cost) as cost, sum(expenses) as expenses from (($sql) union all ($sql_for_expenses)) t group by group_field";
524       $sql = $combined;
525     }
526
527     // Execute query.
528     $res = $mdb2->query($sql);
529     if (is_a($res, 'PEAR_Error')) die($res->getMessage());
530
531     while ($val = $res->fetchRow()) {
532       if ('date' == $group_by_option) {
533         $val['group_field'] = ttDateToUserFormat($val['group_field']);
534       }
535       $time = $val['time'] ? sec_to_time_fmt_hm($val['time']) : null;
536       if ($options['show_cost']) {
537         if ('.' != $user->decimal_mark) {
538           $val['cost'] = str_replace('.', $user->decimal_mark, $val['cost']);
539           $val['expenses'] = str_replace('.', $user->decimal_mark, $val['expenses']);
540         }
541         $subtotals[$val['group_field']] = array('name'=>$val['group_field'],'time'=>$time, 'units'=> $val['units'], 'cost'=>$val['cost'],'expenses'=>$val['expenses']);
542       } else
543         $subtotals[$val['group_field']] = array('name'=>$val['group_field'],'time'=>$time, 'units'=> $val['units']);
544     }
545
546     return $subtotals;
547   }
548
549   // getTotals calculates total hours and cost for all report items.
550   static function getTotals($options)
551   {
552     global $user;
553
554     $mdb2 = getConnection();
555
556     $where = ttReportHelper::getWhere($options);
557
558     // Prepare parts.
559     $time_part = "sum(time_to_sec(l.duration)) as time";
560     if ($options['show_work_units']) {
561       $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";
562     }
563     if ($options['show_cost']) {
564       if (MODE_TIME == $user->tracking_mode)
565         $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";
566       else
567         $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";
568     } else {
569       $cost_part = ", null as cost, null as expenses";
570     }
571     if ($options['show_cost']) {
572       if (MODE_TIME == $user->tracking_mode) {
573         $left_joins = "left join tt_users u on (l.user_id = u.id)";
574       } else {
575         $left_joins = "left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id)";
576       }
577     }
578     // Prepare a query for time items.
579     $sql = "select $time_part $units_part $cost_part from tt_log l $left_joins $where";
580
581     // If we have expenses, query becomes a bit more complex.
582     if ($options['show_cost'] && $user->isPluginEnabled('ex')) {
583       $where = ttReportHelper::getExpenseWhere($options);
584       $sql_for_expenses = "select null as time";
585       if ($options['show_work_units']) $sql_for_expenses .= ", null as units";
586       $sql_for_expenses .= ", sum(cost) as cost, sum(cost) as expenses from tt_expense_items ei $where";
587
588       // Create a combined query.
589       $combined = "select sum(time) as time";
590       if ($options['show_work_units']) $combined .= ", sum(units) as units";
591       $combined .= ", sum(cost) as cost, sum(expenses) as expenses from (($sql) union all ($sql_for_expenses)) t";
592       $sql = $combined;
593     }
594
595     // Execute query.
596     $res = $mdb2->query($sql);
597     if (is_a($res, 'PEAR_Error')) die($res->getMessage());
598
599     $val = $res->fetchRow();
600     $total_time = $val['time'] ? sec_to_time_fmt_hm($val['time']) : null;
601     if ($options['show_cost']) {
602       $total_cost = $val['cost'];
603       if (!$total_cost) $total_cost = '0.00';
604       if ('.' != $user->decimal_mark)
605         $total_cost = str_replace('.', $user->decimal_mark, $total_cost);
606       $total_expenses = $val['expenses'];
607       if (!$total_expenses) $total_expenses = '0.00';
608       if ('.' != $user->decimal_mark)
609         $total_expenses = str_replace('.', $user->decimal_mark, $total_expenses);
610     }
611
612     if ($options['period'])
613       $period = new Period($options['period'], new DateAndTime($user->date_format));
614     else {
615       $period = new Period();
616       $period->setPeriod(
617         new DateAndTime($user->date_format, $options['period_start']),
618         new DateAndTime($user->date_format, $options['period_end']));
619     }
620
621     $totals['start_date'] = $period->getStartDate();
622     $totals['end_date'] = $period->getEndDate();
623     $totals['time'] = $total_time;
624     $totals['units'] = $val['units'];
625     $totals['cost'] = $total_cost;
626     $totals['expenses'] = $total_expenses;
627
628     return $totals;
629   }
630
631   // The assignToInvoice assigns a set of records to a specific invoice.
632   static function assignToInvoice($invoice_id, $time_log_ids, $expense_item_ids)
633   {
634     $mdb2 = getConnection();
635     if ($time_log_ids) {
636       $sql = "update tt_log set invoice_id = ".$mdb2->quote($invoice_id).
637         " where id in(".join(', ', $time_log_ids).")";
638       $affected = $mdb2->exec($sql);
639       if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
640     }
641     if ($expense_item_ids) {
642       $sql = "update tt_expense_items set invoice_id = ".$mdb2->quote($invoice_id).
643         " where id in(".join(', ', $expense_item_ids).")";
644       $affected = $mdb2->exec($sql);
645       if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
646     }
647   }
648
649   // The markPaid marks a set of records as either paid or unpaid.
650   static function markPaid($time_log_ids, $expense_item_ids, $paid = true)
651   {
652     $mdb2 = getConnection();
653     $paid_val = (int) $paid;
654     if ($time_log_ids) {
655       $sql = "update tt_log set paid = $paid_val where id in(".join(', ', $time_log_ids).")";
656       $affected = $mdb2->exec($sql);
657       if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
658     }
659     if ($expense_item_ids) {
660       $sql = "update tt_expense_items set paid = $paid_val where id in(".join(', ', $expense_item_ids).")";
661       $affected = $mdb2->exec($sql);
662       if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
663     }
664   }
665
666   // prepareReportBody - prepares an email body for report.
667   static function prepareReportBody($options, $comment = null)
668   {
669     global $user;
670     global $i18n;
671
672     // Determine these once as they are used in multiple places in this function.
673     $canViewReports = $user->can('view_reports') || $user->can('view_all_reports');
674     $isClient = $user->isClient();
675
676     $items = ttReportHelper::getItems($options);
677     $group_by = $options['group_by1'];
678     if ($group_by && 'no_grouping' != $group_by)
679       $subtotals = ttReportHelper::getSubtotals($options);
680     $totals = ttReportHelper::getTotals($options);
681
682     // Use custom fields plugin if it is enabled.
683     if ($user->isPluginEnabled('cf'))
684       $custom_fields = new CustomFields($user->group_id);
685
686     // Define some styles to use in email.
687     $style_title = 'text-align: center; font-size: 15pt; font-family: Arial, Helvetica, sans-serif;';
688     $tableHeader = 'font-weight: bold; background-color: #a6ccf7; text-align: left;';
689     $tableHeaderCentered = 'font-weight: bold; background-color: #a6ccf7; text-align: center;';
690     $rowItem = 'background-color: #ffffff;';
691     $rowItemAlt = 'background-color: #f5f5f5;';
692     $rowSubtotal = 'background-color: #e0e0e0;';
693     $cellLeftAligned = 'text-align: left; vertical-align: top;';
694     $cellRightAligned = 'text-align: right; vertical-align: top;';
695     $cellLeftAlignedSubtotal = 'font-weight: bold; text-align: left; vertical-align: top;';
696     $cellRightAlignedSubtotal = 'font-weight: bold; text-align: right; vertical-align: top;';
697
698     // Start creating email body.
699     $body = '<html>';
700     $body .= '<head><meta http-equiv="content-type" content="text/html; charset='.CHARSET.'"></head>';
701     $body .= '<body>';
702
703     // Output title.
704     $body .= '<p style="'.$style_title.'">'.$i18n->get('form.mail.report_subject').': '.$totals['start_date'].' - '.$totals['end_date'].'</p>';
705
706     // Output comment.
707     if ($comment) $body .= '<p>'.htmlspecialchars($comment).'</p>';
708
709     if ($options['show_totals_only']) {
710       // Totals only report. Output subtotals.
711
712       // Determine group_by header.
713       if ('cf_1' == $group_by)
714         $group_by_header = htmlspecialchars($custom_fields->fields[0]['label']);
715       else {
716         $key = 'label.'.$group_by;
717         $group_by_header = $i18n->get($key);
718       }
719
720       $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
721       $body .= '<tr>';
722       $body .= '<td style="'.$tableHeader.'">'.$group_by_header.'</td>';
723       if ($options['show_duration'])
724         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.duration').'</td>';
725       if ($options['show_work_units'])
726         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.work_units_short').'</td>';
727       if ($options['show_cost'])
728         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.cost').'</td>';
729       $body .= '</tr>';
730       foreach($subtotals as $subtotal) {
731         $body .= '<tr style="'.$rowSubtotal.'">';
732         $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($subtotal['name'] ? htmlspecialchars($subtotal['name']) : '&nbsp;').'</td>';
733         if ($options['show_duration']) {
734           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
735           if ($subtotal['time'] <> '0:00') $body .= $subtotal['time'];
736           $body .= '</td>';
737         }
738         if ($options['show_work_units']) {
739           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
740           $body .= $subtotal['units'];
741           $body .= '</td>';
742         }
743         if ($options['show_cost']) {
744           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
745           $body .= ($canViewReports || $isClient) ? $subtotal['cost'] : $subtotal['expenses'];
746           $body .= '</td>';
747         }
748         $body .= '</tr>';
749       }
750
751       // Print totals.
752       $body .= '<tr><td>&nbsp;</td></tr>';
753       $body .= '<tr style="'.$rowSubtotal.'">';
754       $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.total').'</td>';
755       if ($options['show_duration']) {
756         $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
757         if ($totals['time'] <> '0:00') $body .= $totals['time'];
758         $body .= '</td>';
759       }
760       if ($options['show_work_units']) {
761         $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
762         $body .= $totals['units'];
763         $body .= '</td>';
764       }
765       if ($options['show_cost']) {
766         $body .= '<td nowrap style="'.$cellRightAlignedSubtotal.'">'.htmlspecialchars($user->currency).' ';
767         $body .= ($canViewReports || $isClient) ? $totals['cost'] : $totals['expenses'];
768         $body .= '</td>';
769       }
770       $body .= '</tr>';
771
772       $body .= '</table>';
773     } else {
774       // Regular report.
775
776       // Print table header.
777       $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
778       $body .= '<tr>';
779       $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.date').'</td>';
780       if ($canViewReports || $isClient)
781         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.user').'</td>';
782       if ($options['show_client'])
783         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.client').'</td>';
784       if ($options['show_project'])
785         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.project').'</td>';
786       if ($options['show_task'])
787         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.task').'</td>';
788       if ($options['show_custom_field_1'])
789         $body .= '<td style="'.$tableHeader.'">'.htmlspecialchars($custom_fields->fields[0]['label']).'</td>';
790       if ($options['show_start'])
791         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.start').'</td>';
792       if ($options['show_end'])
793         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.finish').'</td>';
794       if ($options['show_duration'])
795         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.duration').'</td>';
796       if ($options['show_work_units'])
797         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.work_units_short').'</td>';
798       if ($options['show_note'])
799         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.note').'</td>';
800       if ($options['show_cost'])
801         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.cost').'</td>';
802       if ($options['show_paid'])
803         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.paid').'</td>';
804       if ($options['show_ip'])
805         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.ip').'</td>';
806       if ($options['show_invoice'])
807         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.invoice').'</td>';
808       $body .= '</tr>';
809
810       // Initialize variables to print subtotals.
811       if ($items && 'no_grouping' != $group_by) {
812         $print_subtotals = true;
813         $first_pass = true;
814         $prev_grouped_by = '';
815         $cur_grouped_by = '';
816       }
817       // Initialize variables to alternate color of rows for different dates.
818       $prev_date = '';
819       $cur_date = '';
820       $row_style = $rowItem;
821
822       // Print report items.
823       if (is_array($items)) {
824         foreach ($items as $record) {
825           $cur_date = $record['date'];
826           // Print a subtotal row after a block of grouped items.
827           if ($print_subtotals) {
828             $cur_grouped_by = $record['grouped_by'];
829             if ($cur_grouped_by != $prev_grouped_by && !$first_pass) {
830               $body .= '<tr style="'.$rowSubtotal.'">';
831               $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.subtotal').'</td>';
832               $subtotal_name = htmlspecialchars($subtotals[$prev_grouped_by]['name']);
833               if ($canViewReports || $isClient) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'user' ? $subtotal_name : '').'</td>';
834               if ($options['show_client']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'client' ? $subtotal_name : '').'</td>';
835               if ($options['show_project']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'project' ? $subtotal_name : '').'</td>';
836               if ($options['show_task']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'task' ? $subtotal_name : '').'</td>';
837               if ($options['show_custom_field_1']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'cf_1' ? $subtotal_name : '').'</td>';
838               if ($options['show_start']) $body .= '<td></td>';
839               if ($options['show_end']) $body .= '<td></td>';
840               if ($options['show_duration']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['time'].'</td>';
841               if ($options['show_work_units']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['units'].'</td>';
842               if ($options['show_note']) $body .= '<td></td>';
843               if ($options['show_cost']) {
844                 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
845                 $body .= ($canViewReports || $isClient) ? $subtotals[$prev_grouped_by]['cost'] : $subtotals[$prev_grouped_by]['expenses'];
846                 $body .= '</td>';
847               }
848               if ($options['show_paid']) $body .= '<td></td>';
849               if ($options['show_ip']) $body .= '<td></td>';
850               if ($options['show_invoice']) $body .= '<td></td>';
851               $body .= '</tr>';
852               $body .= '<tr><td>&nbsp;</td></tr>';
853             }
854             $first_pass = false;
855           }
856
857           // Print a regular row.
858           if ($cur_date != $prev_date)
859             $row_style = ($row_style == $rowItem) ? $rowItemAlt : $rowItem;
860           $body .= '<tr style="'.$row_style.'">';
861           $body .= '<td style="'.$cellLeftAligned.'">'.$record['date'].'</td>';
862           if ($canViewReports || $isClient)
863             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['user']).'</td>';
864           if ($options['show_client'])
865             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['client']).'</td>';
866           if ($options['show_project'])
867             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['project']).'</td>';
868           if ($options['show_task'])
869             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['task']).'</td>';
870           if ($options['show_custom_field_1'])
871             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['cf_1']).'</td>';
872           if ($options['show_start'])
873             $body .= '<td nowrap style="'.$cellRightAligned.'">'.$record['start'].'</td>';
874           if ($options['show_end'])
875             $body .= '<td nowrap style="'.$cellRightAligned.'">'.$record['finish'].'</td>';
876           if ($options['show_duration'])
877             $body .= '<td style="'.$cellRightAligned.'">'.$record['duration'].'</td>';
878           if ($options['show_work_units'])
879             $body .= '<td style="'.$cellRightAligned.'">'.$record['units'].'</td>';
880           if ($options['show_note'])
881             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['note']).'</td>';
882           if ($options['show_cost'])
883             $body .= '<td style="'.$cellRightAligned.'">'.$record['cost'].'</td>';
884           if ($options['show_paid']) {
885             $body .= '<td style="'.$cellRightAligned.'">';
886             $body .= $record['paid'] == 1 ? $i18n->get('label.yes') : $i18n->get('label.no');
887             $body .= '</td>';
888           }
889           if ($options['show_ip']) {
890             $body .= '<td style="'.$cellRightAligned.'">';
891             $body .= $record['modified'] ? $record['modified_ip'].' '.$record['modified'] : $record['created_ip'].' '.$record['created'];
892             $body .= '</td>';
893           }
894           if ($options['show_invoice'])
895             $body .= '<td style="'.$cellRightAligned.'">'.htmlspecialchars($record['invoice']).'</td>';
896           $body .= '</tr>';
897
898           $prev_date = $record['date'];
899           if ($print_subtotals)
900             $prev_grouped_by = $record['grouped_by'];
901         }
902       }
903
904       // Print a terminating subtotal.
905       if ($print_subtotals) {
906         $body .= '<tr style="'.$rowSubtotal.'">';
907         $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.subtotal').'</td>';
908         $subtotal_name = htmlspecialchars($subtotals[$cur_grouped_by]['name']);
909         if ($canViewReports || $isClient) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'user' ? $subtotal_name : '').'</td>';
910         if ($options['show_client']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'client' ? $subtotal_name : '').'</td>';
911         if ($options['show_project']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'project' ? $subtotal_name : '').'</td>';
912         if ($options['show_task']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'task' ? $subtotal_name : '').'</td>';
913         if ($options['show_custom_field_1']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'cf_1' ? $subtotal_name : '').'</td>';
914         if ($options['show_start']) $body .= '<td></td>';
915         if ($options['show_end']) $body .= '<td></td>';
916         if ($options['show_duration']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$cur_grouped_by]['time'].'</td>';
917         if ($options['show_work_units']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$cur_grouped_by]['units'].'</td>';
918         if ($options['show_note']) $body .= '<td></td>';
919         if ($options['show_cost']) {
920           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
921           $body .= ($canViewReports || $isClient) ? $subtotals[$cur_grouped_by]['cost'] : $subtotals[$cur_grouped_by]['expenses'];
922           $body .= '</td>';
923         }
924         if ($options['show_paid']) $body .= '<td></td>';
925         if ($options['show_ip']) $body .= '<td></td>';
926         if ($options['show_invoice']) $body .= '<td></td>';
927         $body .= '</tr>';
928       }
929
930       // Print totals.
931       $body .= '<tr><td>&nbsp;</td></tr>';
932       $body .= '<tr style="'.$rowSubtotal.'">';
933       $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.total').'</td>';
934       if ($canViewReports || $isClient) $body .= '<td></td>';
935       if ($options['show_client']) $body .= '<td></td>';
936       if ($options['show_project']) $body .= '<td></td>';
937       if ($options['show_task']) $body .= '<td></td>';
938       if ($options['show_custom_field_1']) $body .= '<td></td>';
939       if ($options['show_start']) $body .= '<td></td>';
940       if ($options['show_end']) $body .= '<td></td>';
941       if ($options['show_duration']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$totals['time'].'</td>';
942       if ($options['show_work_units']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$totals['units'].'</td>';
943       if ($options['show_note']) $body .= '<td></td>';
944       if ($options['show_cost']) {
945         $body .= '<td nowrap style="'.$cellRightAlignedSubtotal.'">'.htmlspecialchars($user->currency).' ';
946         $body .= ($canViewReports || $isClient) ? $totals['cost'] : $totals['expenses'];
947         $body .= '</td>';
948       }
949       if ($options['show_paid']) $body .= '<td></td>';
950       if ($options['show_ip']) $body .= '<td></td>';
951       if ($options['show_invoice']) $body .= '<td></td>';
952       $body .= '</tr>';
953
954       $body .= '</table>';
955     }
956
957     // Output footer.
958     if (!defined('REPORT_FOOTER') || !(REPORT_FOOTER == false))
959       $body .= '<p style="text-align: center;">'.$i18n->get('form.mail.footer').'</p>';
960
961     // Finish creating email body.
962     $body .= '</body></html>';
963
964     return $body;
965   }
966
967   // checkFavReportCondition - checks whether it is okay to send fav report.
968   static function checkFavReportCondition($options, $condition)
969   {
970     $items = ttReportHelper::getItems($options);
971
972     $condition = trim(str_replace('count', '', $condition));
973
974     $greater_or_equal = ttStartsWith($condition, '>=');
975     if ($greater_or_equal) $condition = trim(str_replace('>=', '', $condition));
976
977     $less_or_equal = ttStartsWith($condition, '<=');
978     if ($less_or_equal) $condition = trim(str_replace('<=', '', $condition));
979
980     $not_equal = ttStartsWith($condition, '<>');
981     if ($not_equal) $condition = trim(str_replace('<>', '', $condition));
982
983     $greater = ttStartsWith($condition, '>');
984     if ($greater) $condition = trim(str_replace('>', '', $condition));
985
986     $less = ttStartsWith($condition, '<');
987     if ($less) $condition = trim(str_replace('<', '', $condition));
988
989     $equal = ttStartsWith($condition, '=');
990     if ($equal) $condition = trim(str_replace('=', '', $condition));
991
992     $count_required = (int) $condition;
993
994     if ($greater && count($items) > $count_required) return true;
995     if ($greater_or_equal && count($items) >= $count_required) return true;
996     if ($less && count($items) < $count_required) return true;
997     if ($less_or_equal && count($items) <= $count_required) return true;
998     if ($equal && count($items) == $count_required) return true;
999     if ($not_equal && count($items) <> $count_required) return true;
1000
1001     return false;
1002   }
1003
1004   // sendFavReport - sends a favorite report to a specified email, called from cron.php
1005   static function sendFavReport($options, $subject, $email, $cc) {
1006     // We are called from cron.php, we have no $bean in session.
1007     // cron.php sets global $user and $i18n objects to match our favorite report user.
1008     global $user;
1009     global $i18n;
1010
1011     // Prepare report body.
1012     $body = ttReportHelper::prepareReportBody($options);
1013
1014     import('mail.Mailer');
1015     $mailer = new Mailer();
1016     $mailer->setCharSet(CHARSET);
1017     $mailer->setContentType('text/html');
1018     $mailer->setSender(SENDER);
1019     if (!empty($cc))
1020       $mailer->setReceiverCC($cc);
1021     if (!empty($user->bcc_email))
1022       $mailer->setReceiverBCC($user->bcc_email);
1023     $mailer->setReceiver($email);
1024     $mailer->setMailMode(MAIL_MODE);
1025     if (empty($subject)) $subject = $options['name'];
1026     if (!$mailer->send($subject, $body))
1027       return false;
1028
1029     return true;
1030   }
1031
1032   // getReportOptions - returns an array of report options constructed from session bean.
1033   //
1034   // Note: similarly to ttFavReportHelper::getReportOptions, this function is a part of
1035   // refactoring to simplify maintenance of report generating functions, as we currently
1036   // have 2 sets: normal reporting (from bean), and fav report emailing (from db fields).
1037   // Using options obtained from either db or bean shall allow us to use only one set of functions.
1038   static function getReportOptions($bean) {
1039     global $user;
1040
1041     // Prepare an array of report options.
1042     $options = array();
1043
1044     // Construct one by one.
1045     $options['name'] = null; // No name required.
1046     $options['user_id'] = $user->id; // Not sure if we need user_id here. Fav reports use it to recycle $user object in cron.php.
1047     $options['client_id'] = $bean->getAttribute('client');
1048     $options['cf_1_option_id'] = $bean->getAttribute('option');
1049     $options['project_id'] = $bean->getAttribute('project');
1050     $options['task_id'] = $bean->getAttribute('task');
1051     $options['billable'] = $bean->getAttribute('include_records');
1052     $options['invoice'] = $bean->getAttribute('invoice');
1053     $options['paid_status'] = $bean->getAttribute('paid_status');
1054     if (is_array($bean->getAttribute('users'))) $options['users'] = join(',', $bean->getAttribute('users'));
1055     $options['period'] = $bean->getAttribute('period');
1056     $options['period_start'] = $bean->getAttribute('start_date');
1057     $options['period_end'] = $bean->getAttribute('end_date');
1058     $options['show_client'] = $bean->getAttribute('chclient');
1059     $options['show_invoice'] = $bean->getAttribute('chinvoice');
1060     $options['show_paid'] = $bean->getAttribute('chpaid');
1061     $options['show_ip'] = $bean->getAttribute('chip');
1062     $options['show_project'] = $bean->getAttribute('chproject');
1063     $options['show_start'] = $bean->getAttribute('chstart');
1064     $options['show_duration'] = $bean->getAttribute('chduration');
1065     $options['show_cost'] = $bean->getAttribute('chcost');
1066     $options['show_task'] = $bean->getAttribute('chtask');
1067     $options['show_end'] = $bean->getAttribute('chfinish');
1068     $options['show_note'] = $bean->getAttribute('chnote');
1069     $options['show_custom_field_1'] = $bean->getAttribute('chcf_1');
1070     $options['show_work_units'] = $bean->getAttribute('chunits');
1071     $options['show_totals_only'] = $bean->getAttribute('chtotalsonly');
1072     $options['group_by1'] = $bean->getAttribute('group_by1');
1073     $options['group_by2'] = $bean->getAttribute('group_by2');
1074     $options['group_by3'] = $bean->getAttribute('group_by3');
1075     return $options;
1076   }
1077
1078   // verifyBean is a security function to make sure data in bean makes sense for a group.
1079   static function verifyBean($bean) {
1080     global $user;
1081
1082     // Check users.
1083     $users_in_bean = $bean->getAttribute('users');
1084     if (is_array($users_in_bean)) {
1085       $users_in_group = ttTeamHelper::getUsers();
1086       foreach ($users_in_group as $user_in_group) {
1087         $valid_ids[] = $user_in_group['id'];
1088       }
1089       foreach ($users_in_bean as $user_in_bean) {
1090         if (!in_array($user_in_bean, $valid_ids)) {
1091           return false;
1092         }
1093       }
1094     }
1095
1096     // TODO: add additional checks here. Perhaps do it before saving the bean for consistency.
1097     return true;
1098   }
1099 }