Integrated paid status in emailed reports.
[timetracker.git] / WEB-INF / lib / ttReportHelper.class.php
1 <?php
2 // +----------------------------------------------------------------------+
3 // | Anuko Time Tracker
4 // +----------------------------------------------------------------------+
5 // | Copyright (c) Anuko International Ltd. (https://www.anuko.com)
6 // +----------------------------------------------------------------------+
7 // | LIBERAL FREEWARE LICENSE: This source code document may be used
8 // | by anyone for any purpose, and freely redistributed alone or in
9 // | combination with other software, provided that the license is obeyed.
10 // |
11 // | There are only two ways to violate the license:
12 // |
13 // | 1. To redistribute this code in source form, with the copyright
14 // |    notice or license removed or altered. (Distributing in compiled
15 // |    forms without embedded copyright notices is permitted).
16 // |
17 // | 2. To redistribute modified versions of this code in *any* form
18 // |    that bears insufficient indications that the modifications are
19 // |    not the work of the original author(s).
20 // |
21 // | This license applies to this document only, not any other software
22 // | that it may be combined with.
23 // |
24 // +----------------------------------------------------------------------+
25 // | Contributors:
26 // | https://www.anuko.com/time_tracker/credits.htm
27 // +----------------------------------------------------------------------+
28
29 import('ttClientHelper');
30 import('DateAndTime');
31 import('Period');
32 import('ttTimeHelper');
33
34 require_once(dirname(__FILE__).'/../../plugins/CustomFields.class.php');
35
36 // Class ttReportHelper is used for help with reports.
37 class ttReportHelper {
38
39   // getWhere prepares a WHERE clause for a report query.
40   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('chpaid'))
1170         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->getKey('label.paid').'</td>';
1171       if ($bean->getAttribute('chinvoice'))
1172         $body .= '<td style="'.$tableHeader.'">'.$i18n->getKey('label.invoice').'</td>';
1173       $body .= '</tr>';
1174
1175       // Initialize variables to print subtotals.
1176       if ($items && 'no_grouping' != $group_by) {
1177         $print_subtotals = true;
1178         $first_pass = true;
1179         $prev_grouped_by = '';
1180         $cur_grouped_by = '';
1181       }
1182       // Initialize variables to alternate color of rows for different dates.
1183       $prev_date = '';
1184       $cur_date = '';
1185       $row_style = $rowItem;
1186
1187       // Print report items.
1188       if (is_array($items)) {
1189         foreach ($items as $record) {
1190           $cur_date = $record['date'];
1191           // Print a subtotal row after a block of grouped items.
1192           if ($print_subtotals) {
1193             $cur_grouped_by = $record['grouped_by'];
1194             if ($cur_grouped_by != $prev_grouped_by && !$first_pass) {
1195               $body .= '<tr style="'.$rowSubtotal.'">';
1196               $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->getKey('label.subtotal').'</td>';
1197               $subtotal_name = htmlspecialchars($subtotals[$prev_grouped_by]['name']);
1198               if ($user->canManageTeam() || $user->isClient()) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'user' ? $subtotal_name : '').'</td>';
1199               if ($bean->getAttribute('chclient')) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'client' ? $subtotal_name : '').'</td>';
1200               if ($bean->getAttribute('chproject')) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'project' ? $subtotal_name : '').'</td>';
1201               if ($bean->getAttribute('chtask')) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'task' ? $subtotal_name : '').'</td>';
1202               if ($bean->getAttribute('chcf_1')) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'cf_1' ? $subtotal_name : '').'</td>';
1203               if ($bean->getAttribute('chstart')) $body .= '<td></td>';
1204               if ($bean->getAttribute('chfinish')) $body .= '<td></td>';
1205               if ($bean->getAttribute('chduration')) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['time'].'</td>';
1206               if ($bean->getAttribute('chnote')) $body .= '<td></td>';
1207               if ($bean->getAttribute('chcost')) {
1208                 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1209                 $body .= ($user->canManageTeam() || $user->isClient()) ? $subtotals[$prev_grouped_by]['cost'] : $subtotals[$prev_grouped_by]['expenses'];
1210                 $body .= '</td>';
1211               }
1212               if ($bean->getAttribute('chpaid')) $body .= '<td></td>';
1213               if ($bean->getAttribute('chinvoice')) $body .= '<td></td>';
1214               $body .= '</tr>';
1215               $body .= '<tr><td>&nbsp;</td></tr>';
1216             }
1217             $first_pass = false;
1218           }
1219
1220           // Print a regular row.
1221           if ($cur_date != $prev_date)
1222             $row_style = ($row_style == $rowItem) ? $rowItemAlt : $rowItem;
1223           $body .= '<tr style="'.$row_style.'">';
1224           $body .= '<td style="'.$cellLeftAligned.'">'.$record['date'].'</td>';
1225           if ($user->canManageTeam() || $user->isClient())
1226             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['user']).'</td>';
1227           if ($bean->getAttribute('chclient'))
1228             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['client']).'</td>';
1229           if ($bean->getAttribute('chproject'))
1230             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['project']).'</td>';
1231           if ($bean->getAttribute('chtask'))
1232             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['task']).'</td>';
1233           if ($bean->getAttribute('chcf_1'))
1234             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['cf_1']).'</td>';
1235           if ($bean->getAttribute('chstart'))
1236             $body .= '<td nowrap style="'.$cellRightAligned.'">'.$record['start'].'</td>';
1237           if ($bean->getAttribute('chfinish'))
1238             $body .= '<td nowrap style="'.$cellRightAligned.'">'.$record['finish'].'</td>';
1239           if ($bean->getAttribute('chduration'))
1240             $body .= '<td style="'.$cellRightAligned.'">'.$record['duration'].'</td>';
1241           if ($bean->getAttribute('chnote'))
1242             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['note']).'</td>';
1243           if ($bean->getAttribute('chcost'))
1244             $body .= '<td style="'.$cellRightAligned.'">'.$record['cost'].'</td>';
1245           if ($bean->getAttribute('chpaid')) {
1246             $body .= '<td style="'.$cellRightAligned.'">';
1247             $body .= $record['paid'] == 1 ? $i18n->getKey('label.yes') : $i18n->getKey('label.no');
1248             $body .= '</td>';
1249           }
1250           if ($bean->getAttribute('chinvoice'))
1251             $body .= '<td style="'.$cellRightAligned.'">'.htmlspecialchars($record['invoice']).'</td>';
1252           $body .= '</tr>';
1253
1254           $prev_date = $record['date'];
1255           if ($print_subtotals)
1256             $prev_grouped_by = $record['grouped_by'];
1257         }
1258       }
1259
1260       // Print a terminating subtotal.
1261       if ($print_subtotals) {
1262         $body .= '<tr style="'.$rowSubtotal.'">';
1263         $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->getKey('label.subtotal').'</td>';
1264         $subtotal_name = htmlspecialchars($subtotals[$cur_grouped_by]['name']);
1265         if ($user->canManageTeam() || $user->isClient()) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'user' ? $subtotal_name : '').'</td>';
1266         if ($bean->getAttribute('chclient')) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'client' ? $subtotal_name : '').'</td>';
1267         if ($bean->getAttribute('chproject')) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'project' ? $subtotal_name : '').'</td>';
1268         if ($bean->getAttribute('chtask')) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'task' ? $subtotal_name : '').'</td>';
1269         if ($bean->getAttribute('chcf_1')) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'cf_1' ? $subtotal_name : '').'</td>';
1270         if ($bean->getAttribute('chstart')) $body .= '<td></td>';
1271         if ($bean->getAttribute('chfinish')) $body .= '<td></td>';
1272         if ($bean->getAttribute('chduration')) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$cur_grouped_by]['time'].'</td>';
1273         if ($bean->getAttribute('chnote')) $body .= '<td></td>';
1274         if ($bean->getAttribute('chcost')) {
1275           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1276           $body .= ($user->canManageTeam() || $user->isClient()) ? $subtotals[$cur_grouped_by]['cost'] : $subtotals[$cur_grouped_by]['expenses'];
1277           $body .= '</td>';
1278         }
1279         if ($bean->getAttribute('chpaid')) $body .= '<td></td>';
1280         if ($bean->getAttribute('chinvoice')) $body .= '<td></td>';
1281         $body .= '</tr>';
1282       }
1283
1284       // Print totals.
1285       $body .= '<tr><td>&nbsp;</td></tr>';
1286       $body .= '<tr style="'.$rowSubtotal.'">';
1287       $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->getKey('label.total').'</td>';
1288       if ($user->canManageTeam() || $user->isClient()) $body .= '<td></td>';
1289       if ($bean->getAttribute('chclient')) $body .= '<td></td>';
1290       if ($bean->getAttribute('chproject')) $body .= '<td></td>';
1291       if ($bean->getAttribute('chtask')) $body .= '<td></td>';
1292       if ($bean->getAttribute('chcf_1')) $body .= '<td></td>';
1293       if ($bean->getAttribute('chstart')) $body .= '<td></td>';
1294       if ($bean->getAttribute('chfinish')) $body .= '<td></td>';
1295       if ($bean->getAttribute('chduration')) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$totals['time'].'</td>';
1296       if ($bean->getAttribute('chnote')) $body .= '<td></td>';
1297       if ($bean->getAttribute('chcost')) {
1298         $body .= '<td nowrap style="'.$cellRightAlignedSubtotal.'">'.htmlspecialchars($user->currency).' ';
1299         $body .= ($user->canManageTeam() || $user->isClient()) ? $totals['cost'] : $totals['expenses'];
1300         $body .= '</td>';
1301       }
1302       if ($bean->getAttribute('chpaid')) $body .= '<td></td>';
1303       if ($bean->getAttribute('chinvoice')) $body .= '<td></td>';
1304       $body .= '</tr>';
1305
1306       $body .= '</table>';
1307     }
1308
1309     // Output footer.
1310     if (!defined('REPORT_FOOTER') || !(REPORT_FOOTER == false))
1311       $body .= '<p style="text-align: center;">'.$i18n->getKey('form.mail.footer').'</p>';
1312
1313     // Finish creating email body.
1314     $body .= '</body></html>';
1315
1316     return $body;
1317   }
1318
1319   // checkFavReportCondition - checks whether it is okay to send fav report.
1320   static function checkFavReportCondition($report, $condition)
1321   {
1322     $items = ttReportHelper::getFavItems($report);
1323
1324     $condition = str_replace('count', '', $condition);
1325     $count_required = intval(trim(str_replace('>', '', $condition)));
1326
1327     if (count($items) > $count_required)
1328       return true; // Condition ok.
1329
1330     return false;
1331   }
1332
1333   // prepareFavReportBody - prepares an email body for a favorite report.
1334   static function prepareFavReportBody($report)
1335   {
1336     global $user;
1337     global $i18n;
1338
1339     $items = ttReportHelper::getFavItems($report);
1340     $group_by = $report['group_by'];
1341     if ($group_by && 'no_grouping' != $group_by)
1342       $subtotals = ttReportHelper::getFavSubtotals($report);
1343     $totals = ttReportHelper::getFavTotals($report);
1344
1345     // Use custom fields plugin if it is enabled.
1346     if ($user->isPluginEnabled('cf'))
1347       $custom_fields = new CustomFields($user->team_id);
1348
1349     // Define some styles to use in email.
1350     $style_title = 'text-align: center; font-size: 15pt; font-family: Arial, Helvetica, sans-serif;';
1351     $tableHeader = 'font-weight: bold; background-color: #a6ccf7; text-align: left;';
1352     $tableHeaderCentered = 'font-weight: bold; background-color: #a6ccf7; text-align: center;';
1353     $rowItem = 'background-color: #ffffff;';
1354     $rowItemAlt = 'background-color: #f5f5f5;';
1355     $rowSubtotal = 'background-color: #e0e0e0;';
1356     $cellLeftAligned = 'text-align: left; vertical-align: top;';
1357     $cellRightAligned = 'text-align: right; vertical-align: top;';
1358     $cellLeftAlignedSubtotal = 'font-weight: bold; text-align: left; vertical-align: top;';
1359     $cellRightAlignedSubtotal = 'font-weight: bold; text-align: right; vertical-align: top;';
1360
1361     // Start creating email body.
1362     $body = '<html>';
1363     $body .= '<head><meta http-equiv="content-type" content="text/html; charset='.CHARSET.'"></head>';
1364     $body .= '<body>';
1365
1366     // Output title.
1367     $body .= '<p style="'.$style_title.'">'.$i18n->getKey('form.mail.report_subject').': '.$totals['start_date'].' - '.$totals['end_date'].'</p>';
1368
1369     // Output comment.
1370     // if ($comment) $body .= '<p>'.htmlspecialchars($comment).'</p>'; // No comment for fav. reports.
1371
1372     if ($report['show_totals_only']) {
1373       // Totals only report. Output subtotals.
1374
1375       // Determine group_by header.
1376       if ('cf_1' == $group_by)
1377         $group_by_header = htmlspecialchars($custom_fields->fields[0]['label']);
1378       else {
1379         $key = 'label.'.$group_by;
1380         $group_by_header = $i18n->getKey($key);
1381       }
1382
1383       $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
1384       $body .= '<tr>';
1385       $body .= '<td style="'.$tableHeader.'">'.$group_by_header.'</td>';
1386       if ($report['show_duration'])
1387         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->getKey('label.duration').'</td>';
1388       if ($report['show_cost'])
1389         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->getKey('label.cost').'</td>';
1390       $body .= '</tr>';
1391       foreach($subtotals as $subtotal) {
1392         $body .= '<tr style="'.$rowSubtotal.'">';
1393         $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($subtotal['name'] ? htmlspecialchars($subtotal['name']) : '&nbsp;').'</td>';
1394         if ($report['show_duration']) {
1395           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1396           if ($subtotal['time'] <> '0:00') $body .= $subtotal['time'];
1397           $body .= '</td>';
1398         }
1399         if ($report['show_cost']) {
1400           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1401           $body .= ($user->canManageTeam() || $user->isClient()) ? $subtotal['cost'] : $subtotal['expenses'];
1402           $body .= '</td>';
1403         }
1404         $body .= '</tr>';
1405       }
1406
1407       // Print totals.
1408       $body .= '<tr><td>&nbsp;</td></tr>';
1409       $body .= '<tr style="'.$rowSubtotal.'">';
1410       $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->getKey('label.total').'</td>';
1411       if ($report['show_duration']) {
1412         $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1413         if ($totals['time'] <> '0:00') $body .= $totals['time'];
1414         $body .= '</td>';
1415       }
1416       if ($report['show_cost']) {
1417         $body .= '<td nowrap style="'.$cellRightAlignedSubtotal.'">'.htmlspecialchars($user->currency).' ';
1418         $body .= ($user->canManageTeam() || $user->isClient()) ? $totals['cost'] : $totals['expenses'];
1419         $body .= '</td>';
1420       }
1421       $body .= '</tr>';
1422
1423       $body .= '</table>';
1424     } else {
1425       // Regular report.
1426
1427       // Print table header.
1428       $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
1429       $body .= '<tr>';
1430       $body .= '<td style="'.$tableHeader.'">'.$i18n->getKey('label.date').'</td>';
1431       if ($user->canManageTeam() || $user->isClient())
1432         $body .= '<td style="'.$tableHeader.'">'.$i18n->getKey('label.user').'</td>';
1433       if ($report['show_client'])
1434         $body .= '<td style="'.$tableHeader.'">'.$i18n->getKey('label.client').'</td>';
1435       if ($report['show_project'])
1436         $body .= '<td style="'.$tableHeader.'">'.$i18n->getKey('label.project').'</td>';
1437       if ($report['show_task'])
1438         $body .= '<td style="'.$tableHeader.'">'.$i18n->getKey('label.task').'</td>';
1439       if ($report['show_custom_field_1'])
1440         $body .= '<td style="'.$tableHeader.'">'.htmlspecialchars($custom_fields->fields[0]['label']).'</td>';
1441       if ($report['show_start'])
1442         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->getKey('label.start').'</td>';
1443       if ($report['show_end'])
1444         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->getKey('label.finish').'</td>';
1445       if ($report['show_duration'])
1446         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->getKey('label.duration').'</td>';
1447       if ($report['show_note'])
1448         $body .= '<td style="'.$tableHeader.'">'.$i18n->getKey('label.note').'</td>';
1449       if ($report['show_cost'])
1450         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->getKey('label.cost').'</td>';
1451       if ($report['show_invoice'])
1452         $body .= '<td style="'.$tableHeader.'">'.$i18n->getKey('label.invoice').'</td>';
1453       $body .= '</tr>';
1454
1455       // Initialize variables to print subtotals.
1456       if ($items && 'no_grouping' != $group_by) {
1457         $print_subtotals = true;
1458         $first_pass = true;
1459         $prev_grouped_by = '';
1460         $cur_grouped_by = '';
1461       }
1462       // Initialize variables to alternate color of rows for different dates.
1463       $prev_date = '';
1464       $cur_date = '';
1465       $row_style = $rowItem;
1466
1467       // Print report items.
1468       if (is_array($items)) {
1469         foreach ($items as $record) {
1470           $cur_date = $record['date'];
1471           // Print a subtotal row after a block of grouped items.
1472           if ($print_subtotals) {
1473             $cur_grouped_by = $record['grouped_by'];
1474             if ($cur_grouped_by != $prev_grouped_by && !$first_pass) {
1475               $body .= '<tr style="'.$rowSubtotal.'">';
1476               $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->getKey('label.subtotal').'</td>';
1477               $subtotal_name = htmlspecialchars($subtotals[$prev_grouped_by]['name']);
1478               if ($user->canManageTeam() || $user->isClient()) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'user' ? $subtotal_name : '').'</td>';
1479               if ($report['show_client']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'client' ? $subtotal_name : '').'</td>';
1480               if ($report['show_project']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'project' ? $subtotal_name : '').'</td>';
1481               if ($report['show_task']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'task' ? $subtotal_name : '').'</td>';
1482               if ($report['show_custom_field_1']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'cf_1' ? $subtotal_name : '').'</td>';
1483               if ($report['show_start']) $body .= '<td></td>';
1484               if ($report['show_end']) $body .= '<td></td>';
1485               if ($report['show_duration']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['time'].'</td>';
1486               if ($report['show_note']) $body .= '<td></td>';
1487               if ($report['show_cost']) {
1488                 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1489                 $body .= ($user->canManageTeam() || $user->isClient()) ? $subtotals[$prev_grouped_by]['cost'] : $subtotals[$prev_grouped_by]['expenses'];
1490                 $body .= '</td>';
1491               }
1492               if ($report['show_invoice']) $body .= '<td></td>';
1493               $body .= '</tr>';
1494               $body .= '<tr><td>&nbsp;</td></tr>';
1495             }
1496             $first_pass = false;
1497           }
1498
1499           // Print a regular row.
1500           if ($cur_date != $prev_date)
1501             $row_style = ($row_style == $rowItem) ? $rowItemAlt : $rowItem;
1502           $body .= '<tr style="'.$row_style.'">';
1503           $body .= '<td style="'.$cellLeftAligned.'">'.$record['date'].'</td>';
1504           if ($user->canManageTeam() || $user->isClient())
1505             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['user']).'</td>';
1506           if ($report['show_client'])
1507             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['client']).'</td>';
1508           if ($report['show_project'])
1509             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['project']).'</td>';
1510           if ($report['show_task'])
1511             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['task']).'</td>';
1512           if ($report['show_custom_field_1'])
1513             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['cf_1']).'</td>';
1514           if ($report['show_start'])
1515             $body .= '<td nowrap style="'.$cellRightAligned.'">'.$record['start'].'</td>';
1516           if ($report['show_end'])
1517             $body .= '<td nowrap style="'.$cellRightAligned.'">'.$record['finish'].'</td>';
1518           if ($report['show_duration'])
1519             $body .= '<td style="'.$cellRightAligned.'">'.$record['duration'].'</td>';
1520           if ($report['show_note'])
1521             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['note']).'</td>';
1522           if ($report['show_cost'])
1523             $body .= '<td style="'.$cellRightAligned.'">'.$record['cost'].'</td>';
1524           if ($report['show_invoice'])
1525             $body .= '<td style="'.$cellRightAligned.'">'.htmlspecialchars($record['invoice']).'</td>';
1526           $body .= '</tr>';
1527
1528           $prev_date = $record['date'];
1529           if ($print_subtotals)
1530             $prev_grouped_by = $record['grouped_by'];
1531         }
1532       }
1533
1534       // Print a terminating subtotal.
1535       if ($print_subtotals) {
1536         $body .= '<tr style="'.$rowSubtotal.'">';
1537         $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->getKey('label.subtotal').'</td>';
1538         $subtotal_name = htmlspecialchars($subtotals[$cur_grouped_by]['name']);
1539         if ($user->canManageTeam() || $user->isClient()) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'user' ? $subtotal_name : '').'</td>';
1540         if ($report['show_client']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'client' ? $subtotal_name : '').'</td>';
1541         if ($report['show_project']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'project' ? $subtotal_name : '').'</td>';
1542         if ($report['show_task']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'task' ? $subtotal_name : '').'</td>';
1543         if ($report['show_custom_field_1']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'cf_1' ? $subtotal_name : '').'</td>';
1544         if ($report['show_start']) $body .= '<td></td>';
1545         if ($report['show_end']) $body .= '<td></td>';
1546         if ($report['show_duration']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$cur_grouped_by]['time'].'</td>';
1547         if ($report['show_note']) $body .= '<td></td>';
1548         if ($report['show_cost']) {
1549           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1550           $body .= ($user->canManageTeam() || $user->isClient()) ? $subtotals[$cur_grouped_by]['cost'] : $subtotals[$cur_grouped_by]['expenses'];
1551           $body .= '</td>';
1552         }
1553         if ($report['show_invoice']) $body .= '<td></td>';
1554         $body .= '</tr>';
1555       }
1556
1557       // Print totals.
1558       $body .= '<tr><td>&nbsp;</td></tr>';
1559       $body .= '<tr style="'.$rowSubtotal.'">';
1560       $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->getKey('label.total').'</td>';
1561       if ($user->canManageTeam() || $user->isClient()) $body .= '<td></td>';
1562       if ($report['show_client']) $body .= '<td></td>';
1563       if ($report['show_project']) $body .= '<td></td>';
1564       if ($report['show_task']) $body .= '<td></td>';
1565       if ($report['show_custom_field_1']) $body .= '<td></td>';
1566       if ($report['show_start']) $body .= '<td></td>';
1567       if ($report['show_end']) $body .= '<td></td>';
1568       if ($report['show_duration']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$totals['time'].'</td>';
1569       if ($report['show_note']) $body .= '<td></td>';
1570       if ($report['show_cost']) {
1571         $body .= '<td nowrap style="'.$cellRightAlignedSubtotal.'">'.htmlspecialchars($user->currency).' ';
1572         $body .= ($user->canManageTeam() || $user->isClient()) ? $totals['cost'] : $totals['expenses'];
1573         $body .= '</td>';
1574       }
1575       if ($report['show_invoice']) $body .= '<td></td>';
1576       $body .= '</tr>';
1577
1578       $body .= '</table>';
1579     }
1580
1581     // Output footer.
1582     if (!defined('REPORT_FOOTER') || !(REPORT_FOOTER == false))
1583       $body .= '<p style="text-align: center;">'.$i18n->getKey('form.mail.footer').'</p>';
1584
1585     // Finish creating email body.
1586     $body .= '</body></html>';
1587
1588     return $body;
1589   }
1590
1591   // sendFavReport - sends a favorite report to a specified email, called from cron.php
1592   static function sendFavReport($report, $subject, $email, $cc) {
1593     // We are called from cron.php, we have no $bean in session.
1594     // cron.php sets global $user and $i18n objects to match our favorite report user.
1595     global $user;
1596     global $i18n;
1597
1598     // Prepare report body.
1599     $body = ttReportHelper::prepareFavReportBody($report);
1600
1601     import('mail.Mailer');
1602     $mailer = new Mailer();
1603     $mailer->setCharSet(CHARSET);
1604     $mailer->setContentType('text/html');
1605     $mailer->setSender(SENDER);
1606     if (!empty($cc))
1607       $mailer->setReceiverCC($cc);
1608     if (!empty($user->bcc_email))
1609       $mailer->setReceiverBCC($user->bcc_email);
1610     $mailer->setReceiver($email);
1611     $mailer->setMailMode(MAIL_MODE);
1612     if (empty($subject)) $subject = $report['name'];
1613     if (!$mailer->send($subject, $body))
1614       return false;
1615
1616     return true;
1617   }
1618 }