4d510bbb2962f99670158708f217a65b2a499dca
[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($options) {
41     global $user;
42
43     // Prepare dropdown parts.
44     $dropdown_parts = '';
45     if ($options['client_id'])
46       $dropdown_parts .= ' and l.client_id = '.$options['client_id'];
47     elseif ($user->isClient() && $user->client_id)
48       $dropdown_parts .= ' and l.client_id = '.$user->client_id;
49     if ($options['cf_1_option_id']) $dropdown_parts .= ' and l.id in(select log_id from tt_custom_field_log where status = 1 and option_id = '.$options['cf_1_option_id'].')';
50     if ($options['project_id']) $dropdown_parts .= ' and l.project_id = '.$options['project_id'];
51     if ($options['task_id']) $dropdown_parts .= ' and l.task_id = '.$options['task_id'];
52     if ($options['billable']=='1') $dropdown_parts .= ' and l.billable = 1';
53     if ($options['billable']=='2') $dropdown_parts .= ' and l.billable = 0';
54     if ($options['invoice']=='1') $dropdown_parts .= ' and l.invoice_id is not NULL';
55     if ($options['invoice']=='2') $dropdown_parts .= ' and l.invoice_id is NULL';
56     if ($options['paid_status']=='1') $dropdown_parts .= ' and l.paid = 1';
57     if ($options['paid_status']=='2') $dropdown_parts .= ' and l.paid = 0';
58
59     // Prepare sql query part for user list.
60     $userlist = $options['users'] ? $options['users'] : '-1';
61     if ($user->can('view_reports') || $user->can('view_all_reports') || $user->isClient())
62       $user_list_part = " and l.user_id in ($userlist)";
63     else
64       $user_list_part = " and l.user_id = ".$user->id;
65     $user_list_part .= " and l.group_id = ".$user->getActiveGroup();
66
67     // Prepare sql query part for where.
68     if ($options['period'])
69       $period = new Period($options['period'], new DateAndTime($user->date_format));
70     else {
71       $period = new Period();
72       $period->setPeriod(
73         new DateAndTime($user->date_format, $options['period_start']),
74         new DateAndTime($user->date_format, $options['period_end']));
75     }
76     $where = " where l.status = 1 and l.date >= '".$period->getStartDate(DB_DATEFORMAT)."' and l.date <= '".$period->getEndDate(DB_DATEFORMAT)."'".
77       " $user_list_part $dropdown_parts";
78     return $where;
79   }
80
81   // getExpenseWhere prepares WHERE clause for expenses query in a report.
82   static function getExpenseWhere($options) {
83     global $user;
84
85     // Prepare dropdown parts.
86     $dropdown_parts = '';
87     if ($options['client_id'])
88       $dropdown_parts .= ' and ei.client_id = '.$options['client_id'];
89     elseif ($user->isClient() && $user->client_id)
90       $dropdown_parts .= ' and ei.client_id = '.$user->client_id;
91     if ($options['project_id']) $dropdown_parts .= ' and ei.project_id = '.$options['project_id'];
92     if ($options['invoice']=='1') $dropdown_parts .= ' and ei.invoice_id is not NULL';
93     if ($options['invoice']=='2') $dropdown_parts .= ' and ei.invoice_id is NULL';
94     if ($options['paid_status']=='1') $dropdown_parts .= ' and ei.paid = 1';
95     if ($options['paid_status']=='2') $dropdown_parts .= ' and ei.paid = 0';
96
97     // Prepare sql query part for user list.
98     $userlist = $options['users'] ? $options['users'] : '-1';
99     if ($user->can('view_reports') || $user->can('view_all_reports') || $user->isClient())
100       $user_list_part = " and ei.user_id in ($userlist)";
101     else
102       $user_list_part = " and ei.user_id = ".$user->id;
103     $user_list_part .= " and ei.group_id = ".$user->getActiveGroup();
104
105     // Prepare sql query part for where.
106     if ($options['period'])
107       $period = new Period($options['period'], new DateAndTime($user->date_format));
108     else {
109       $period = new Period();
110       $period->setPeriod(
111         new DateAndTime($user->date_format, $options['period_start']),
112         new DateAndTime($user->date_format, $options['period_end']));
113     }
114     $where = " where ei.status = 1 and ei.date >= '".$period->getStartDate(DB_DATEFORMAT)."' and ei.date <= '".$period->getEndDate(DB_DATEFORMAT)."'".
115       " $user_list_part $dropdown_parts";
116     return $where;
117   }
118
119   // getItems retrieves all items associated with a report.
120   // It combines tt_log and tt_expense_items in one array for presentation in one table using mysql union all.
121   // Expense items use the "note" field for item name.
122   static function getItems($options) {
123     global $user;
124     $mdb2 = getConnection();
125
126     // Determine these once as they are used in multiple places in this function.
127     $canViewReports = $user->can('view_reports') || $user->can('view_all_reports');
128     $isClient = $user->isClient();
129
130     $group_by_option = $options['group_by'];
131     $convertTo12Hour = ('%I:%M %p' == $user->time_format) && ($options['show_start'] || $options['show_end']);
132
133     // Prepare a query for time items in tt_log table.
134     $fields = array(); // An array of fields for database query.
135     array_push($fields, 'l.id as id');
136     array_push($fields, '1 as type'); // Type 1 is for tt_log entries.
137     array_push($fields, 'l.date as date');
138     if($canViewReports || $isClient)
139       array_push($fields, 'u.name as user');
140     // Add client name if it is selected.
141     if ($options['show_client'] || 'client' == $group_by_option)
142       array_push($fields, 'c.name as client');
143     // Add project name if it is selected.
144     if ($options['show_project'] || 'project' == $group_by_option)
145       array_push($fields, 'p.name as project');
146     // Add task name if it is selected.
147     if ($options['show_task'] || 'task' == $group_by_option)
148       array_push($fields, 't.name as task');
149     // Add custom field.
150     $include_cf_1 = $options['show_custom_field_1'] || 'cf_1' == $group_by_option;
151     if ($include_cf_1) {
152       $custom_fields = new CustomFields($user->group_id);
153       $cf_1_type = $custom_fields->fields[0]['type'];
154       if ($cf_1_type == CustomFields::TYPE_TEXT) {
155         array_push($fields, 'cfl.value as cf_1');
156       } elseif ($cf_1_type == CustomFields::TYPE_DROPDOWN) {
157         array_push($fields, 'cfo.value as cf_1');
158       }
159     }
160     // Add start time.
161     if ($options['show_start']) {
162       array_push($fields, "l.start as unformatted_start");
163       array_push($fields, "TIME_FORMAT(l.start, '%k:%i') as start");
164     }
165     // Add finish time.
166     if ($options['show_end'])
167       array_push($fields, "TIME_FORMAT(sec_to_time(time_to_sec(l.start) + time_to_sec(l.duration)), '%k:%i') as finish");
168     // Add duration.
169     if ($options['show_duration'])
170       array_push($fields, "TIME_FORMAT(l.duration, '%k:%i') as duration");
171     // Add work units.
172     if ($options['show_work_units']) {
173       if ($user->unit_totals_only)
174         array_push($fields, "null as units");
175       else
176         array_push($fields, "if(l.billable = 0 or time_to_sec(l.duration)/60 < $user->first_unit_threshold, 0, ceil(time_to_sec(l.duration)/60/$user->minutes_in_unit)) as units");
177     }
178     // Add note.
179     if ($options['show_note'])
180       array_push($fields, 'l.comment as note');
181     // Handle cost.
182     $includeCost = $options['show_cost'];
183     if ($includeCost) {
184       if (MODE_TIME == $user->tracking_mode)
185         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.
186       else
187         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.
188       array_push($fields, "null as expense"); 
189     }
190     // Add paid status.
191     if ($canViewReports && $options['show_paid'])
192       array_push($fields, 'l.paid as paid');
193     // Add IP address.
194     if ($canViewReports && $options['show_ip']) {
195       array_push($fields, 'l.created as created');
196       array_push($fields, 'l.created_ip as created_ip');
197       array_push($fields, 'l.modified as modified');
198       array_push($fields, 'l.modified_ip as modified_ip');
199     }
200     // Add invoice name if it is selected.
201     if (($canViewReports || $isClient) && $options['show_invoice'])
202       array_push($fields, 'i.name as invoice');
203
204     // Prepare sql query part for left joins.
205     $left_joins = null;
206     if ($options['show_client'] || 'client' == $group_by_option)
207       $left_joins .= " left join tt_clients c on (c.id = l.client_id)";
208     if (($canViewReports || $isClient) && $options['show_invoice'])
209       $left_joins .= " left join tt_invoices i on (i.id = l.invoice_id and i.status = 1)";
210     if ($canViewReports || $isClient || $user->isPluginEnabled('ex'))
211        $left_joins .= " left join tt_users u on (u.id = l.user_id)";
212     if ($options['show_project'] || 'project' == $group_by_option)
213       $left_joins .= " left join tt_projects p on (p.id = l.project_id)";
214     if ($options['show_task'] || 'task' == $group_by_option)
215       $left_joins .= " left join tt_tasks t on (t.id = l.task_id)";
216     if ($include_cf_1) {
217       if ($cf_1_type == CustomFields::TYPE_TEXT)
218         $left_joins .= " left join tt_custom_field_log cfl on (l.id = cfl.log_id and cfl.status = 1)";
219       elseif ($cf_1_type == CustomFields::TYPE_DROPDOWN) {
220         $left_joins .=  " left join tt_custom_field_log cfl on (l.id = cfl.log_id and cfl.status = 1)".
221           " left join tt_custom_field_options cfo on (cfl.option_id = cfo.id)";
222       }
223     }
224     if ($includeCost && MODE_TIME != $user->tracking_mode)
225       $left_joins .= " left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id)";
226
227     $where = ttReportHelper::getWhere($options);
228
229     // Construct sql query for tt_log items.
230     $sql = "select ".join(', ', $fields)." from tt_log l $left_joins $where";
231     // If we don't have expense items (such as when the Expenses plugin is desabled), the above is all sql we need,
232     // with an exception of sorting part, that is added in the end.
233
234     // However, when we have expenses, we need to do a union with a separate query for expense items from tt_expense_items table.
235     if ($options['show_cost'] && $user->isPluginEnabled('ex')) { // if ex(penses) plugin is enabled
236
237       $fields = array(); // An array of fields for database query.
238       array_push($fields, 'ei.id');
239       array_push($fields, '2 as type'); // Type 2 is for tt_expense_items entries.
240       array_push($fields, 'ei.date');
241       if($canViewReports || $isClient)
242         array_push($fields, 'u.name as user');
243       // Add client name if it is selected.
244       if ($options['show_client'] || 'client' == $group_by_option)
245         array_push($fields, 'c.name as client');
246       // Add project name if it is selected.
247       if ($options['show_project'] || 'project' == $group_by_option)
248         array_push($fields, 'p.name as project');
249       if ($options['show_task'] || 'task' == $group_by_option)
250         array_push($fields, 'null'); // null for task name. We need to match column count for union.
251       if ($options['show_custom_field_1'] || 'cf_1' == $group_by_option)
252         array_push($fields, 'null'); // null for cf_1.
253       if ($options['show_start']) {
254         array_push($fields, 'null'); // null for unformatted_start.
255         array_push($fields, 'null'); // null for start.
256       }
257       if ($options['show_end'])
258         array_push($fields, 'null'); // null for finish.
259       if ($options['show_duration'])
260         array_push($fields, 'null'); // null for duration.
261       if ($options['show_work_units'])
262         array_push($fields, 'null as units'); // null for work units.
263       // Use the note field to print item name.
264       if ($options['show_note'])
265         array_push($fields, 'ei.name as note');
266       array_push($fields, 'ei.cost as cost');
267       array_push($fields, 'ei.cost as expense');
268       // Add paid status.
269       if ($canViewReports && $options['show_paid'])
270         array_push($fields, 'ei.paid as paid');
271       // Add IP address.
272       if ($canViewReports && $options['show_ip']) {
273         array_push($fields, 'ei.created as created');
274         array_push($fields, 'ei.created_ip as created_ip');
275         array_push($fields, 'ei.modified as modified');
276         array_push($fields, 'ei.modified_ip as modified_ip');
277       }
278       // Add invoice name if it is selected.
279       if (($canViewReports || $isClient) && $options['show_invoice'])
280         array_push($fields, 'i.name as invoice');
281
282       // Prepare sql query part for left joins.
283       $left_joins = null;
284       if ($canViewReports || $isClient)
285         $left_joins .= " left join tt_users u on (u.id = ei.user_id)";
286       if ($options['show_client'] || 'client' == $group_by_option)
287         $left_joins .= " left join tt_clients c on (c.id = ei.client_id)";
288       if ($options['show_project'] || 'project' == $group_by_option)
289         $left_joins .= " left join tt_projects p on (p.id = ei.project_id)";
290       if (($canViewReports || $isClient) && $options['show_invoice'])
291         $left_joins .= " left join tt_invoices i on (i.id = ei.invoice_id and i.status = 1)";
292
293       $where = ttReportHelper::getExpenseWhere($options);
294
295       // Construct sql query for expense items.
296       $sql_for_expense_items = "select ".join(', ', $fields)." from tt_expense_items ei $left_joins $where";
297
298       // Construct a union.
299       $sql = "($sql) union all ($sql_for_expense_items)";
300     }
301
302     // Determine sort part.
303     $sort_part = ' order by ';
304     if ($group_by_option == null || 'no_grouping' == $group_by_option || 'date' == $group_by_option)
305       $sort_part .= 'date';
306     else
307       $sort_part .= $group_by_option.', date';
308     if (($canViewReports || $isClient) && $options['users'] && 'user' != $group_by_option)
309       $sort_part .= ', user, type';
310     if ($options['show_start'])
311       $sort_part .= ', unformatted_start';
312     $sort_part .= ', id';
313
314     $sql .= $sort_part;
315     // By now we are ready with sql.
316
317     // Obtain items for report.
318     $res = $mdb2->query($sql);
319     if (is_a($res, 'PEAR_Error')) die($res->getMessage());
320
321     while ($val = $res->fetchRow()) {
322       if ($convertTo12Hour) {
323         if($val['start'] != '')
324           $val['start'] = ttTimeHelper::to12HourFormat($val['start']);
325         if($val['finish'] != '')
326           $val['finish'] = ttTimeHelper::to12HourFormat($val['finish']);
327       }
328       if (isset($val['cost'])) {
329         if ('.' != $user->decimal_mark)
330           $val['cost'] = str_replace('.', $user->decimal_mark, $val['cost']);
331       }
332       if (isset($val['expense'])) {
333         if ('.' != $user->decimal_mark)
334           $val['expense'] = str_replace('.', $user->decimal_mark, $val['expense']);
335       }
336       if ('no_grouping' != $group_by_option) {
337         $val['grouped_by'] = $val[$group_by_option];
338         if ('date' == $group_by_option) {
339           // This is needed to get the date in user date format.
340           $o_date = new DateAndTime(DB_DATEFORMAT, $val['grouped_by']);
341           $val['grouped_by'] = $o_date->toString($user->date_format);
342           unset($o_date);
343         }
344       }
345
346       // This is needed to get the date in user date format.
347       $o_date = new DateAndTime(DB_DATEFORMAT, $val['date']);
348       $val['date'] = $o_date->toString($user->date_format);
349       unset($o_date);
350
351       $row = $val;
352       $report_items[] = $row;
353     }
354
355     return $report_items;
356   }
357
358   // putInSession stores tt_log and tt_expense_items ids from a report in user session
359   // as 2 comma-separated lists.
360   static function putInSession($report_items) {
361     unset($_SESSION['report_item_ids']);
362     unset($_SESSION['report_item_expense_ids']);
363
364     // Iterate through records and build 2 comma-separated lists.
365     foreach($report_items as $item) {
366       if ($item['type'] == 1)
367         $report_item_ids .= ','.$item['id'];
368       else if ($item['type'] == 2)
369          $report_item_expense_ids .= ','.$item['id'];
370     }
371     $report_item_ids = trim($report_item_ids, ',');
372     $report_item_expense_ids = trim($report_item_expense_ids, ',');
373
374     // The lists are reqdy. Put them in session.
375     if ($report_item_ids) $_SESSION['report_item_ids'] = $report_item_ids;
376     if ($report_item_expense_ids) $_SESSION['report_item_expense_ids'] = $report_item_expense_ids;
377   }
378
379   // getFromSession obtains tt_log and tt_expense_items ids stored in user session.
380   static function getFromSession() {
381     $items = array();
382     $report_item_ids = $_SESSION['report_item_ids'];
383     if ($report_item_ids)
384       $items['report_item_ids'] = explode(',', $report_item_ids);
385     $report_item_expense_ids = $_SESSION['report_item_expense_ids'];
386     if ($report_item_expense_ids)
387       $items['report_item_expense_ids'] = explode(',', $report_item_expense_ids);
388     return $items;
389   }
390
391   // getSubtotals calculates report items subtotals when a report is grouped by.
392   // Without expenses, it's a simple select with group by.
393   // With expenses, it becomes a select with group by from a combined set of records obtained with "union all".
394   static function getSubtotals($options) {
395     global $user;
396
397     $group_by_option = $options['group_by'];
398     if ('no_grouping' == $group_by_option) return null;
399
400     $mdb2 = getConnection();
401
402     // Start with sql to obtain subtotals for time items. This simple sql will be used when we have no expenses.
403
404     // Determine group by field and a required join.
405     switch ($group_by_option) {
406       case 'date':
407         $group_field = 'l.date';
408         $group_join = '';
409         break;
410       case 'user':
411         $group_field = 'u.name';
412         $group_join = 'left join tt_users u on (l.user_id = u.id) ';
413         break;
414       case 'client':
415         $group_field = 'c.name';
416         $group_join = 'left join tt_clients c on (l.client_id = c.id) ';
417         break;
418       case 'project':
419         $group_field = 'p.name';
420         $group_join = 'left join tt_projects p on (l.project_id = p.id) ';
421         break;
422       case 'task':
423         $group_field = 't.name';
424         $group_join = 'left join tt_tasks t on (l.task_id = t.id) ';
425         break;
426       case 'cf_1':
427         $group_field = 'cfo.value';
428         $custom_fields = new CustomFields($user->group_id);
429         if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_TEXT)
430           $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) ';
431         elseif ($custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN)
432           $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) ';
433         break;
434     }
435
436     $where = ttReportHelper::getWhere($options);
437     if ($options['show_cost']) {
438       if (MODE_TIME == $user->tracking_mode) {
439         if ($group_by_option != 'user')
440           $left_join = 'left join tt_users u on (l.user_id = u.id)';
441         $sql = "select $group_field as group_field, sum(time_to_sec(l.duration)) as time";
442         if ($options['show_work_units']) {
443           if ($user->unit_totals_only)
444             $sql .= ", if (sum(l.billable * time_to_sec(l.duration)/60) < $user->first_unit_threshold, 0, ceil(sum(l.billable * time_to_sec(l.duration)/60/$user->minutes_in_unit))) as units";
445           else
446             $sql .= ", sum(if(l.billable = 0 or time_to_sec(l.duration)/60 < $user->first_unit_threshold, 0, ceil(time_to_sec(l.duration)/60/$user->minutes_in_unit))) as units";
447         }
448         $sql .= ", sum(cast(l.billable * coalesce(u.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10, 2))) as cost,
449           null as expenses from tt_log l
450           $group_join $left_join $where group by $group_field";
451       } else {
452         // If we are including cost and tracking projects, our query (the same as above) needs to join the tt_user_project_binds table.
453         $sql = "select $group_field as group_field, sum(time_to_sec(l.duration)) as time";
454         if ($options['show_work_units']) {
455           if ($user->unit_totals_only)
456             $sql .= ", if (sum(l.billable * time_to_sec(l.duration)/60) < $user->first_unit_threshold, 0, ceil(sum(l.billable * time_to_sec(l.duration)/60/$user->minutes_in_unit))) as units";
457           else
458             $sql .= ", sum(if(l.billable = 0 or time_to_sec(l.duration)/60 < $user->first_unit_threshold, 0, ceil(time_to_sec(l.duration)/60/$user->minutes_in_unit))) as units";
459         }
460         $sql .= ", sum(cast(l.billable * coalesce(upb.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10,2))) as cost,
461           null as expenses from tt_log l 
462           $group_join
463           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";
464       }
465     } else {
466       $sql = "select $group_field as group_field, sum(time_to_sec(l.duration)) as time";
467       if ($options['show_work_units']) {
468         if ($user->unit_totals_only)
469           $sql .= ", if (sum(l.billable * time_to_sec(l.duration)/60) < $user->first_unit_threshold, 0, ceil(sum(l.billable * time_to_sec(l.duration)/60/$user->minutes_in_unit))) as units";
470         else
471           $sql .= ", sum(if(l.billable = 0 or time_to_sec(l.duration)/60 < $user->first_unit_threshold, 0, ceil(time_to_sec(l.duration)/60/$user->minutes_in_unit))) as units";
472       }
473       $sql .= ", null as expenses from tt_log l 
474         $group_join $where group by $group_field";
475     }
476     // By now we have sql for time items.
477
478     // However, when we have expenses, we need to do a union with a separate query for expense items from tt_expense_items table.
479     if ($options['show_cost'] && $user->isPluginEnabled('ex')) { // if ex(penses) plugin is enabled
480
481       // Determine group by field and a required join.
482       $group_join = null;
483       $group_field = 'null';
484       switch ($group_by_option) {
485         case 'date':
486           $group_field = 'ei.date';
487           $group_join = '';
488           break;
489         case 'user':
490           $group_field = 'u.name';
491           $group_join = 'left join tt_users u on (ei.user_id = u.id) ';
492           break;
493         case 'client':
494           $group_field = 'c.name';
495           $group_join = 'left join tt_clients c on (ei.client_id = c.id) ';
496           break;
497         case 'project':
498           $group_field = 'p.name';
499           $group_join = 'left join tt_projects p on (ei.project_id = p.id) ';
500           break;
501       }
502
503       $where = ttReportHelper::getExpenseWhere($options);
504       $sql_for_expenses = "select $group_field as group_field, null as time";
505       if ($options['show_work_units']) $sql_for_expenses .= ", null as units";
506       $sql_for_expenses .= ", sum(ei.cost) as cost, sum(ei.cost) as expenses from tt_expense_items ei $group_join $where";
507       // Add a "group by" clause if we are grouping.
508       if ('null' != $group_field) $sql_for_expenses .= " group by $group_field";
509
510       // Create a combined query.
511       $combined = "select group_field, sum(time) as time";
512       if ($options['show_work_units']) $combined .= ", sum(units) as units";
513       $combined .= ", sum(cost) as cost, sum(expenses) as expenses from (($sql) union all ($sql_for_expenses)) t group by group_field";
514       $sql = $combined;
515     }
516
517     // Execute query.
518     $res = $mdb2->query($sql);
519     if (is_a($res, 'PEAR_Error')) die($res->getMessage());
520
521     while ($val = $res->fetchRow()) {
522       if ('date' == $group_by_option) {
523         // This is needed to get the date in user date format.
524         $o_date = new DateAndTime(DB_DATEFORMAT, $val['group_field']);
525         $val['group_field'] = $o_date->toString($user->date_format);
526         unset($o_date);
527       }
528       $time = $val['time'] ? sec_to_time_fmt_hm($val['time']) : null;
529       if ($options['show_cost']) {
530         if ('.' != $user->decimal_mark) {
531           $val['cost'] = str_replace('.', $user->decimal_mark, $val['cost']);
532           $val['expenses'] = str_replace('.', $user->decimal_mark, $val['expenses']);
533         }
534         $subtotals[$val['group_field']] = array('name'=>$val['group_field'],'time'=>$time, 'units'=> $val['units'], 'cost'=>$val['cost'],'expenses'=>$val['expenses']);
535       } else
536         $subtotals[$val['group_field']] = array('name'=>$val['group_field'],'time'=>$time, 'units'=> $val['units']);
537     }
538
539     return $subtotals;
540   }
541
542   // getTotals calculates total hours and cost for all report items.
543   static function getTotals($options)
544   {
545     global $user;
546
547     $mdb2 = getConnection();
548
549     $where = ttReportHelper::getWhere($options);
550
551     // Prepare parts.
552     $time_part = "sum(time_to_sec(l.duration)) as time";
553     if ($options['show_work_units']) {
554       $units_part = $user->unit_totals_only ? ", null as units" : ", sum(if(l.billable = 0 or time_to_sec(l.duration)/60 < $user->first_unit_threshold, 0, ceil(time_to_sec(l.duration)/60/$user->minutes_in_unit))) as units";
555     }
556     if ($options['show_cost']) {
557       if (MODE_TIME == $user->tracking_mode)
558         $cost_part = ", sum(cast(l.billable * coalesce(u.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10,2))) as cost, null as expenses";
559       else
560         $cost_part = ", sum(cast(l.billable * coalesce(upb.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10,2))) as cost, null as expenses";
561     } else {
562       $cost_part = ", null as cost, null as expenses";
563     }
564     if ($options['show_cost']) {
565       if (MODE_TIME == $user->tracking_mode) {
566         $left_joins = "left join tt_users u on (l.user_id = u.id)";
567       } else {
568         $left_joins = "left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id)";
569       }
570     }
571     // Prepare a query for time items.
572     $sql = "select $time_part $units_part $cost_part from tt_log l $left_joins $where";
573
574     // If we have expenses, query becomes a bit more complex.
575     if ($options['show_cost'] && $user->isPluginEnabled('ex')) {
576       $where = ttReportHelper::getExpenseWhere($options);
577       $sql_for_expenses = "select null as time";
578       if ($options['show_work_units']) $sql_for_expenses .= ", null as units";
579       $sql_for_expenses .= ", sum(cost) as cost, sum(cost) as expenses from tt_expense_items ei $where";
580
581       // Create a combined query.
582       $combined = "select sum(time) as time";
583       if ($options['show_work_units']) $combined .= ", sum(units) as units";
584       $combined .= ", sum(cost) as cost, sum(expenses) as expenses from (($sql) union all ($sql_for_expenses)) t";
585       $sql = $combined;
586     }
587
588     // Execute query.
589     $res = $mdb2->query($sql);
590     if (is_a($res, 'PEAR_Error')) die($res->getMessage());
591
592     $val = $res->fetchRow();
593     $total_time = $val['time'] ? sec_to_time_fmt_hm($val['time']) : null;
594     if ($options['show_cost']) {
595       $total_cost = $val['cost'];
596       if (!$total_cost) $total_cost = '0.00';
597       if ('.' != $user->decimal_mark)
598         $total_cost = str_replace('.', $user->decimal_mark, $total_cost);
599       $total_expenses = $val['expenses'];
600       if (!$total_expenses) $total_expenses = '0.00';
601       if ('.' != $user->decimal_mark)
602         $total_expenses = str_replace('.', $user->decimal_mark, $total_expenses);
603     }
604
605     if ($options['period'])
606       $period = new Period($options['period'], new DateAndTime($user->date_format));
607     else {
608       $period = new Period();
609       $period->setPeriod(
610         new DateAndTime($user->date_format, $options['period_start']),
611         new DateAndTime($user->date_format, $options['period_end']));
612     }
613
614     $totals['start_date'] = $period->getStartDate();
615     $totals['end_date'] = $period->getEndDate();
616     $totals['time'] = $total_time;
617     $totals['units'] = $val['units'];
618     $totals['cost'] = $total_cost;
619     $totals['expenses'] = $total_expenses;
620
621     return $totals;
622   }
623
624   // The assignToInvoice assigns a set of records to a specific invoice.
625   static function assignToInvoice($invoice_id, $time_log_ids, $expense_item_ids)
626   {
627     $mdb2 = getConnection();
628     if ($time_log_ids) {
629       $sql = "update tt_log set invoice_id = ".$mdb2->quote($invoice_id).
630         " where id in(".join(', ', $time_log_ids).")";
631       $affected = $mdb2->exec($sql);
632       if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
633     }
634     if ($expense_item_ids) {
635       $sql = "update tt_expense_items set invoice_id = ".$mdb2->quote($invoice_id).
636         " where id in(".join(', ', $expense_item_ids).")";
637       $affected = $mdb2->exec($sql);
638       if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
639     }
640   }
641
642   // The markPaid marks a set of records as either paid or unpaid.
643   static function markPaid($time_log_ids, $expense_item_ids, $paid = true)
644   {
645     $mdb2 = getConnection();
646     $paid_val = (int) $paid;
647     if ($time_log_ids) {
648       $sql = "update tt_log set paid = $paid_val where id in(".join(', ', $time_log_ids).")";
649       $affected = $mdb2->exec($sql);
650       if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
651     }
652     if ($expense_item_ids) {
653       $sql = "update tt_expense_items set paid = $paid_val where id in(".join(', ', $expense_item_ids).")";
654       $affected = $mdb2->exec($sql);
655       if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
656     }
657   }
658
659   // prepareReportBody - prepares an email body for report.
660   static function prepareReportBody($bean, $comment)
661   {
662     global $user;
663     global $i18n;
664
665     // Determine these once as they are used in multiple places in this function.
666     $canViewReports = $user->can('view_reports') || $user->can('view_all_reports');
667     $isClient = $user->isClient();
668     $options = ttReportHelper::getReportOptions($bean);
669
670     $items = ttReportHelper::getItems($options);
671     $group_by = $bean->getAttribute('group_by');
672     if ($group_by && 'no_grouping' != $group_by)
673       $subtotals = ttReportHelper::getSubtotals($options);
674     $totals = ttReportHelper::getTotals($options);
675
676     // Use custom fields plugin if it is enabled.
677     if ($user->isPluginEnabled('cf'))
678       $custom_fields = new CustomFields($user->group_id);
679
680     // Define some styles to use in email.
681     $style_title = 'text-align: center; font-size: 15pt; font-family: Arial, Helvetica, sans-serif;';
682     $tableHeader = 'font-weight: bold; background-color: #a6ccf7; text-align: left;';
683     $tableHeaderCentered = 'font-weight: bold; background-color: #a6ccf7; text-align: center;';
684     $rowItem = 'background-color: #ffffff;';
685     $rowItemAlt = 'background-color: #f5f5f5;';
686     $rowSubtotal = 'background-color: #e0e0e0;';
687     $cellLeftAligned = 'text-align: left; vertical-align: top;';
688     $cellRightAligned = 'text-align: right; vertical-align: top;';
689     $cellLeftAlignedSubtotal = 'font-weight: bold; text-align: left; vertical-align: top;';
690     $cellRightAlignedSubtotal = 'font-weight: bold; text-align: right; vertical-align: top;';
691
692     // Start creating email body.
693     $body = '<html>';
694     $body .= '<head><meta http-equiv="content-type" content="text/html; charset='.CHARSET.'"></head>';
695     $body .= '<body>';
696
697     // Output title.
698     $body .= '<p style="'.$style_title.'">'.$i18n->get('form.mail.report_subject').': '.$totals['start_date'].' - '.$totals['end_date'].'</p>';
699
700     // Output comment.
701     if ($comment) $body .= '<p>'.htmlspecialchars($comment).'</p>';
702
703     if ($bean->getAttribute('chtotalsonly')) {
704       // Totals only report. Output subtotals.
705
706       // Determine group_by header.
707       if ('cf_1' == $group_by)
708         $group_by_header = htmlspecialchars($custom_fields->fields[0]['label']);
709       else {
710         $key = 'label.'.$group_by;
711         $group_by_header = $i18n->get($key);
712       }
713
714       $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
715       $body .= '<tr>';
716       $body .= '<td style="'.$tableHeader.'">'.$group_by_header.'</td>';
717       if ($bean->getAttribute('chduration'))
718         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.duration').'</td>';
719       if ($bean->getAttribute('chunits'))
720         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.work_units_short').'</td>';
721       if ($bean->getAttribute('chcost'))
722         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.cost').'</td>';
723       $body .= '</tr>';
724       foreach($subtotals as $subtotal) {
725         $body .= '<tr style="'.$rowSubtotal.'">';
726         $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($subtotal['name'] ? htmlspecialchars($subtotal['name']) : '&nbsp;').'</td>';
727         if ($bean->getAttribute('chduration')) {
728           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
729           if ($subtotal['time'] <> '0:00') $body .= $subtotal['time'];
730           $body .= '</td>';
731         }
732         if ($bean->getAttribute('chunits')) {
733           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
734           $body .= $subtotal['units'];
735           $body .= '</td>';
736         }
737         if ($bean->getAttribute('chcost')) {
738           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
739           $body .= ($canViewReports || $isClient) ? $subtotal['cost'] : $subtotal['expenses'];
740           $body .= '</td>';
741         }
742         $body .= '</tr>';
743       }
744
745       // Print totals.
746       $body .= '<tr><td>&nbsp;</td></tr>';
747       $body .= '<tr style="'.$rowSubtotal.'">';
748       $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.total').'</td>';
749       if ($bean->getAttribute('chduration')) {
750         $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
751         if ($totals['time'] <> '0:00') $body .= $totals['time'];
752         $body .= '</td>';
753       }
754       if ($bean->getAttribute('chunits')) {
755         $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
756         $body .= $totals['units'];
757         $body .= '</td>';
758       }
759       if ($bean->getAttribute('chcost')) {
760         $body .= '<td nowrap style="'.$cellRightAlignedSubtotal.'">'.htmlspecialchars($user->currency).' ';
761         $body .= ($canViewReports || $isClient) ? $totals['cost'] : $totals['expenses'];
762         $body .= '</td>';
763       }
764       $body .= '</tr>';
765
766       $body .= '</table>';
767     } else {
768       // Regular report.
769
770       // Print table header.
771       $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
772       $body .= '<tr>';
773       $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.date').'</td>';
774       if ($canViewReports || $isClient)
775         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.user').'</td>';
776       if ($bean->getAttribute('chclient'))
777         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.client').'</td>';
778       if ($bean->getAttribute('chproject'))
779         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.project').'</td>';
780       if ($bean->getAttribute('chtask'))
781         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.task').'</td>';
782       if ($bean->getAttribute('chcf_1'))
783         $body .= '<td style="'.$tableHeader.'">'.htmlspecialchars($custom_fields->fields[0]['label']).'</td>';
784       if ($bean->getAttribute('chstart'))
785         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.start').'</td>';
786       if ($bean->getAttribute('chfinish'))
787         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.finish').'</td>';
788       if ($bean->getAttribute('chduration'))
789         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.duration').'</td>';
790       if ($bean->getAttribute('chunits'))
791         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.work_units_short').'</td>';
792       if ($bean->getAttribute('chnote'))
793         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.note').'</td>';
794       if ($bean->getAttribute('chcost'))
795         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.cost').'</td>';
796       if ($bean->getAttribute('chpaid'))
797         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.paid').'</td>';
798       if ($bean->getAttribute('chip'))
799         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.ip').'</td>';
800       if ($bean->getAttribute('chinvoice'))
801         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.invoice').'</td>';
802       $body .= '</tr>';
803
804       // Initialize variables to print subtotals.
805       if ($items && 'no_grouping' != $group_by) {
806         $print_subtotals = true;
807         $first_pass = true;
808         $prev_grouped_by = '';
809         $cur_grouped_by = '';
810       }
811       // Initialize variables to alternate color of rows for different dates.
812       $prev_date = '';
813       $cur_date = '';
814       $row_style = $rowItem;
815
816       // Print report items.
817       if (is_array($items)) {
818         foreach ($items as $record) {
819           $cur_date = $record['date'];
820           // Print a subtotal row after a block of grouped items.
821           if ($print_subtotals) {
822             $cur_grouped_by = $record['grouped_by'];
823             if ($cur_grouped_by != $prev_grouped_by && !$first_pass) {
824               $body .= '<tr style="'.$rowSubtotal.'">';
825               $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.subtotal').'</td>';
826               $subtotal_name = htmlspecialchars($subtotals[$prev_grouped_by]['name']);
827               if ($canViewReports || $isClient) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'user' ? $subtotal_name : '').'</td>';
828               if ($bean->getAttribute('chclient')) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'client' ? $subtotal_name : '').'</td>';
829               if ($bean->getAttribute('chproject')) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'project' ? $subtotal_name : '').'</td>';
830               if ($bean->getAttribute('chtask')) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'task' ? $subtotal_name : '').'</td>';
831               if ($bean->getAttribute('chcf_1')) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'cf_1' ? $subtotal_name : '').'</td>';
832               if ($bean->getAttribute('chstart')) $body .= '<td></td>';
833               if ($bean->getAttribute('chfinish')) $body .= '<td></td>';
834               if ($bean->getAttribute('chduration')) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['time'].'</td>';
835               if ($bean->getAttribute('chunits')) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['units'].'</td>';
836               if ($bean->getAttribute('chnote')) $body .= '<td></td>';
837               if ($bean->getAttribute('chcost')) {
838                 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
839                 $body .= ($canViewReports || $isClient) ? $subtotals[$prev_grouped_by]['cost'] : $subtotals[$prev_grouped_by]['expenses'];
840                 $body .= '</td>';
841               }
842               if ($bean->getAttribute('chpaid')) $body .= '<td></td>';
843               if ($bean->getAttribute('chip')) $body .= '<td></td>';
844               if ($bean->getAttribute('chinvoice')) $body .= '<td></td>';
845               $body .= '</tr>';
846               $body .= '<tr><td>&nbsp;</td></tr>';
847             }
848             $first_pass = false;
849           }
850
851           // Print a regular row.
852           if ($cur_date != $prev_date)
853             $row_style = ($row_style == $rowItem) ? $rowItemAlt : $rowItem;
854           $body .= '<tr style="'.$row_style.'">';
855           $body .= '<td style="'.$cellLeftAligned.'">'.$record['date'].'</td>';
856           if ($canViewReports || $isClient)
857             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['user']).'</td>';
858           if ($bean->getAttribute('chclient'))
859             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['client']).'</td>';
860           if ($bean->getAttribute('chproject'))
861             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['project']).'</td>';
862           if ($bean->getAttribute('chtask'))
863             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['task']).'</td>';
864           if ($bean->getAttribute('chcf_1'))
865             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['cf_1']).'</td>';
866           if ($bean->getAttribute('chstart'))
867             $body .= '<td nowrap style="'.$cellRightAligned.'">'.$record['start'].'</td>';
868           if ($bean->getAttribute('chfinish'))
869             $body .= '<td nowrap style="'.$cellRightAligned.'">'.$record['finish'].'</td>';
870           if ($bean->getAttribute('chduration'))
871             $body .= '<td style="'.$cellRightAligned.'">'.$record['duration'].'</td>';
872           if ($bean->getAttribute('chunits'))
873             $body .= '<td style="'.$cellRightAligned.'">'.$record['units'].'</td>';
874           if ($bean->getAttribute('chnote'))
875             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['note']).'</td>';
876           if ($bean->getAttribute('chcost'))
877             $body .= '<td style="'.$cellRightAligned.'">'.$record['cost'].'</td>';
878           if ($bean->getAttribute('chpaid')) {
879             $body .= '<td style="'.$cellRightAligned.'">';
880             $body .= $record['paid'] == 1 ? $i18n->get('label.yes') : $i18n->get('label.no');
881             $body .= '</td>';
882           }
883           if ($bean->getAttribute('chip')) {
884             $body .= '<td style="'.$cellRightAligned.'">';
885             $body .= $record['modified'] ? $record['modified_ip'].' '.$record['modified'] : $record['created_ip'].' '.$record['created'];
886             $body .= '</td>';
887           }
888           if ($bean->getAttribute('chinvoice'))
889             $body .= '<td style="'.$cellRightAligned.'">'.htmlspecialchars($record['invoice']).'</td>';
890           $body .= '</tr>';
891
892           $prev_date = $record['date'];
893           if ($print_subtotals)
894             $prev_grouped_by = $record['grouped_by'];
895         }
896       }
897
898       // Print a terminating subtotal.
899       if ($print_subtotals) {
900         $body .= '<tr style="'.$rowSubtotal.'">';
901         $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.subtotal').'</td>';
902         $subtotal_name = htmlspecialchars($subtotals[$cur_grouped_by]['name']);
903         if ($canViewReports || $isClient) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'user' ? $subtotal_name : '').'</td>';
904         if ($bean->getAttribute('chclient')) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'client' ? $subtotal_name : '').'</td>';
905         if ($bean->getAttribute('chproject')) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'project' ? $subtotal_name : '').'</td>';
906         if ($bean->getAttribute('chtask')) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'task' ? $subtotal_name : '').'</td>';
907         if ($bean->getAttribute('chcf_1')) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'cf_1' ? $subtotal_name : '').'</td>';
908         if ($bean->getAttribute('chstart')) $body .= '<td></td>';
909         if ($bean->getAttribute('chfinish')) $body .= '<td></td>';
910         if ($bean->getAttribute('chduration')) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$cur_grouped_by]['time'].'</td>';
911         if ($bean->getAttribute('chunits')) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$cur_grouped_by]['units'].'</td>';
912         if ($bean->getAttribute('chnote')) $body .= '<td></td>';
913         if ($bean->getAttribute('chcost')) {
914           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
915           $body .= ($canViewReports || $isClient) ? $subtotals[$cur_grouped_by]['cost'] : $subtotals[$cur_grouped_by]['expenses'];
916           $body .= '</td>';
917         }
918         if ($bean->getAttribute('chpaid')) $body .= '<td></td>';
919         if ($bean->getAttribute('chip')) $body .= '<td></td>';
920         if ($bean->getAttribute('chinvoice')) $body .= '<td></td>';
921         $body .= '</tr>';
922       }
923
924       // Print totals.
925       $body .= '<tr><td>&nbsp;</td></tr>';
926       $body .= '<tr style="'.$rowSubtotal.'">';
927       $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.total').'</td>';
928       if ($canViewReports || $isClient) $body .= '<td></td>';
929       if ($bean->getAttribute('chclient')) $body .= '<td></td>';
930       if ($bean->getAttribute('chproject')) $body .= '<td></td>';
931       if ($bean->getAttribute('chtask')) $body .= '<td></td>';
932       if ($bean->getAttribute('chcf_1')) $body .= '<td></td>';
933       if ($bean->getAttribute('chstart')) $body .= '<td></td>';
934       if ($bean->getAttribute('chfinish')) $body .= '<td></td>';
935       if ($bean->getAttribute('chduration')) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$totals['time'].'</td>';
936       if ($bean->getAttribute('chunits')) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$totals['units'].'</td>';
937       if ($bean->getAttribute('chnote')) $body .= '<td></td>';
938       if ($bean->getAttribute('chcost')) {
939         $body .= '<td nowrap style="'.$cellRightAlignedSubtotal.'">'.htmlspecialchars($user->currency).' ';
940         $body .= ($canViewReports || $isClient) ? $totals['cost'] : $totals['expenses'];
941         $body .= '</td>';
942       }
943       if ($bean->getAttribute('chpaid')) $body .= '<td></td>';
944       if ($bean->getAttribute('chip')) $body .= '<td></td>';
945       if ($bean->getAttribute('chinvoice')) $body .= '<td></td>';
946       $body .= '</tr>';
947
948       $body .= '</table>';
949     }
950
951     // Output footer.
952     if (!defined('REPORT_FOOTER') || !(REPORT_FOOTER == false))
953       $body .= '<p style="text-align: center;">'.$i18n->get('form.mail.footer').'</p>';
954
955     // Finish creating email body.
956     $body .= '</body></html>';
957
958     return $body;
959   }
960
961   // checkFavReportCondition - checks whether it is okay to send fav report.
962   static function checkFavReportCondition($options, $condition)
963   {
964     $items = ttReportHelper::getItems($options);
965
966     $condition = str_replace('count', '', $condition);
967     $count_required = (int) trim(str_replace('>', '', $condition));
968
969     if (count($items) > $count_required)
970       return true; // Condition ok.
971
972     return false;
973   }
974
975   // prepareFavReportBody - prepares an email body for a favorite report.
976   static function prepareFavReportBody($options)
977   {
978     global $user;
979     global $i18n;
980
981     // Determine these once as they are used in multiple places in this function.
982     $canViewReports = $user->can('view_reports') || $user->can('view_all_reports');
983     $isClient = $user->isClient();
984
985     $items = ttReportHelper::getItems($options);
986     $group_by = $options['group_by'];
987     if ($group_by && 'no_grouping' != $group_by)
988       $subtotals = ttReportHelper::getSubtotals($options);
989     $totals = ttReportHelper::getTotals($options);
990
991     // Use custom fields plugin if it is enabled.
992     if ($user->isPluginEnabled('cf'))
993       $custom_fields = new CustomFields($user->group_id);
994
995     // Define some styles to use in email.
996     $style_title = 'text-align: center; font-size: 15pt; font-family: Arial, Helvetica, sans-serif;';
997     $tableHeader = 'font-weight: bold; background-color: #a6ccf7; text-align: left;';
998     $tableHeaderCentered = 'font-weight: bold; background-color: #a6ccf7; text-align: center;';
999     $rowItem = 'background-color: #ffffff;';
1000     $rowItemAlt = 'background-color: #f5f5f5;';
1001     $rowSubtotal = 'background-color: #e0e0e0;';
1002     $cellLeftAligned = 'text-align: left; vertical-align: top;';
1003     $cellRightAligned = 'text-align: right; vertical-align: top;';
1004     $cellLeftAlignedSubtotal = 'font-weight: bold; text-align: left; vertical-align: top;';
1005     $cellRightAlignedSubtotal = 'font-weight: bold; text-align: right; vertical-align: top;';
1006
1007     // Start creating email body.
1008     $body = '<html>';
1009     $body .= '<head><meta http-equiv="content-type" content="text/html; charset='.CHARSET.'"></head>';
1010     $body .= '<body>';
1011
1012     // Output title.
1013     $body .= '<p style="'.$style_title.'">'.$i18n->get('form.mail.report_subject').': '.$totals['start_date'].' - '.$totals['end_date'].'</p>';
1014
1015     // Output comment.
1016     // if ($comment) $body .= '<p>'.htmlspecialchars($comment).'</p>'; // No comment for fav. reports.
1017
1018     if ($options['show_totals_only']) {
1019       // Totals only report. Output subtotals.
1020
1021       // Determine group_by header.
1022       if ('cf_1' == $group_by)
1023         $group_by_header = htmlspecialchars($custom_fields->fields[0]['label']);
1024       else {
1025         $key = 'label.'.$group_by;
1026         $group_by_header = $i18n->get($key);
1027       }
1028
1029       $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
1030       $body .= '<tr>';
1031       $body .= '<td style="'.$tableHeader.'">'.$group_by_header.'</td>';
1032       if ($options['show_duration'])
1033         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.duration').'</td>';
1034       if ($options['show_work_units'])
1035         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.work_units_short').'</td>';
1036       if ($options['show_cost'])
1037         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.cost').'</td>';
1038       $body .= '</tr>';
1039       foreach($subtotals as $subtotal) {
1040         $body .= '<tr style="'.$rowSubtotal.'">';
1041         $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($subtotal['name'] ? htmlspecialchars($subtotal['name']) : '&nbsp;').'</td>';
1042         if ($options['show_duration']) {
1043           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1044           if ($subtotal['time'] <> '0:00') $body .= $subtotal['time'];
1045           $body .= '</td>';
1046         }
1047         if ($options['show_work_units']) {
1048           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1049           $body .= $subtotal['units'];
1050           $body .= '</td>';
1051         }
1052         if ($options['show_cost']) {
1053           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1054           $body .= ($canViewReports || $isClient) ? $subtotal['cost'] : $subtotal['expenses'];
1055           $body .= '</td>';
1056         }
1057         $body .= '</tr>';
1058       }
1059
1060       // Print totals.
1061       $body .= '<tr><td>&nbsp;</td></tr>';
1062       $body .= '<tr style="'.$rowSubtotal.'">';
1063       $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.total').'</td>';
1064       if ($options['show_duration']) {
1065         $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1066         if ($totals['time'] <> '0:00') $body .= $totals['time'];
1067         $body .= '</td>';
1068       }
1069       if ($options['show_work_units']) {
1070         $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1071         $body .= $totals['units'];
1072         $body .= '</td>';
1073       }
1074       if ($options['show_cost']) {
1075         $body .= '<td nowrap style="'.$cellRightAlignedSubtotal.'">'.htmlspecialchars($user->currency).' ';
1076         $body .= ($canViewReports || $isClient) ? $totals['cost'] : $totals['expenses'];
1077         $body .= '</td>';
1078       }
1079       $body .= '</tr>';
1080
1081       $body .= '</table>';
1082     } else {
1083       // Regular report.
1084
1085       // Print table header.
1086       $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
1087       $body .= '<tr>';
1088       $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.date').'</td>';
1089       if ($canViewReports || $isClient)
1090         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.user').'</td>';
1091       if ($options['show_client'])
1092         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.client').'</td>';
1093       if ($options['show_project'])
1094         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.project').'</td>';
1095       if ($options['show_task'])
1096         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.task').'</td>';
1097       if ($options['show_custom_field_1'])
1098         $body .= '<td style="'.$tableHeader.'">'.htmlspecialchars($custom_fields->fields[0]['label']).'</td>';
1099       if ($options['show_start'])
1100         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.start').'</td>';
1101       if ($options['show_end'])
1102         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.finish').'</td>';
1103       if ($options['show_duration'])
1104         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.duration').'</td>';
1105       if ($options['show_work_units'])
1106         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.work_units_short').'</td>';
1107       if ($options['show_note'])
1108         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.note').'</td>';
1109       if ($options['show_cost'])
1110         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.cost').'</td>';
1111       if ($options['show_paid'])
1112         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.paid').'</td>';
1113       if ($options['show_ip'])
1114         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.ip').'</td>';
1115       if ($options['show_invoice'])
1116         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.invoice').'</td>';
1117       $body .= '</tr>';
1118
1119       // Initialize variables to print subtotals.
1120       if ($items && 'no_grouping' != $group_by) {
1121         $print_subtotals = true;
1122         $first_pass = true;
1123         $prev_grouped_by = '';
1124         $cur_grouped_by = '';
1125       }
1126       // Initialize variables to alternate color of rows for different dates.
1127       $prev_date = '';
1128       $cur_date = '';
1129       $row_style = $rowItem;
1130
1131       // Print report items.
1132       if (is_array($items)) {
1133         foreach ($items as $record) {
1134           $cur_date = $record['date'];
1135           // Print a subtotal row after a block of grouped items.
1136           if ($print_subtotals) {
1137             $cur_grouped_by = $record['grouped_by'];
1138             if ($cur_grouped_by != $prev_grouped_by && !$first_pass) {
1139               $body .= '<tr style="'.$rowSubtotal.'">';
1140               $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.subtotal').'</td>';
1141               $subtotal_name = htmlspecialchars($subtotals[$prev_grouped_by]['name']);
1142               if ($canViewReports || $isClient) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'user' ? $subtotal_name : '').'</td>';
1143               if ($options['show_client']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'client' ? $subtotal_name : '').'</td>';
1144               if ($options['show_project']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'project' ? $subtotal_name : '').'</td>';
1145               if ($options['show_task']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'task' ? $subtotal_name : '').'</td>';
1146               if ($options['show_custom_field_1']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'cf_1' ? $subtotal_name : '').'</td>';
1147               if ($options['show_start']) $body .= '<td></td>';
1148               if ($options['show_end']) $body .= '<td></td>';
1149               if ($options['show_duration']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['time'].'</td>';
1150               if ($options['show_work_units']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['units'].'</td>';
1151               if ($options['show_note']) $body .= '<td></td>';
1152               if ($options['show_cost']) {
1153                 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1154                 $body .= ($canViewReports || $isClient) ? $subtotals[$prev_grouped_by]['cost'] : $subtotals[$prev_grouped_by]['expenses'];
1155                 $body .= '</td>';
1156               }
1157               if ($options['show_paid']) $body .= '<td></td>';
1158               if ($options['show_ip']) $body .= '<td></td>';
1159               if ($options['show_invoice']) $body .= '<td></td>';
1160               $body .= '</tr>';
1161               $body .= '<tr><td>&nbsp;</td></tr>';
1162             }
1163             $first_pass = false;
1164           }
1165
1166           // Print a regular row.
1167           if ($cur_date != $prev_date)
1168             $row_style = ($row_style == $rowItem) ? $rowItemAlt : $rowItem;
1169           $body .= '<tr style="'.$row_style.'">';
1170           $body .= '<td style="'.$cellLeftAligned.'">'.$record['date'].'</td>';
1171           if ($canViewReports || $isClient)
1172             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['user']).'</td>';
1173           if ($options['show_client'])
1174             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['client']).'</td>';
1175           if ($options['show_project'])
1176             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['project']).'</td>';
1177           if ($options['show_task'])
1178             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['task']).'</td>';
1179           if ($options['show_custom_field_1'])
1180             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['cf_1']).'</td>';
1181           if ($options['show_start'])
1182             $body .= '<td nowrap style="'.$cellRightAligned.'">'.$record['start'].'</td>';
1183           if ($options['show_end'])
1184             $body .= '<td nowrap style="'.$cellRightAligned.'">'.$record['finish'].'</td>';
1185           if ($options['show_duration'])
1186             $body .= '<td style="'.$cellRightAligned.'">'.$record['duration'].'</td>';
1187           if ($options['show_work_units'])
1188             $body .= '<td style="'.$cellRightAligned.'">'.$record['units'].'</td>';
1189           if ($options['show_note'])
1190             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['note']).'</td>';
1191           if ($options['show_cost'])
1192             $body .= '<td style="'.$cellRightAligned.'">'.$record['cost'].'</td>';
1193           if ($options['show_paid']) {
1194             $body .= '<td style="'.$cellRightAligned.'">';
1195             $body .= $record['paid'] == 1 ? $i18n->get('label.yes') : $i18n->get('label.no');
1196             $body .= '</td>';
1197           }
1198           if ($options['show_ip']) {
1199             $body .= '<td style="'.$cellRightAligned.'">';
1200             $body .= $record['modified'] ? $record['modified_ip'].' '.$record['modified'] : $record['created_ip'].' '.$record['created'];
1201             $body .= '</td>';
1202           }
1203           if ($options['show_invoice'])
1204             $body .= '<td style="'.$cellRightAligned.'">'.htmlspecialchars($record['invoice']).'</td>';
1205           $body .= '</tr>';
1206
1207           $prev_date = $record['date'];
1208           if ($print_subtotals)
1209             $prev_grouped_by = $record['grouped_by'];
1210         }
1211       }
1212
1213       // Print a terminating subtotal.
1214       if ($print_subtotals) {
1215         $body .= '<tr style="'.$rowSubtotal.'">';
1216         $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.subtotal').'</td>';
1217         $subtotal_name = htmlspecialchars($subtotals[$cur_grouped_by]['name']);
1218         if ($canViewReports || $isClient) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'user' ? $subtotal_name : '').'</td>';
1219         if ($options['show_client']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'client' ? $subtotal_name : '').'</td>';
1220         if ($options['show_project']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'project' ? $subtotal_name : '').'</td>';
1221         if ($options['show_task']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'task' ? $subtotal_name : '').'</td>';
1222         if ($options['show_custom_field_1']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'cf_1' ? $subtotal_name : '').'</td>';
1223         if ($options['show_start']) $body .= '<td></td>';
1224         if ($options['show_end']) $body .= '<td></td>';
1225         if ($options['show_duration']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$cur_grouped_by]['time'].'</td>';
1226         if ($options['show_work_units']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$cur_grouped_by]['units'].'</td>';
1227         if ($options['show_note']) $body .= '<td></td>';
1228         if ($options['show_cost']) {
1229           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1230           $body .= ($canViewReports || $isClient) ? $subtotals[$cur_grouped_by]['cost'] : $subtotals[$cur_grouped_by]['expenses'];
1231           $body .= '</td>';
1232         }
1233         if ($options['show_paid']) $body .= '<td></td>';
1234         if ($options['show_ip']) $body .= '<td></td>';
1235         if ($options['show_invoice']) $body .= '<td></td>';
1236         $body .= '</tr>';
1237       }
1238
1239       // Print totals.
1240       $body .= '<tr><td>&nbsp;</td></tr>';
1241       $body .= '<tr style="'.$rowSubtotal.'">';
1242       $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.total').'</td>';
1243       if ($canViewReports || $isClient) $body .= '<td></td>';
1244       if ($options['show_client']) $body .= '<td></td>';
1245       if ($options['show_project']) $body .= '<td></td>';
1246       if ($options['show_task']) $body .= '<td></td>';
1247       if ($options['show_custom_field_1']) $body .= '<td></td>';
1248       if ($options['show_start']) $body .= '<td></td>';
1249       if ($options['show_end']) $body .= '<td></td>';
1250       if ($options['show_duration']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$totals['time'].'</td>';
1251       if ($options['show_work_units']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$totals['units'].'</td>';
1252       if ($options['show_note']) $body .= '<td></td>';
1253       if ($options['show_cost']) {
1254         $body .= '<td nowrap style="'.$cellRightAlignedSubtotal.'">'.htmlspecialchars($user->currency).' ';
1255         $body .= ($canViewReports || $isClient) ? $totals['cost'] : $totals['expenses'];
1256         $body .= '</td>';
1257       }
1258       if ($options['show_paid']) $body .= '<td></td>';
1259       if ($options['show_ip']) $body .= '<td></td>';
1260       if ($options['show_invoice']) $body .= '<td></td>';
1261       $body .= '</tr>';
1262
1263       $body .= '</table>';
1264     }
1265
1266     // Output footer.
1267     if (!defined('REPORT_FOOTER') || !(REPORT_FOOTER == false))
1268       $body .= '<p style="text-align: center;">'.$i18n->get('form.mail.footer').'</p>';
1269
1270     // Finish creating email body.
1271     $body .= '</body></html>';
1272
1273     return $body;
1274   }
1275
1276   // sendFavReport - sends a favorite report to a specified email, called from cron.php
1277   static function sendFavReport($options, $subject, $email, $cc) {
1278     // We are called from cron.php, we have no $bean in session.
1279     // cron.php sets global $user and $i18n objects to match our favorite report user.
1280     global $user;
1281     global $i18n;
1282
1283     // Prepare report body.
1284     $body = ttReportHelper::prepareFavReportBody($options);
1285
1286     import('mail.Mailer');
1287     $mailer = new Mailer();
1288     $mailer->setCharSet(CHARSET);
1289     $mailer->setContentType('text/html');
1290     $mailer->setSender(SENDER);
1291     if (!empty($cc))
1292       $mailer->setReceiverCC($cc);
1293     if (!empty($user->bcc_email))
1294       $mailer->setReceiverBCC($user->bcc_email);
1295     $mailer->setReceiver($email);
1296     $mailer->setMailMode(MAIL_MODE);
1297     if (empty($subject)) $subject = $options['name'];
1298     if (!$mailer->send($subject, $body))
1299       return false;
1300
1301     return true;
1302   }
1303
1304   // getReportOptions - returns an array of report options constructed from session bean.
1305   //
1306   // Note: similarly to ttFavReportHelper::getReportOptions, this function is a part of
1307   // refactoring to simplify maintenance of report generating functions, as we currently
1308   // have 2 sets: normal reporting (from bean), and fav report emailing (from db fields).
1309   // Using options obtained from either db or bean shall allow us to use only one set of functions.
1310   static function getReportOptions($bean) {
1311     global $user;
1312
1313     // Prepare an array of report options.
1314     $options = array();
1315
1316     // Construct one by one.
1317     $options['name'] = null; // No name required.
1318     $options['user_id'] = $user->id; // Not sure if we need user_id here. Fav reports use it to recycle $user object in cron.php.
1319     $options['client_id'] = $bean->getAttribute('client');
1320     $options['cf_1_option_id'] = $bean->getAttribute('option');
1321     $options['project_id'] = $bean->getAttribute('project');
1322     $options['task_id'] = $bean->getAttribute('task');
1323     $options['billable'] = $bean->getAttribute('include_records');
1324     $options['invoice'] = $bean->getAttribute('invoice');
1325     $options['paid_status'] = $bean->getAttribute('paid_status');
1326     if (is_array($bean->getAttribute('users'))) $options['users'] = join(',', $bean->getAttribute('users'));
1327     $options['period'] = $bean->getAttribute('period');
1328     $options['period_start'] = $bean->getAttribute('start_date');
1329     $options['period_end'] = $bean->getAttribute('end_date');
1330     $options['show_client'] = $bean->getAttribute('chclient');
1331     $options['show_invoice'] = $bean->getAttribute('chinvoice');
1332     $options['show_paid'] = $bean->getAttribute('chpaid');
1333     $options['show_ip'] = $bean->getAttribute('chip');
1334     $options['show_project'] = $bean->getAttribute('chproject');
1335     $options['show_start'] = $bean->getAttribute('chstart');
1336     $options['show_duration'] = $bean->getAttribute('chduration');
1337     $options['show_cost'] = $bean->getAttribute('chcost');
1338     $options['show_task'] = $bean->getAttribute('chtask');
1339     $options['show_end'] = $bean->getAttribute('chfinish');
1340     $options['show_note'] = $bean->getAttribute('chnote');
1341     $options['show_custom_field_1'] = $bean->getAttribute('chcf_1');
1342     $options['show_work_units'] = $bean->getAttribute('chunits');
1343     $options['show_totals_only'] = $bean->getAttribute('chtotalsonly');
1344     $options['group_by'] = $bean->getAttribute('group_by');
1345     return $options;
1346   }
1347
1348   // verifyBean is a security function to make sure data in bean makes sense for a group.
1349   static function verifyBean($bean) {
1350     global $user;
1351
1352     // Check users.
1353     $users_in_bean = $bean->getAttribute('users');
1354     if (is_array($users_in_bean)) {
1355       $users_in_group = ttTeamHelper::getUsers();
1356       foreach ($users_in_group as $user_in_group) {
1357         $valid_ids[] = $user_in_group['id'];
1358       }
1359       foreach ($users_in_bean as $user_in_bean) {
1360         if (!in_array($user_in_bean, $valid_ids)) {
1361           return false;
1362         }
1363       }
1364     }
1365
1366     // TODO: add additional checks here. Perhaps do it before saving the bean for consistency.
1367     return true;
1368   }
1369 }