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