Reorganized code a bit.
[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')) die($res->getMessage());
593
594     while ($val = $res->fetchRow()) {
595       if ($convertTo12Hour) {
596         if($val['start'] != '')
597           $val['start'] = ttTimeHelper::to12HourFormat($val['start']);
598         if($val['finish'] != '')
599           $val['finish'] = ttTimeHelper::to12HourFormat($val['finish']);
600       }
601       if (isset($val['cost'])) {
602         if ('.' != $user->decimal_mark)
603           $val['cost'] = str_replace('.', $user->decimal_mark, $val['cost']);
604       }
605       if (isset($val['expense'])) {
606         if ('.' != $user->decimal_mark)
607           $val['expense'] = str_replace('.', $user->decimal_mark, $val['expense']);
608       }
609       if ('no_grouping' != $group_by_option) {
610         $val['grouped_by'] = $val[$group_by_option];
611         if ('date' == $group_by_option) {
612           // This is needed to get the date in user date format.
613           $o_date = new DateAndTime(DB_DATEFORMAT, $val['grouped_by']);
614           $val['grouped_by'] = $o_date->toString($user->date_format);
615           unset($o_date);
616         }
617       }
618
619       // This is needed to get the date in user date format.
620       $o_date = new DateAndTime(DB_DATEFORMAT, $val['date']);
621       $val['date'] = $o_date->toString($user->date_format);
622       unset($o_date);
623
624       $row = $val;
625       $report_items[] = $row;
626     }
627
628     return $report_items;
629   }
630
631   // getSubtotals calculates report items subtotals when a report is grouped by.
632   // Without expenses, it's a simple select with group by.
633   // With expenses, it becomes a select with group by from a combined set of records obtained with "union all".
634   static function getSubtotals($bean) {
635         global $user;
636         
637     $group_by_option = $bean->getAttribute('group_by');
638     if ('no_grouping' == $group_by_option) return null;
639     
640     $mdb2 = getConnection();
641     
642     // Start with sql to obtain subtotals for time items. This simple sql will be used when we have no expenses.
643     
644     // Determine group by field and a required join.
645     switch ($group_by_option) {
646           case 'date':
647         $group_field = 'l.date';
648         $group_join = '';
649         break;
650       case 'user':
651         $group_field = 'u.name';
652         $group_join = 'left join tt_users u on (l.user_id = u.id) ';
653         break;
654       case 'client':
655         $group_field = 'c.name';
656         $group_join = 'left join tt_clients c on (l.client_id = c.id) ';
657         break;
658       case 'project':
659             $group_field = 'p.name';
660         $group_join = 'left join tt_projects p on (l.project_id = p.id) ';
661             break;
662       case 'task':
663             $group_field = 't.name';
664         $group_join = 'left join tt_tasks t on (l.task_id = t.id) ';
665             break;
666       case 'cf_1':
667             $group_field = 'cfo.value';
668             $custom_fields = new CustomFields($user->team_id);
669             if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_TEXT)
670           $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) ';
671         elseif ($custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN)
672           $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) ';
673           break;
674     }
675
676     $where = ttReportHelper::getWhere($bean);
677     if ($bean->getAttribute('chcost')) {
678       if (MODE_TIME == $user->tracking_mode) {
679         if ($group_by_option != 'user')
680           $left_join = 'left join tt_users u on (l.user_id = u.id)';
681         $sql = "select $group_field as group_field, sum(time_to_sec(l.duration)) as time, 
682           sum(cast(l.billable * coalesce(u.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10, 2))) as cost,
683           null as expenses from tt_log l
684           $group_join $left_join $where group by $group_field";         
685       } else {
686         // If we are including cost and tracking projects, our query (the same as above) needs to join the tt_user_project_binds table.
687         $sql = "select $group_field as group_field, sum(time_to_sec(l.duration)) as time, 
688           sum(cast(l.billable * coalesce(upb.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
691           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";
692       }
693     } else {
694            $sql = "select $group_field as group_field, sum(time_to_sec(l.duration)) as time, null as expenses from tt_log l 
695          $group_join $where group by $group_field";
696     }
697     // By now we have sql for time items.
698     
699     // However, when we have expenses, we need to do a union with a separate query for expense items from tt_expense_items table.
700     if ($bean->getAttribute('chcost') && in_array('ex', explode(',', $user->plugins))) { // if ex(penses) plugin is enabled
701         
702       // Determine group by field and a required join.
703       $group_join = null;
704       $group_field = 'null';
705       switch ($group_by_option) {
706             case 'date':
707           $group_field = 'ei.date';
708           $group_join = '';
709           break;
710         case 'user':
711           $group_field = 'u.name';
712           $group_join = 'left join tt_users u on (ei.user_id = u.id) ';
713           break;
714         case 'client':
715           $group_field = 'c.name';
716           $group_join = 'left join tt_clients c on (ei.client_id = c.id) ';
717           break;
718         case 'project':
719               $group_field = 'p.name';
720           $group_join = 'left join tt_projects p on (ei.project_id = p.id) ';
721               break;
722       }
723
724       $where = ttReportHelper::getExpenseWhere($bean);
725       $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 
726         $group_join $where";
727       // Add a "group by" clause if we are grouping.
728       if ('null' != $group_field) $sql_for_expenses .= " group by $group_field";
729          
730       // Create a combined query.
731       $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";
732     }
733     
734     // Execute query.
735     $res = $mdb2->query($sql);
736     if (!is_a($res, 'PEAR_Error')) {
737           while ($val = $res->fetchRow()) {
738                 if ('date' == $group_by_option) {
739           // This is needed to get the date in user date format.
740           $o_date = new DateAndTime(DB_DATEFORMAT, $val['group_field']);
741           $val['group_field'] = $o_date->toString($user->date_format);
742           unset($o_date);
743                 }
744                 $time = $val['time'] ? sec_to_time_fmt_hm($val['time']) : null;
745         if ($bean->getAttribute('chcost')) {
746               if ('.' != $user->decimal_mark) {
747                 $val['cost'] = str_replace('.', $user->decimal_mark, $val['cost']);
748                 $val['expenses'] = str_replace('.', $user->decimal_mark, $val['expenses']);
749               }
750           $subtotals[$val['group_field']] = array('name'=>$val['group_field'],'time'=>$time,'cost'=>$val['cost'],'expenses'=>$val['expenses']);
751         } else
752           $subtotals[$val['group_field']] = array('name'=>$val['group_field'],'time'=>$time);
753       }
754     } else
755       die($res->getMessage());
756
757     return $subtotals;
758   }
759   
760   // getFavSubtotals calculates report items subtotals when a favorite report is grouped by.
761   // Without expenses, it's a simple select with group by.
762   // With expenses, it becomes a select with group by from a combined set of records obtained with "union all".
763   static function getFavSubtotals($report) {
764         global $user;
765         
766     $group_by_option = $report['group_by'];
767     if ('no_grouping' == $group_by_option) return null;
768     
769     $mdb2 = getConnection();
770     
771     // Start with sql to obtain subtotals for time items. This simple sql will be used when we have no expenses.
772     
773     // Determine group by field and a required join.
774     switch ($group_by_option) {
775           case 'date':
776         $group_field = 'l.date';
777         $group_join = '';
778         break;
779       case 'user':
780         $group_field = 'u.name';
781         $group_join = 'left join tt_users u on (l.user_id = u.id) ';
782         break;
783       case 'client':
784         $group_field = 'c.name';
785         $group_join = 'left join tt_clients c on (l.client_id = c.id) ';
786         break;
787       case 'project':
788             $group_field = 'p.name';
789         $group_join = 'left join tt_projects p on (l.project_id = p.id) ';
790             break;
791       case 'task':
792             $group_field = 't.name';
793         $group_join = 'left join tt_tasks t on (l.task_id = t.id) ';
794             break;
795       case 'cf_1':
796             $group_field = 'cfo.value';
797             $custom_fields = new CustomFields($user->team_id);
798             if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_TEXT)
799           $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) ';
800         elseif ($custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN)
801           $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) ';
802           break;
803     }
804
805     $where = ttReportHelper::getFavWhere($report);
806     if ($report['show_cost']) {
807       if (MODE_TIME == $user->tracking_mode) {
808         if ($group_by_option != 'user')
809           $left_join = 'left join tt_users u on (l.user_id = u.id)';
810         $sql = "select $group_field as group_field, sum(time_to_sec(l.duration)) as time, 
811           sum(cast(l.billable * coalesce(u.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10, 2))) as cost,
812           null as expenses from tt_log l
813           $group_join $left_join $where group by $group_field";         
814       } else {
815         // If we are including cost and tracking projects, our query (the same as above) needs to join the tt_user_project_binds table.
816         $sql = "select $group_field as group_field, sum(time_to_sec(l.duration)) as time, 
817           sum(cast(l.billable * coalesce(upb.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10,2))) as cost,
818           null as expenses from tt_log l 
819           $group_join
820           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";
821       }
822     } else {
823            $sql = "select $group_field as group_field, sum(time_to_sec(l.duration)) as time, null as expenses from tt_log l 
824          $group_join $where group by $group_field";
825     }
826     // By now we have sql for time items.
827     
828     // However, when we have expenses, we need to do a union with a separate query for expense items from tt_expense_items table.
829     if ($report['show_cost'] && in_array('ex', explode(',', $user->plugins))) { // if ex(penses) plugin is enabled
830         
831       // Determine group by field and a required join.
832       $group_join = null;
833       $group_field = 'null';
834       switch ($group_by_option) {
835             case 'date':
836           $group_field = 'ei.date';
837           $group_join = '';
838           break;
839         case 'user':
840           $group_field = 'u.name';
841           $group_join = 'left join tt_users u on (ei.user_id = u.id) ';
842           break;
843         case 'client':
844           $group_field = 'c.name';
845           $group_join = 'left join tt_clients c on (ei.client_id = c.id) ';
846           break;
847         case 'project':
848               $group_field = 'p.name';
849           $group_join = 'left join tt_projects p on (ei.project_id = p.id) ';
850               break;
851       }
852
853       $where = ttReportHelper::getFavExpenseWhere($report);
854       $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 
855         $group_join $where";
856       // Add a "group by" clause if we are grouping.
857       if ('null' != $group_field) $sql_for_expenses .= " group by $group_field";
858          
859       // Create a combined query.
860       $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";
861     }
862     
863     // Execute query.
864     $res = $mdb2->query($sql);
865     if (!is_a($res, 'PEAR_Error')) {
866           while ($val = $res->fetchRow()) {
867                 if ('date' == $group_by_option) {
868           // This is needed to get the date in user date format.
869           $o_date = new DateAndTime(DB_DATEFORMAT, $val['group_field']);
870           $val['group_field'] = $o_date->toString($user->date_format);
871           unset($o_date);
872                 }
873                 $time = $val['time'] ? sec_to_time_fmt_hm($val['time']) : null;
874         if ($report['show_cost']) {
875               if ('.' != $user->decimal_mark) {
876                 $val['cost'] = str_replace('.', $user->decimal_mark, $val['cost']);
877                 $val['expenses'] = str_replace('.', $user->decimal_mark, $val['expenses']);
878               }
879           $subtotals[$val['group_field']] = array('name'=>$val['group_field'],'time'=>$time,'cost'=>$val['cost'],'expenses'=>$val['expenses']);
880         } else
881           $subtotals[$val['group_field']] = array('name'=>$val['group_field'],'time'=>$time);
882       }
883     } else
884       die($res->getMessage());
885
886     return $subtotals;
887   }
888   
889   // getTotals calculates total hours and cost for all report items.
890   static function getTotals($bean)
891   {
892     global $user;
893     
894     $mdb2 = getConnection();
895     
896     $where = ttReportHelper::getWhere($bean);
897         
898     // Start with a query for time items.
899     if ($bean->getAttribute('chcost')) {
900       if (MODE_TIME == $user->tracking_mode) {
901         $sql = "select sum(time_to_sec(l.duration)) as time,
902           sum(cast(l.billable * coalesce(u.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10,2))) as cost,
903           null as expenses 
904           from tt_log l
905           left join tt_users u on (l.user_id = u.id) $where";
906       } else {
907         $sql = "select sum(time_to_sec(l.duration)) as time,
908           sum(cast(l.billable * coalesce(upb.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10,2))) as cost,
909           null as expenses
910           from tt_log l
911           left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id) $where";   
912       }
913     } else
914       $sql = "select sum(time_to_sec(l.duration)) as time, null as cost, null as expenses from tt_log l $where";
915       
916     // If we have expenses, query becomes a bit more complex.
917     if ($bean->getAttribute('chcost') && in_array('ex', explode(',', $user->plugins))) {
918       $where = ttReportHelper::getExpenseWhere($bean);
919       $sql_for_expenses = "select null as time, sum(cost) as cost, sum(cost) as expenses from tt_expense_items ei $where";
920       // Create a combined query.
921       $sql = "select sum(time) as time, sum(cost) as cost, sum(expenses) as expenses from (($sql) union all ($sql_for_expenses)) t";
922         }
923
924         // Execute query.
925     $res = $mdb2->query($sql);
926     if (!is_a($res, 'PEAR_Error')) {
927       $val = $res->fetchRow();
928       $total_time = $val['time'] ? sec_to_time_fmt_hm($val['time']) : null;
929       if ($bean->getAttribute('chcost')) {
930         $total_cost = $val['cost'];
931         if (!$total_cost) $total_cost = '0.00';
932         if ('.' != $user->decimal_mark)
933               $total_cost = str_replace('.', $user->decimal_mark, $total_cost);
934               
935             $total_expenses = $val['expenses'];
936         if (!$total_expenses) $total_expenses = '0.00';
937         if ('.' != $user->decimal_mark)
938               $total_expenses = str_replace('.', $user->decimal_mark, $total_expenses);
939       }
940     } else
941       die($res->getMessage());
942       
943     if ($bean->getAttribute('period'))
944       $period = new Period($bean->getAttribute('period'), new DateAndTime($user->date_format));
945     else {
946       $period = new Period();
947       $period->setPeriod(
948         new DateAndTime($user->date_format, $bean->getAttribute('start_date')),
949         new DateAndTime($user->date_format, $bean->getAttribute('end_date')));
950     }
951
952     $totals['start_date'] = $period->getBeginDate();
953         $totals['end_date'] = $period->getEndDate();
954         $totals['time'] = $total_time;
955         $totals['cost'] = $total_cost;
956         $totals['expenses'] = $total_expenses;
957
958     return $totals;
959   }
960   
961   // getFavTotals calculates total hours and cost for all favorite report items.
962   static function getFavTotals($report)
963   {
964     global $user;
965     
966     $mdb2 = getConnection();
967     
968     $where = ttReportHelper::getFavWhere($report);
969         
970     // Start with a query for time items.
971     if ($report['show_cost']) {
972       if (MODE_TIME == $user->tracking_mode) {
973         $sql = "select sum(time_to_sec(l.duration)) as time,
974           sum(cast(l.billable * coalesce(u.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10,2))) as cost,
975           null as expenses 
976           from tt_log l
977           left join tt_users u on (l.user_id = u.id) $where";
978       } else {
979         $sql = "select sum(time_to_sec(l.duration)) as time,
980           sum(cast(l.billable * coalesce(upb.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10,2))) as cost,
981           null as expenses
982           from tt_log l
983           left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id) $where";   
984       }
985     } else
986       $sql = "select sum(time_to_sec(l.duration)) as time, null as cost, null as expenses from tt_log l $where";
987       
988     // If we have expenses, query becomes a bit more complex.
989     if ($report['show_cost'] && in_array('ex', explode(',', $user->plugins))) {
990       $where = ttReportHelper::getFavExpenseWhere($report);
991       $sql_for_expenses = "select null as time, sum(cost) as cost, sum(cost) as expenses from tt_expense_items ei $where";
992       // Create a combined query.
993       $sql = "select sum(time) as time, sum(cost) as cost, sum(expenses) as expenses from (($sql) union all ($sql_for_expenses)) t";
994         }
995
996         // Execute query.
997     $res = $mdb2->query($sql);
998     if (!is_a($res, 'PEAR_Error')) {
999       $val = $res->fetchRow();
1000       $total_time = $val['time'] ? sec_to_time_fmt_hm($val['time']) : null;
1001       if ($report['show_cost']) {
1002         $total_cost = $val['cost'];
1003         if (!$total_cost) $total_cost = '0.00';
1004         if ('.' != $user->decimal_mark)
1005               $total_cost = str_replace('.', $user->decimal_mark, $total_cost);
1006               
1007             $total_expenses = $val['expenses'];
1008         if (!$total_expenses) $total_expenses = '0.00';
1009         if ('.' != $user->decimal_mark)
1010               $total_expenses = str_replace('.', $user->decimal_mark, $total_expenses);
1011       }
1012     } else
1013       die($res->getMessage());
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->getBeginDate();
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'))
1042             die($affected->getMessage());
1043         }
1044     if ($expense_item_ids) {
1045       $sql = "update tt_expense_items set invoice_id = ".$mdb2->quote($invoice_id).
1046         " where id in(".join(', ', $expense_item_ids).")";
1047       $affected = $mdb2->exec($sql);
1048       if (is_a($affected, 'PEAR_Error'))
1049             die($affected->getMessage());
1050         }
1051   }
1052
1053   // prepareReportBody - prepares an email body for report.
1054   static function prepareReportBody($bean, $comment)
1055   {
1056     global $user;
1057     global $i18n;
1058
1059     $items = ttReportHelper::getItems($bean);
1060     $group_by = $bean->getAttribute('group_by');
1061     if ($group_by && 'no_grouping' != $group_by)
1062       $subtotals = ttReportHelper::getSubtotals($bean);
1063     $totals = ttReportHelper::getTotals($bean);
1064     
1065     // Use custom fields plugin if it is enabled.
1066     if (in_array('cf', explode(',', $user->plugins)))
1067       $custom_fields = new CustomFields($user->team_id);
1068
1069     // Define some styles to use in email.
1070     $style_title = 'text-align: center; font-size: 15pt; font-family: Arial, Helvetica, sans-serif;';
1071     $tableHeader = 'font-weight: bold; background-color: #a6ccf7; text-align: left;';
1072     $tableHeaderCentered = 'font-weight: bold; background-color: #a6ccf7; text-align: center;';
1073     $rowItem = 'background-color: #ccccce;';
1074     $rowItemAlt = 'background-color: #f5f5f5;';
1075     $rowSubtotal = 'background-color: #e0e0e0;';
1076     $cellLeftAligned = 'text-align: left; vertical-align: top;';
1077     $cellRightAligned = 'text-align: right; vertical-align: top;';
1078     $cellLeftAlignedSubtotal = 'font-weight: bold; text-align: left; vertical-align: top;';
1079     $cellRightAlignedSubtotal = 'font-weight: bold; text-align: right; vertical-align: top;';
1080     
1081     // Start creating email body.
1082     $body = '<html>';
1083     $body .= '<head><meta http-equiv="content-type" content="text/html; charset='.CHARSET.'"></head>';
1084     $body .= '<body>';
1085     
1086     // Output title.
1087     $body .= '<p style="'.$style_title.'">'.$i18n->getKey('form.mail.report_subject').': '.$totals['start_date'].' - '.$totals['end_date'].'</p>';
1088     
1089     // Output comment.
1090     if ($comment) $body .= '<p>'.htmlspecialchars($comment).'</p>';
1091
1092     if ($bean->getAttribute('chtotalsonly')) {
1093       // Totals only report. Output subtotals.
1094       
1095       // Determine group_by header.
1096       if ('cf_1' == $group_by)
1097         $group_by_header = htmlspecialchars($custom_fields->fields[0]['label']);
1098       else {
1099         $key = 'label.'.$group_by;
1100         $group_by_header = $i18n->getKey($key);
1101       }
1102         
1103       $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
1104       $body .= '<tr>';
1105       $body .= '<td style="'.$tableHeader.'">'.$group_by_header.'</td>';
1106       if ($bean->getAttribute('chduration'))
1107         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->getKey('label.duration').'</td>';
1108       if ($bean->getAttribute('chcost'))
1109         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->getKey('label.cost').'</td>';
1110       $body .= '</tr>';
1111       foreach($subtotals as $subtotal) {
1112         $body .= '<tr style="'.$rowSubtotal.'">';
1113         $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($subtotal['name'] ? htmlspecialchars($subtotal['name']) : '&nbsp;').'</td>';
1114         if ($bean->getAttribute('chduration')) {
1115           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1116           if ($subtotal['time'] <> '0:00') $body .= $subtotal['time'];
1117           $body .= '</td>';
1118         }
1119         if ($bean->getAttribute('chcost')) {
1120           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1121           $body .= ($user->canManageTeam() || $user->isClient()) ? $subtotal['cost'] : $subtotal['expenses'];
1122           $body .= '</td>';
1123         }
1124         $body .= '</tr>';
1125       }
1126       
1127       // Print totals.
1128       $body .= '<tr><td>&nbsp;</td></tr>';
1129       $body .= '<tr style="'.$rowSubtotal.'">';
1130       $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->getKey('label.total').'</td>';
1131       if ($bean->getAttribute('chduration')) {
1132         $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1133         if ($totals['time'] <> '0:00') $body .= $totals['time'];
1134         $body .= '</td>';
1135       }
1136       if ($bean->getAttribute('chcost')) {
1137         $body .= '<td nowrap style="'.$cellRightAlignedSubtotal.'">'.htmlspecialchars($user->currency).' ';
1138         $body .= ($user->canManageTeam() || $user->isClient()) ? $totals['cost'] : $totals['expenses'];
1139         $body .= '</td>';
1140       }
1141       $body .= '</tr>';
1142        
1143       $body .= '</table>';
1144     } else {
1145       // Regular report.
1146       
1147       // Print table header.
1148       $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
1149       $body .= '<tr>';
1150       $body .= '<td style="'.$tableHeader.'">'.$i18n->getKey('label.date').'</td>';
1151       if ($user->canManageTeam() || $user->isClient())
1152         $body .= '<td style="'.$tableHeader.'">'.$i18n->getKey('label.user').'</td>';
1153       if ($bean->getAttribute('chclient'))
1154         $body .= '<td style="'.$tableHeader.'">'.$i18n->getKey('label.client').'</td>';
1155       if ($bean->getAttribute('chproject'))
1156         $body .= '<td style="'.$tableHeader.'">'.$i18n->getKey('label.project').'</td>';
1157       if ($bean->getAttribute('chtask'))
1158         $body .= '<td style="'.$tableHeader.'">'.$i18n->getKey('label.task').'</td>';
1159       if ($bean->getAttribute('chcf_1'))
1160         $body .= '<td style="'.$tableHeader.'">'.htmlspecialchars($custom_fields->fields[0]['label']).'</td>';
1161       if ($bean->getAttribute('chstart'))
1162         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->getKey('label.start').'</td>';
1163       if ($bean->getAttribute('chfinish'))
1164         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->getKey('label.finish').'</td>';
1165       if ($bean->getAttribute('chduration'))
1166         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->getKey('label.duration').'</td>';
1167       if ($bean->getAttribute('chnote'))
1168         $body .= '<td style="'.$tableHeader.'">'.$i18n->getKey('label.note').'</td>';
1169       if ($bean->getAttribute('chcost'))
1170         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->getKey('label.cost').'</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('chinvoice')) $body .= '<td></td>';
1213               $body .= '</tr>';
1214               $body .= '<tr><td>&nbsp;</td></tr>';
1215             }
1216             $first_pass = false;
1217           }
1218           
1219           // Print a regular row.
1220           if ($cur_date != $prev_date)
1221             $row_style = ($row_style == $rowItem) ? $rowItemAlt : $rowItem;
1222           $body .= '<tr style="'.$row_style.'">';
1223           $body .= '<td style="'.$cellLeftAligned.'">'.$record['date'].'</td>';
1224           if ($user->canManageTeam() || $user->isClient())
1225             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['user']).'</td>';
1226           if ($bean->getAttribute('chclient'))
1227             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['client']).'</td>';
1228           if ($bean->getAttribute('chproject'))
1229             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['project']).'</td>';
1230           if ($bean->getAttribute('chtask'))
1231             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['task']).'</td>';
1232           if ($bean->getAttribute('chcf_1'))
1233             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['cf_1']).'</td>';
1234           if ($bean->getAttribute('chstart'))
1235             $body .= '<td nowrap style="'.$cellRightAligned.'">'.$record['start'].'</td>';
1236           if ($bean->getAttribute('chfinish'))
1237             $body .= '<td nowrap style="'.$cellRightAligned.'">'.$record['finish'].'</td>';
1238           if ($bean->getAttribute('chduration'))
1239             $body .= '<td style="'.$cellRightAligned.'">'.$record['duration'].'</td>';
1240           if ($bean->getAttribute('chnote'))
1241             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['note']).'</td>';
1242           if ($bean->getAttribute('chcost'))
1243             $body .= '<td style="'.$cellRightAligned.'">'.$record['cost'].'</td>';
1244           if ($bean->getAttribute('chinvoice'))
1245             $body .= '<td style="'.$cellRightAligned.'">'.htmlspecialchars($record['invoice']).'</td>';
1246           $body .= '</tr>';
1247           
1248           $prev_date = $record['date'];
1249           if ($print_subtotals)
1250             $prev_grouped_by = $record['grouped_by'];
1251         }
1252       }
1253       
1254       // Print a terminating subtotal.
1255       if ($print_subtotals) {
1256         $body .= '<tr style="'.$rowSubtotal.'">';
1257         $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->getKey('label.subtotal').'</td>';
1258         $subtotal_name = htmlspecialchars($subtotals[$cur_grouped_by]['name']);
1259         if ($user->canManageTeam() || $user->isClient()) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'user' ? $subtotal_name : '').'</td>';
1260         if ($bean->getAttribute('chclient')) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'client' ? $subtotal_name : '').'</td>';
1261         if ($bean->getAttribute('chproject')) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'project' ? $subtotal_name : '').'</td>';
1262         if ($bean->getAttribute('chtask')) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'task' ? $subtotal_name : '').'</td>';
1263         if ($bean->getAttribute('chcf_1')) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'cf_1' ? $subtotal_name : '').'</td>';
1264         if ($bean->getAttribute('chstart')) $body .= '<td></td>';
1265         if ($bean->getAttribute('chfinish')) $body .= '<td></td>';
1266         if ($bean->getAttribute('chduration')) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$cur_grouped_by]['time'].'</td>';
1267         if ($bean->getAttribute('chnote')) $body .= '<td></td>';
1268         if ($bean->getAttribute('chcost')) {
1269           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1270           $body .= ($user->canManageTeam() || $user->isClient()) ? $subtotals[$cur_grouped_by]['cost'] : $subtotals[$cur_grouped_by]['expenses'];
1271           $body .= '</td>';
1272         }
1273         if ($bean->getAttribute('chinvoice')) $body .= '<td></td>';
1274         $body .= '</tr>';
1275       }
1276       
1277       // Print totals.
1278       $body .= '<tr><td>&nbsp;</td></tr>';
1279       $body .= '<tr style="'.$rowSubtotal.'">';
1280       $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->getKey('label.total').'</td>';
1281       if ($user->canManageTeam() || $user->isClient()) $body .= '<td></td>';
1282       if ($bean->getAttribute('chclient')) $body .= '<td></td>';
1283       if ($bean->getAttribute('chproject')) $body .= '<td></td>';
1284       if ($bean->getAttribute('chtask')) $body .= '<td></td>';
1285       if ($bean->getAttribute('chcf_1')) $body .= '<td></td>';
1286       if ($bean->getAttribute('chstart')) $body .= '<td></td>';
1287       if ($bean->getAttribute('chfinish')) $body .= '<td></td>';
1288       if ($bean->getAttribute('chduration')) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$totals['time'].'</td>';
1289       if ($bean->getAttribute('chnote')) $body .= '<td></td>';
1290       if ($bean->getAttribute('chcost')) {
1291         $body .= '<td nowrap style="'.$cellRightAlignedSubtotal.'">'.htmlspecialchars($user->currency).' ';
1292         $body .= ($user->canManageTeam() || $user->isClient()) ? $totals['cost'] : $totals['expenses'];
1293         $body .= '</td>';
1294       }
1295       if ($bean->getAttribute('chinvoice')) $body .= '<td></td>';
1296       $body .= '</tr>';
1297       
1298       $body .= '</table>';
1299     }
1300     
1301     // Output footer.
1302     if (!defined('REPORT_FOOTER') || !(REPORT_FOOTER == false))
1303       $body .= '<p style="text-align: center;">'.$i18n->getKey('form.mail.footer').'</p>';
1304
1305     // Finish creating email body.
1306     $body .= '</body></html>';
1307
1308     return $body;
1309   }
1310   
1311 // prepareFavReportBody - prepares an email body for a favorite report.
1312   static function prepareFavReportBody($report)
1313   {
1314         global $user;
1315         global $i18n;
1316         
1317         $items = ttReportHelper::getFavItems($report);
1318     $group_by = $report['group_by'];
1319         if ($group_by && 'no_grouping' != $group_by)
1320         $subtotals = ttReportHelper::getFavSubtotals($report);    
1321     $totals = ttReportHelper::getFavTotals($report);            
1322         
1323     // Use custom fields plugin if it is enabled.
1324     if (in_array('cf', explode(',', $user->plugins)))
1325       $custom_fields = new CustomFields($user->team_id);
1326
1327     // Define some styles to use in email.
1328     $style_title = 'text-align: center; font-size: 15pt; font-family: Arial, Helvetica, sans-serif;';
1329     $tableHeader = 'font-weight: bold; background-color: #a6ccf7; text-align: left;';
1330     $tableHeaderCentered = 'font-weight: bold; background-color: #a6ccf7; text-align: center;';
1331     $rowItem = 'background-color: #ccccce;';
1332     $rowItemAlt = 'background-color: #f5f5f5;';
1333     $rowSubtotal = 'background-color: #e0e0e0;';
1334     $cellLeftAligned = 'text-align: left; vertical-align: top;';
1335     $cellRightAligned = 'text-align: right; vertical-align: top;';
1336     $cellLeftAlignedSubtotal = 'font-weight: bold; text-align: left; vertical-align: top;';
1337     $cellRightAlignedSubtotal = 'font-weight: bold; text-align: right; vertical-align: top;';
1338     
1339     // Start creating email body.
1340     $body = '<html>';
1341     $body .= '<head><meta http-equiv="content-type" content="text/html; charset='.CHARSET.'"></head>';
1342     $body .= '<body>';
1343     
1344     // Output title.
1345     $body .= '<p style="'.$style_title.'">'.$i18n->getKey('form.mail.report_subject').': '.$totals['start_date'].' - '.$totals['end_date'].'</p>';
1346
1347     // Output comment.
1348     // if ($comment) $body .= '<p>'.htmlspecialchars($comment).'</p>'; // No comment for fav. reports.
1349
1350     if ($report['show_totals_only']) {
1351       // Totals only report. Output subtotals.
1352       
1353       // Determine group_by header.
1354       if ('cf_1' == $group_by)
1355         $group_by_header = htmlspecialchars($custom_fields->fields[0]['label']);
1356       else {
1357         $key = 'label.'.$group_by;
1358         $group_by_header = $i18n->getKey($key);
1359       }
1360         
1361       $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
1362       $body .= '<tr>';
1363       $body .= '<td style="'.$tableHeader.'">'.$group_by_header.'</td>';
1364       if ($report['show_duration'])
1365         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->getKey('label.duration').'</td>';
1366       if ($report['show_cost'])
1367         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->getKey('label.cost').'</td>';
1368       $body .= '</tr>';
1369       foreach($subtotals as $subtotal) {
1370         $body .= '<tr style="'.$rowSubtotal.'">';
1371         $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($subtotal['name'] ? htmlspecialchars($subtotal['name']) : '&nbsp;').'</td>';
1372         if ($report['show_duration']) {
1373           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1374           if ($subtotal['time'] <> '0:00') $body .= $subtotal['time'];
1375           $body .= '</td>';
1376         }
1377         if ($report['show_cost']) {
1378           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1379           $body .= ($user->canManageTeam() || $user->isClient()) ? $subtotal['cost'] : $subtotal['expenses'];
1380           $body .= '</td>';
1381         }
1382         $body .= '</tr>';
1383       }
1384       
1385       // Print totals.
1386       $body .= '<tr><td>&nbsp;</td></tr>';
1387       $body .= '<tr style="'.$rowSubtotal.'">';
1388       $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->getKey('label.total').'</td>';
1389       if ($report['show_duration']) {
1390         $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1391         if ($totals['time'] <> '0:00') $body .= $totals['time'];
1392         $body .= '</td>';
1393       }
1394       if ($report['show_cost']) {
1395         $body .= '<td nowrap style="'.$cellRightAlignedSubtotal.'">'.htmlspecialchars($user->currency).' ';
1396         $body .= ($user->canManageTeam() || $user->isClient()) ? $totals['cost'] : $totals['expenses'];
1397         $body .= '</td>';
1398       }
1399       $body .= '</tr>';
1400        
1401       $body .= '</table>';
1402     } else {
1403       // Regular report.
1404       
1405       // Print table header.
1406       $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
1407       $body .= '<tr>';
1408       $body .= '<td style="'.$tableHeader.'">'.$i18n->getKey('label.date').'</td>';
1409       if ($user->canManageTeam() || $user->isClient())
1410         $body .= '<td style="'.$tableHeader.'">'.$i18n->getKey('label.user').'</td>';
1411       if ($report['show_client'])
1412         $body .= '<td style="'.$tableHeader.'">'.$i18n->getKey('label.client').'</td>';
1413       if ($report['show_project'])
1414         $body .= '<td style="'.$tableHeader.'">'.$i18n->getKey('label.project').'</td>';
1415       if ($report['show_task'])
1416         $body .= '<td style="'.$tableHeader.'">'.$i18n->getKey('label.task').'</td>';
1417       if ($report['show_custom_field_1'])
1418         $body .= '<td style="'.$tableHeader.'">'.htmlspecialchars($custom_fields->fields[0]['label']).'</td>';
1419       if ($report['show_start'])
1420         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->getKey('label.start').'</td>';
1421       if ($report['show_end'])
1422         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->getKey('label.finish').'</td>';
1423       if ($report['show_duration'])
1424         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->getKey('label.duration').'</td>';
1425       if ($report['show_note'])
1426         $body .= '<td style="'.$tableHeader.'">'.$i18n->getKey('label.note').'</td>';
1427       if ($report['show_cost'])
1428         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->getKey('label.cost').'</td>';
1429       if ($report['show_invoice'])
1430         $body .= '<td style="'.$tableHeader.'">'.$i18n->getKey('label.invoice').'</td>';
1431       $body .= '</tr>';
1432       
1433       // Initialize variables to print subtotals.
1434       if ($items && 'no_grouping' != $group_by) {
1435         $print_subtotals = true;
1436         $first_pass = true;
1437         $prev_grouped_by = '';
1438         $cur_grouped_by = '';
1439       }
1440       // Initialize variables to alternate color of rows for different dates.
1441       $prev_date = '';
1442       $cur_date = '';
1443       $row_style = $rowItem;
1444       
1445       // Print report items.
1446       if (is_array($items)) {
1447         foreach ($items as $record) {
1448           $cur_date = $record['date'];
1449           // Print a subtotal row after a block of grouped items.
1450           if ($print_subtotals) {
1451             $cur_grouped_by = $record['grouped_by'];
1452             if ($cur_grouped_by != $prev_grouped_by && !$first_pass) {
1453               $body .= '<tr style="'.$rowSubtotal.'">';
1454               $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->getKey('label.subtotal').'</td>';
1455               $subtotal_name = htmlspecialchars($subtotals[$prev_grouped_by]['name']);
1456               if ($user->canManageTeam() || $user->isClient()) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'user' ? $subtotal_name : '').'</td>';
1457               if ($report['show_client']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'client' ? $subtotal_name : '').'</td>';
1458               if ($report['show_project']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'project' ? $subtotal_name : '').'</td>';
1459               if ($report['show_task']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'task' ? $subtotal_name : '').'</td>';
1460               if ($report['show_custom_field_1']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'cf_1' ? $subtotal_name : '').'</td>';
1461               if ($report['show_start']) $body .= '<td></td>';
1462               if ($report['show_end']) $body .= '<td></td>';
1463               if ($report['show_duration']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['time'].'</td>';
1464               if ($report['show_note']) $body .= '<td></td>';
1465               if ($report['show_cost']) {
1466                 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1467                 $body .= ($user->canManageTeam() || $user->isClient()) ? $subtotals[$prev_grouped_by]['cost'] : $subtotals[$prev_grouped_by]['expenses'];
1468                 $body .= '</td>';
1469               }
1470               if ($report['show_invoice']) $body .= '<td></td>';
1471               $body .= '</tr>';
1472               $body .= '<tr><td>&nbsp;</td></tr>';      
1473             }
1474             $first_pass = false;
1475           }
1476         
1477           // Print a regular row.
1478           if ($cur_date != $prev_date)
1479             $row_style = ($row_style == $rowItem) ? $rowItemAlt : $rowItem;
1480           $body .= '<tr style="'.$row_style.'">';
1481           $body .= '<td style="'.$cellLeftAligned.'">'.$record['date'].'</td>';
1482           if ($user->canManageTeam() || $user->isClient())
1483             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['user']).'</td>';
1484           if ($report['show_client'])
1485             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['client']).'</td>';
1486           if ($report['show_project'])
1487             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['project']).'</td>';
1488           if ($report['show_task'])
1489             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['task']).'</td>';
1490           if ($report['show_custom_field_1'])
1491             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['cf_1']).'</td>';
1492           if ($report['show_start'])
1493             $body .= '<td nowrap style="'.$cellRightAligned.'">'.$record['start'].'</td>';
1494           if ($report['show_end'])
1495             $body .= '<td nowrap style="'.$cellRightAligned.'">'.$record['finish'].'</td>';
1496           if ($report['show_duration'])
1497             $body .= '<td style="'.$cellRightAligned.'">'.$record['duration'].'</td>';
1498           if ($report['show_note'])
1499             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['note']).'</td>';
1500           if ($report['show_cost'])
1501             $body .= '<td style="'.$cellRightAligned.'">'.$record['cost'].'</td>';
1502           if ($report['show_invoice'])
1503             $body .= '<td style="'.$cellRightAligned.'">'.htmlspecialchars($record['invoice']).'</td>';
1504           $body .= '</tr>';
1505             
1506           $prev_date = $record['date'];
1507           if ($print_subtotals)
1508             $prev_grouped_by = $record['grouped_by'];
1509         }
1510       }
1511       
1512       // Print a terminating subtotal.
1513       if ($print_subtotals) {
1514         $body .= '<tr style="'.$rowSubtotal.'">';
1515         $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->getKey('label.subtotal').'</td>';
1516         $subtotal_name = htmlspecialchars($subtotals[$cur_grouped_by]['name']);
1517         if ($user->canManageTeam() || $user->isClient()) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'user' ? $subtotal_name : '').'</td>';
1518         if ($report['show_client']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'client' ? $subtotal_name : '').'</td>';
1519         if ($report['show_project']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'project' ? $subtotal_name : '').'</td>';
1520         if ($report['show_task']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'task' ? $subtotal_name : '').'</td>';
1521         if ($report['show_custom_field_1']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'cf_1' ? $subtotal_name : '').'</td>';
1522         if ($report['show_start']) $body .= '<td></td>';
1523         if ($report['show_end']) $body .= '<td></td>';
1524         if ($report['show_duration']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$cur_grouped_by]['time'].'</td>';
1525         if ($report['show_note']) $body .= '<td></td>';
1526         if ($report['show_cost']) {
1527           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1528           $body .= ($user->canManageTeam() || $user->isClient()) ? $subtotals[$cur_grouped_by]['cost'] : $subtotals[$cur_grouped_by]['expenses'];
1529           $body .= '</td>';
1530         }
1531         if ($report['show_invoice']) $body .= '<td></td>';
1532         $body .= '</tr>';
1533       }
1534       
1535       // Print totals.
1536       $body .= '<tr><td>&nbsp;</td></tr>';
1537       $body .= '<tr style="'.$rowSubtotal.'">';
1538       $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->getKey('label.total').'</td>';
1539       if ($user->canManageTeam() || $user->isClient()) $body .= '<td></td>';
1540       if ($report['show_client']) $body .= '<td></td>';
1541       if ($report['show_project']) $body .= '<td></td>';
1542       if ($report['show_task']) $body .= '<td></td>';
1543       if ($report['show_custom_field_1']) $body .= '<td></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.'">'.$totals['time'].'</td>';
1547       if ($report['show_note']) $body .= '<td></td>';
1548       if ($report['show_cost']) {
1549         $body .= '<td nowrap style="'.$cellRightAlignedSubtotal.'">'.htmlspecialchars($user->currency).' ';
1550         $body .= ($user->canManageTeam() || $user->isClient()) ? $totals['cost'] : $totals['expenses'];
1551         $body .= '</td>';
1552       }
1553       if ($report['show_invoice']) $body .= '<td></td>';
1554       $body .= '</tr>';
1555       
1556       $body .= '</table>';
1557     }
1558     
1559     // Output footer.
1560     if (!defined('REPORT_FOOTER') || !(REPORT_FOOTER == false))
1561       $body .= '<p style="text-align: center;">'.$i18n->getKey('form.mail.footer').'</p>';
1562
1563     // Finish creating email body.
1564     $body .= '</body></html>';
1565
1566     return $body;
1567   }
1568   
1569   // sendFavReport - sends a favorite report to a specified email, called from cron.php
1570   static function sendFavReport($report, $email) {
1571     // We are called from cron.php, we have no $bean in session.
1572     // cron.php set global $user and $i18n objects to match our favorite report user.
1573     global $user;
1574     global $i18n;
1575     
1576     // Prepare report body.
1577     $body = ttReportHelper::prepareFavReportBody($report);
1578                         
1579     import('mail.Mailer');
1580     $mailer = new Mailer();
1581     $mailer->setCharSet(CHARSET);
1582     $mailer->setContentType('text/html');
1583     $mailer->setSender(SENDER);
1584     $mailer->setReceiver($email);
1585     $mailer->setSendType(MAIL_MODE);
1586     if (!$mailer->send($report['name'], $body))
1587       return false;
1588       
1589     return true;
1590   }
1591 }