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