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