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