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