A bit more progress on roles revamp.
[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     $items = ttReportHelper::getItems($bean);
1125     $group_by = $bean->getAttribute('group_by');
1126     if ($group_by && 'no_grouping' != $group_by)
1127       $subtotals = ttReportHelper::getSubtotals($bean);
1128     $totals = ttReportHelper::getTotals($bean);
1129
1130     // Use custom fields plugin if it is enabled.
1131     if ($user->isPluginEnabled('cf'))
1132       $custom_fields = new CustomFields($user->team_id);
1133
1134     // Define some styles to use in email.
1135     $style_title = 'text-align: center; font-size: 15pt; font-family: Arial, Helvetica, sans-serif;';
1136     $tableHeader = 'font-weight: bold; background-color: #a6ccf7; text-align: left;';
1137     $tableHeaderCentered = 'font-weight: bold; background-color: #a6ccf7; text-align: center;';
1138     $rowItem = 'background-color: #ffffff;';
1139     $rowItemAlt = 'background-color: #f5f5f5;';
1140     $rowSubtotal = 'background-color: #e0e0e0;';
1141     $cellLeftAligned = 'text-align: left; vertical-align: top;';
1142     $cellRightAligned = 'text-align: right; vertical-align: top;';
1143     $cellLeftAlignedSubtotal = 'font-weight: bold; text-align: left; vertical-align: top;';
1144     $cellRightAlignedSubtotal = 'font-weight: bold; text-align: right; vertical-align: top;';
1145
1146     // Start creating email body.
1147     $body = '<html>';
1148     $body .= '<head><meta http-equiv="content-type" content="text/html; charset='.CHARSET.'"></head>';
1149     $body .= '<body>';
1150
1151     // Output title.
1152     $body .= '<p style="'.$style_title.'">'.$i18n->getKey('form.mail.report_subject').': '.$totals['start_date'].' - '.$totals['end_date'].'</p>';
1153
1154     // Output comment.
1155     if ($comment) $body .= '<p>'.htmlspecialchars($comment).'</p>';
1156
1157     if ($bean->getAttribute('chtotalsonly')) {
1158       // Totals only report. Output subtotals.
1159
1160       // Determine group_by header.
1161       if ('cf_1' == $group_by)
1162         $group_by_header = htmlspecialchars($custom_fields->fields[0]['label']);
1163       else {
1164         $key = 'label.'.$group_by;
1165         $group_by_header = $i18n->getKey($key);
1166       }
1167
1168       $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
1169       $body .= '<tr>';
1170       $body .= '<td style="'.$tableHeader.'">'.$group_by_header.'</td>';
1171       if ($bean->getAttribute('chduration'))
1172         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->getKey('label.duration').'</td>';
1173       if ($bean->getAttribute('chcost'))
1174         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->getKey('label.cost').'</td>';
1175       $body .= '</tr>';
1176       foreach($subtotals as $subtotal) {
1177         $body .= '<tr style="'.$rowSubtotal.'">';
1178         $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($subtotal['name'] ? htmlspecialchars($subtotal['name']) : '&nbsp;').'</td>';
1179         if ($bean->getAttribute('chduration')) {
1180           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1181           if ($subtotal['time'] <> '0:00') $body .= $subtotal['time'];
1182           $body .= '</td>';
1183         }
1184         if ($bean->getAttribute('chcost')) {
1185           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1186           $body .= ($user->canManageTeam() || $user->isClient()) ? $subtotal['cost'] : $subtotal['expenses'];
1187           $body .= '</td>';
1188         }
1189         $body .= '</tr>';
1190       }
1191
1192       // Print totals.
1193       $body .= '<tr><td>&nbsp;</td></tr>';
1194       $body .= '<tr style="'.$rowSubtotal.'">';
1195       $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->getKey('label.total').'</td>';
1196       if ($bean->getAttribute('chduration')) {
1197         $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1198         if ($totals['time'] <> '0:00') $body .= $totals['time'];
1199         $body .= '</td>';
1200       }
1201       if ($bean->getAttribute('chcost')) {
1202         $body .= '<td nowrap style="'.$cellRightAlignedSubtotal.'">'.htmlspecialchars($user->currency).' ';
1203         $body .= ($user->canManageTeam() || $user->isClient()) ? $totals['cost'] : $totals['expenses'];
1204         $body .= '</td>';
1205       }
1206       $body .= '</tr>';
1207
1208       $body .= '</table>';
1209     } else {
1210       // Regular report.
1211
1212       // Print table header.
1213       $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
1214       $body .= '<tr>';
1215       $body .= '<td style="'.$tableHeader.'">'.$i18n->getKey('label.date').'</td>';
1216       if ($user->canManageTeam() || $user->isClient())
1217         $body .= '<td style="'.$tableHeader.'">'.$i18n->getKey('label.user').'</td>';
1218       if ($bean->getAttribute('chclient'))
1219         $body .= '<td style="'.$tableHeader.'">'.$i18n->getKey('label.client').'</td>';
1220       if ($bean->getAttribute('chproject'))
1221         $body .= '<td style="'.$tableHeader.'">'.$i18n->getKey('label.project').'</td>';
1222       if ($bean->getAttribute('chtask'))
1223         $body .= '<td style="'.$tableHeader.'">'.$i18n->getKey('label.task').'</td>';
1224       if ($bean->getAttribute('chcf_1'))
1225         $body .= '<td style="'.$tableHeader.'">'.htmlspecialchars($custom_fields->fields[0]['label']).'</td>';
1226       if ($bean->getAttribute('chstart'))
1227         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->getKey('label.start').'</td>';
1228       if ($bean->getAttribute('chfinish'))
1229         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->getKey('label.finish').'</td>';
1230       if ($bean->getAttribute('chduration'))
1231         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->getKey('label.duration').'</td>';
1232       if ($bean->getAttribute('chnote'))
1233         $body .= '<td style="'.$tableHeader.'">'.$i18n->getKey('label.note').'</td>';
1234       if ($bean->getAttribute('chcost'))
1235         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->getKey('label.cost').'</td>';
1236       if ($bean->getAttribute('chpaid'))
1237         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->getKey('label.paid').'</td>';
1238       if ($bean->getAttribute('chinvoice'))
1239         $body .= '<td style="'.$tableHeader.'">'.$i18n->getKey('label.invoice').'</td>';
1240       $body .= '</tr>';
1241
1242       // Initialize variables to print subtotals.
1243       if ($items && 'no_grouping' != $group_by) {
1244         $print_subtotals = true;
1245         $first_pass = true;
1246         $prev_grouped_by = '';
1247         $cur_grouped_by = '';
1248       }
1249       // Initialize variables to alternate color of rows for different dates.
1250       $prev_date = '';
1251       $cur_date = '';
1252       $row_style = $rowItem;
1253
1254       // Print report items.
1255       if (is_array($items)) {
1256         foreach ($items as $record) {
1257           $cur_date = $record['date'];
1258           // Print a subtotal row after a block of grouped items.
1259           if ($print_subtotals) {
1260             $cur_grouped_by = $record['grouped_by'];
1261             if ($cur_grouped_by != $prev_grouped_by && !$first_pass) {
1262               $body .= '<tr style="'.$rowSubtotal.'">';
1263               $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->getKey('label.subtotal').'</td>';
1264               $subtotal_name = htmlspecialchars($subtotals[$prev_grouped_by]['name']);
1265               if ($user->canManageTeam() || $user->isClient()) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'user' ? $subtotal_name : '').'</td>';
1266               if ($bean->getAttribute('chclient')) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'client' ? $subtotal_name : '').'</td>';
1267               if ($bean->getAttribute('chproject')) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'project' ? $subtotal_name : '').'</td>';
1268               if ($bean->getAttribute('chtask')) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'task' ? $subtotal_name : '').'</td>';
1269               if ($bean->getAttribute('chcf_1')) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'cf_1' ? $subtotal_name : '').'</td>';
1270               if ($bean->getAttribute('chstart')) $body .= '<td></td>';
1271               if ($bean->getAttribute('chfinish')) $body .= '<td></td>';
1272               if ($bean->getAttribute('chduration')) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['time'].'</td>';
1273               if ($bean->getAttribute('chnote')) $body .= '<td></td>';
1274               if ($bean->getAttribute('chcost')) {
1275                 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1276                 $body .= ($user->canManageTeam() || $user->isClient()) ? $subtotals[$prev_grouped_by]['cost'] : $subtotals[$prev_grouped_by]['expenses'];
1277                 $body .= '</td>';
1278               }
1279               if ($bean->getAttribute('chpaid')) $body .= '<td></td>';
1280               if ($bean->getAttribute('chinvoice')) $body .= '<td></td>';
1281               $body .= '</tr>';
1282               $body .= '<tr><td>&nbsp;</td></tr>';
1283             }
1284             $first_pass = false;
1285           }
1286
1287           // Print a regular row.
1288           if ($cur_date != $prev_date)
1289             $row_style = ($row_style == $rowItem) ? $rowItemAlt : $rowItem;
1290           $body .= '<tr style="'.$row_style.'">';
1291           $body .= '<td style="'.$cellLeftAligned.'">'.$record['date'].'</td>';
1292           if ($user->canManageTeam() || $user->isClient())
1293             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['user']).'</td>';
1294           if ($bean->getAttribute('chclient'))
1295             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['client']).'</td>';
1296           if ($bean->getAttribute('chproject'))
1297             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['project']).'</td>';
1298           if ($bean->getAttribute('chtask'))
1299             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['task']).'</td>';
1300           if ($bean->getAttribute('chcf_1'))
1301             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['cf_1']).'</td>';
1302           if ($bean->getAttribute('chstart'))
1303             $body .= '<td nowrap style="'.$cellRightAligned.'">'.$record['start'].'</td>';
1304           if ($bean->getAttribute('chfinish'))
1305             $body .= '<td nowrap style="'.$cellRightAligned.'">'.$record['finish'].'</td>';
1306           if ($bean->getAttribute('chduration'))
1307             $body .= '<td style="'.$cellRightAligned.'">'.$record['duration'].'</td>';
1308           if ($bean->getAttribute('chnote'))
1309             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['note']).'</td>';
1310           if ($bean->getAttribute('chcost'))
1311             $body .= '<td style="'.$cellRightAligned.'">'.$record['cost'].'</td>';
1312           if ($bean->getAttribute('chpaid')) {
1313             $body .= '<td style="'.$cellRightAligned.'">';
1314             $body .= $record['paid'] == 1 ? $i18n->getKey('label.yes') : $i18n->getKey('label.no');
1315             $body .= '</td>';
1316           }
1317           if ($bean->getAttribute('chinvoice'))
1318             $body .= '<td style="'.$cellRightAligned.'">'.htmlspecialchars($record['invoice']).'</td>';
1319           $body .= '</tr>';
1320
1321           $prev_date = $record['date'];
1322           if ($print_subtotals)
1323             $prev_grouped_by = $record['grouped_by'];
1324         }
1325       }
1326
1327       // Print a terminating subtotal.
1328       if ($print_subtotals) {
1329         $body .= '<tr style="'.$rowSubtotal.'">';
1330         $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->getKey('label.subtotal').'</td>';
1331         $subtotal_name = htmlspecialchars($subtotals[$cur_grouped_by]['name']);
1332         if ($user->canManageTeam() || $user->isClient()) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'user' ? $subtotal_name : '').'</td>';
1333         if ($bean->getAttribute('chclient')) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'client' ? $subtotal_name : '').'</td>';
1334         if ($bean->getAttribute('chproject')) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'project' ? $subtotal_name : '').'</td>';
1335         if ($bean->getAttribute('chtask')) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'task' ? $subtotal_name : '').'</td>';
1336         if ($bean->getAttribute('chcf_1')) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'cf_1' ? $subtotal_name : '').'</td>';
1337         if ($bean->getAttribute('chstart')) $body .= '<td></td>';
1338         if ($bean->getAttribute('chfinish')) $body .= '<td></td>';
1339         if ($bean->getAttribute('chduration')) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$cur_grouped_by]['time'].'</td>';
1340         if ($bean->getAttribute('chnote')) $body .= '<td></td>';
1341         if ($bean->getAttribute('chcost')) {
1342           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1343           $body .= ($user->canManageTeam() || $user->isClient()) ? $subtotals[$cur_grouped_by]['cost'] : $subtotals[$cur_grouped_by]['expenses'];
1344           $body .= '</td>';
1345         }
1346         if ($bean->getAttribute('chpaid')) $body .= '<td></td>';
1347         if ($bean->getAttribute('chinvoice')) $body .= '<td></td>';
1348         $body .= '</tr>';
1349       }
1350
1351       // Print totals.
1352       $body .= '<tr><td>&nbsp;</td></tr>';
1353       $body .= '<tr style="'.$rowSubtotal.'">';
1354       $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->getKey('label.total').'</td>';
1355       if ($user->canManageTeam() || $user->isClient()) $body .= '<td></td>';
1356       if ($bean->getAttribute('chclient')) $body .= '<td></td>';
1357       if ($bean->getAttribute('chproject')) $body .= '<td></td>';
1358       if ($bean->getAttribute('chtask')) $body .= '<td></td>';
1359       if ($bean->getAttribute('chcf_1')) $body .= '<td></td>';
1360       if ($bean->getAttribute('chstart')) $body .= '<td></td>';
1361       if ($bean->getAttribute('chfinish')) $body .= '<td></td>';
1362       if ($bean->getAttribute('chduration')) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$totals['time'].'</td>';
1363       if ($bean->getAttribute('chnote')) $body .= '<td></td>';
1364       if ($bean->getAttribute('chcost')) {
1365         $body .= '<td nowrap style="'.$cellRightAlignedSubtotal.'">'.htmlspecialchars($user->currency).' ';
1366         $body .= ($user->canManageTeam() || $user->isClient()) ? $totals['cost'] : $totals['expenses'];
1367         $body .= '</td>';
1368       }
1369       if ($bean->getAttribute('chpaid')) $body .= '<td></td>';
1370       if ($bean->getAttribute('chinvoice')) $body .= '<td></td>';
1371       $body .= '</tr>';
1372
1373       $body .= '</table>';
1374     }
1375
1376     // Output footer.
1377     if (!defined('REPORT_FOOTER') || !(REPORT_FOOTER == false))
1378       $body .= '<p style="text-align: center;">'.$i18n->getKey('form.mail.footer').'</p>';
1379
1380     // Finish creating email body.
1381     $body .= '</body></html>';
1382
1383     return $body;
1384   }
1385
1386   // checkFavReportCondition - checks whether it is okay to send fav report.
1387   static function checkFavReportCondition($report, $condition)
1388   {
1389     $items = ttReportHelper::getFavItems($report);
1390
1391     $condition = str_replace('count', '', $condition);
1392     $count_required = (int) trim(str_replace('>', '', $condition));
1393
1394     if (count($items) > $count_required)
1395       return true; // Condition ok.
1396
1397     return false;
1398   }
1399
1400   // prepareFavReportBody - prepares an email body for a favorite report.
1401   static function prepareFavReportBody($report)
1402   {
1403     global $user;
1404     global $i18n;
1405
1406     $items = ttReportHelper::getFavItems($report);
1407     $group_by = $report['group_by'];
1408     if ($group_by && 'no_grouping' != $group_by)
1409       $subtotals = ttReportHelper::getFavSubtotals($report);
1410     $totals = ttReportHelper::getFavTotals($report);
1411
1412     // Use custom fields plugin if it is enabled.
1413     if ($user->isPluginEnabled('cf'))
1414       $custom_fields = new CustomFields($user->team_id);
1415
1416     // Define some styles to use in email.
1417     $style_title = 'text-align: center; font-size: 15pt; font-family: Arial, Helvetica, sans-serif;';
1418     $tableHeader = 'font-weight: bold; background-color: #a6ccf7; text-align: left;';
1419     $tableHeaderCentered = 'font-weight: bold; background-color: #a6ccf7; text-align: center;';
1420     $rowItem = 'background-color: #ffffff;';
1421     $rowItemAlt = 'background-color: #f5f5f5;';
1422     $rowSubtotal = 'background-color: #e0e0e0;';
1423     $cellLeftAligned = 'text-align: left; vertical-align: top;';
1424     $cellRightAligned = 'text-align: right; vertical-align: top;';
1425     $cellLeftAlignedSubtotal = 'font-weight: bold; text-align: left; vertical-align: top;';
1426     $cellRightAlignedSubtotal = 'font-weight: bold; text-align: right; vertical-align: top;';
1427
1428     // Start creating email body.
1429     $body = '<html>';
1430     $body .= '<head><meta http-equiv="content-type" content="text/html; charset='.CHARSET.'"></head>';
1431     $body .= '<body>';
1432
1433     // Output title.
1434     $body .= '<p style="'.$style_title.'">'.$i18n->getKey('form.mail.report_subject').': '.$totals['start_date'].' - '.$totals['end_date'].'</p>';
1435
1436     // Output comment.
1437     // if ($comment) $body .= '<p>'.htmlspecialchars($comment).'</p>'; // No comment for fav. reports.
1438
1439     if ($report['show_totals_only']) {
1440       // Totals only report. Output subtotals.
1441
1442       // Determine group_by header.
1443       if ('cf_1' == $group_by)
1444         $group_by_header = htmlspecialchars($custom_fields->fields[0]['label']);
1445       else {
1446         $key = 'label.'.$group_by;
1447         $group_by_header = $i18n->getKey($key);
1448       }
1449
1450       $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
1451       $body .= '<tr>';
1452       $body .= '<td style="'.$tableHeader.'">'.$group_by_header.'</td>';
1453       if ($report['show_duration'])
1454         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->getKey('label.duration').'</td>';
1455       if ($report['show_cost'])
1456         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->getKey('label.cost').'</td>';
1457       $body .= '</tr>';
1458       foreach($subtotals as $subtotal) {
1459         $body .= '<tr style="'.$rowSubtotal.'">';
1460         $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($subtotal['name'] ? htmlspecialchars($subtotal['name']) : '&nbsp;').'</td>';
1461         if ($report['show_duration']) {
1462           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1463           if ($subtotal['time'] <> '0:00') $body .= $subtotal['time'];
1464           $body .= '</td>';
1465         }
1466         if ($report['show_cost']) {
1467           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1468           $body .= ($user->canManageTeam() || $user->isClient()) ? $subtotal['cost'] : $subtotal['expenses'];
1469           $body .= '</td>';
1470         }
1471         $body .= '</tr>';
1472       }
1473
1474       // Print totals.
1475       $body .= '<tr><td>&nbsp;</td></tr>';
1476       $body .= '<tr style="'.$rowSubtotal.'">';
1477       $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->getKey('label.total').'</td>';
1478       if ($report['show_duration']) {
1479         $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1480         if ($totals['time'] <> '0:00') $body .= $totals['time'];
1481         $body .= '</td>';
1482       }
1483       if ($report['show_cost']) {
1484         $body .= '<td nowrap style="'.$cellRightAlignedSubtotal.'">'.htmlspecialchars($user->currency).' ';
1485         $body .= ($user->canManageTeam() || $user->isClient()) ? $totals['cost'] : $totals['expenses'];
1486         $body .= '</td>';
1487       }
1488       $body .= '</tr>';
1489
1490       $body .= '</table>';
1491     } else {
1492       // Regular report.
1493
1494       // Print table header.
1495       $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
1496       $body .= '<tr>';
1497       $body .= '<td style="'.$tableHeader.'">'.$i18n->getKey('label.date').'</td>';
1498       if ($user->canManageTeam() || $user->isClient())
1499         $body .= '<td style="'.$tableHeader.'">'.$i18n->getKey('label.user').'</td>';
1500       if ($report['show_client'])
1501         $body .= '<td style="'.$tableHeader.'">'.$i18n->getKey('label.client').'</td>';
1502       if ($report['show_project'])
1503         $body .= '<td style="'.$tableHeader.'">'.$i18n->getKey('label.project').'</td>';
1504       if ($report['show_task'])
1505         $body .= '<td style="'.$tableHeader.'">'.$i18n->getKey('label.task').'</td>';
1506       if ($report['show_custom_field_1'])
1507         $body .= '<td style="'.$tableHeader.'">'.htmlspecialchars($custom_fields->fields[0]['label']).'</td>';
1508       if ($report['show_start'])
1509         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->getKey('label.start').'</td>';
1510       if ($report['show_end'])
1511         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->getKey('label.finish').'</td>';
1512       if ($report['show_duration'])
1513         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->getKey('label.duration').'</td>';
1514       if ($report['show_note'])
1515         $body .= '<td style="'.$tableHeader.'">'.$i18n->getKey('label.note').'</td>';
1516       if ($report['show_cost'])
1517         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->getKey('label.cost').'</td>';
1518       if ($report['show_paid'])
1519         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->getKey('label.paid').'</td>';
1520       if ($report['show_invoice'])
1521         $body .= '<td style="'.$tableHeader.'">'.$i18n->getKey('label.invoice').'</td>';
1522       $body .= '</tr>';
1523
1524       // Initialize variables to print subtotals.
1525       if ($items && 'no_grouping' != $group_by) {
1526         $print_subtotals = true;
1527         $first_pass = true;
1528         $prev_grouped_by = '';
1529         $cur_grouped_by = '';
1530       }
1531       // Initialize variables to alternate color of rows for different dates.
1532       $prev_date = '';
1533       $cur_date = '';
1534       $row_style = $rowItem;
1535
1536       // Print report items.
1537       if (is_array($items)) {
1538         foreach ($items as $record) {
1539           $cur_date = $record['date'];
1540           // Print a subtotal row after a block of grouped items.
1541           if ($print_subtotals) {
1542             $cur_grouped_by = $record['grouped_by'];
1543             if ($cur_grouped_by != $prev_grouped_by && !$first_pass) {
1544               $body .= '<tr style="'.$rowSubtotal.'">';
1545               $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->getKey('label.subtotal').'</td>';
1546               $subtotal_name = htmlspecialchars($subtotals[$prev_grouped_by]['name']);
1547               if ($user->canManageTeam() || $user->isClient()) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'user' ? $subtotal_name : '').'</td>';
1548               if ($report['show_client']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'client' ? $subtotal_name : '').'</td>';
1549               if ($report['show_project']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'project' ? $subtotal_name : '').'</td>';
1550               if ($report['show_task']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'task' ? $subtotal_name : '').'</td>';
1551               if ($report['show_custom_field_1']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'cf_1' ? $subtotal_name : '').'</td>';
1552               if ($report['show_start']) $body .= '<td></td>';
1553               if ($report['show_end']) $body .= '<td></td>';
1554               if ($report['show_duration']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['time'].'</td>';
1555               if ($report['show_note']) $body .= '<td></td>';
1556               if ($report['show_cost']) {
1557                 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1558                 $body .= ($user->canManageTeam() || $user->isClient()) ? $subtotals[$prev_grouped_by]['cost'] : $subtotals[$prev_grouped_by]['expenses'];
1559                 $body .= '</td>';
1560               }
1561               if ($report['show_paid']) $body .= '<td></td>';
1562               if ($report['show_invoice']) $body .= '<td></td>';
1563               $body .= '</tr>';
1564               $body .= '<tr><td>&nbsp;</td></tr>';
1565             }
1566             $first_pass = false;
1567           }
1568
1569           // Print a regular row.
1570           if ($cur_date != $prev_date)
1571             $row_style = ($row_style == $rowItem) ? $rowItemAlt : $rowItem;
1572           $body .= '<tr style="'.$row_style.'">';
1573           $body .= '<td style="'.$cellLeftAligned.'">'.$record['date'].'</td>';
1574           if ($user->canManageTeam() || $user->isClient())
1575             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['user']).'</td>';
1576           if ($report['show_client'])
1577             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['client']).'</td>';
1578           if ($report['show_project'])
1579             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['project']).'</td>';
1580           if ($report['show_task'])
1581             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['task']).'</td>';
1582           if ($report['show_custom_field_1'])
1583             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['cf_1']).'</td>';
1584           if ($report['show_start'])
1585             $body .= '<td nowrap style="'.$cellRightAligned.'">'.$record['start'].'</td>';
1586           if ($report['show_end'])
1587             $body .= '<td nowrap style="'.$cellRightAligned.'">'.$record['finish'].'</td>';
1588           if ($report['show_duration'])
1589             $body .= '<td style="'.$cellRightAligned.'">'.$record['duration'].'</td>';
1590           if ($report['show_note'])
1591             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['note']).'</td>';
1592           if ($report['show_cost'])
1593             $body .= '<td style="'.$cellRightAligned.'">'.$record['cost'].'</td>';
1594           if ($report['show_paid']) {
1595             $body .= '<td style="'.$cellRightAligned.'">';
1596             $body .= $record['paid'] == 1 ? $i18n->getKey('label.yes') : $i18n->getKey('label.no');
1597             $body .= '</td>';
1598           }
1599           if ($report['show_invoice'])
1600             $body .= '<td style="'.$cellRightAligned.'">'.htmlspecialchars($record['invoice']).'</td>';
1601           $body .= '</tr>';
1602
1603           $prev_date = $record['date'];
1604           if ($print_subtotals)
1605             $prev_grouped_by = $record['grouped_by'];
1606         }
1607       }
1608
1609       // Print a terminating subtotal.
1610       if ($print_subtotals) {
1611         $body .= '<tr style="'.$rowSubtotal.'">';
1612         $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->getKey('label.subtotal').'</td>';
1613         $subtotal_name = htmlspecialchars($subtotals[$cur_grouped_by]['name']);
1614         if ($user->canManageTeam() || $user->isClient()) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'user' ? $subtotal_name : '').'</td>';
1615         if ($report['show_client']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'client' ? $subtotal_name : '').'</td>';
1616         if ($report['show_project']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'project' ? $subtotal_name : '').'</td>';
1617         if ($report['show_task']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'task' ? $subtotal_name : '').'</td>';
1618         if ($report['show_custom_field_1']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'cf_1' ? $subtotal_name : '').'</td>';
1619         if ($report['show_start']) $body .= '<td></td>';
1620         if ($report['show_end']) $body .= '<td></td>';
1621         if ($report['show_duration']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$cur_grouped_by]['time'].'</td>';
1622         if ($report['show_note']) $body .= '<td></td>';
1623         if ($report['show_cost']) {
1624           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1625           $body .= ($user->canManageTeam() || $user->isClient()) ? $subtotals[$cur_grouped_by]['cost'] : $subtotals[$cur_grouped_by]['expenses'];
1626           $body .= '</td>';
1627         }
1628         if ($report['show_paid']) $body .= '<td></td>';
1629         if ($report['show_invoice']) $body .= '<td></td>';
1630         $body .= '</tr>';
1631       }
1632
1633       // Print totals.
1634       $body .= '<tr><td>&nbsp;</td></tr>';
1635       $body .= '<tr style="'.$rowSubtotal.'">';
1636       $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->getKey('label.total').'</td>';
1637       if ($user->canManageTeam() || $user->isClient()) $body .= '<td></td>';
1638       if ($report['show_client']) $body .= '<td></td>';
1639       if ($report['show_project']) $body .= '<td></td>';
1640       if ($report['show_task']) $body .= '<td></td>';
1641       if ($report['show_custom_field_1']) $body .= '<td></td>';
1642       if ($report['show_start']) $body .= '<td></td>';
1643       if ($report['show_end']) $body .= '<td></td>';
1644       if ($report['show_duration']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$totals['time'].'</td>';
1645       if ($report['show_note']) $body .= '<td></td>';
1646       if ($report['show_cost']) {
1647         $body .= '<td nowrap style="'.$cellRightAlignedSubtotal.'">'.htmlspecialchars($user->currency).' ';
1648         $body .= ($user->canManageTeam() || $user->isClient()) ? $totals['cost'] : $totals['expenses'];
1649         $body .= '</td>';
1650       }
1651       if ($report['show_paid']) $body .= '<td></td>';
1652       if ($report['show_invoice']) $body .= '<td></td>';
1653       $body .= '</tr>';
1654
1655       $body .= '</table>';
1656     }
1657
1658     // Output footer.
1659     if (!defined('REPORT_FOOTER') || !(REPORT_FOOTER == false))
1660       $body .= '<p style="text-align: center;">'.$i18n->getKey('form.mail.footer').'</p>';
1661
1662     // Finish creating email body.
1663     $body .= '</body></html>';
1664
1665     return $body;
1666   }
1667
1668   // sendFavReport - sends a favorite report to a specified email, called from cron.php
1669   static function sendFavReport($report, $subject, $email, $cc) {
1670     // We are called from cron.php, we have no $bean in session.
1671     // cron.php sets global $user and $i18n objects to match our favorite report user.
1672     global $user;
1673     global $i18n;
1674
1675     // Prepare report body.
1676     $body = ttReportHelper::prepareFavReportBody($report);
1677
1678     import('mail.Mailer');
1679     $mailer = new Mailer();
1680     $mailer->setCharSet(CHARSET);
1681     $mailer->setContentType('text/html');
1682     $mailer->setSender(SENDER);
1683     if (!empty($cc))
1684       $mailer->setReceiverCC($cc);
1685     if (!empty($user->bcc_email))
1686       $mailer->setReceiverBCC($user->bcc_email);
1687     $mailer->setReceiver($email);
1688     $mailer->setMailMode(MAIL_MODE);
1689     if (empty($subject)) $subject = $report['name'];
1690     if (!$mailer->send($subject, $body))
1691       return false;
1692
1693     return true;
1694   }
1695 }