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