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