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