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