Refactored ttReportHelper::getItems for multiple group by condition.
[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     $no_grouping = ($options['group_by1'] == null || $options['group_by1'] == 'no_grouping') &&
131                    ($options['group_by2'] == null || $options['group_by2'] == 'no_grouping') &&
132                    ($options['group_by3'] == null || $options['group_by3'] == 'no_grouping');
133     $grouping_by_date = ($options['group_by1'] == 'date'|| $options['group_by2'] == 'date' || $options['group_by3'] == 'date');
134     $grouping_by_client = ($options['group_by1'] == 'client'|| $options['group_by2'] == 'client' || $options['group_by3'] == 'client');
135     $grouping_by_project = ($options['group_by1'] == 'project'|| $options['group_by2'] == 'project' || $options['group_by3'] == 'project');
136     $grouping_by_task = ($options['group_by1'] == 'task'|| $options['group_by2'] == 'task' || $options['group_by3'] == 'task');
137     $grouping_by_user = ($options['group_by1'] == 'user'|| $options['group_by2'] == 'user' || $options['group_by3'] == 'user');
138     $grouping_by_cf_1 = ($options['group_by1'] == 'cf_1'|| $options['group_by2'] == 'cf_1' || $options['group_by3'] == 'cf_1');
139
140     $group_by_option = $options['group_by1'];
141     $convertTo12Hour = ('%I:%M %p' == $user->time_format) && ($options['show_start'] || $options['show_end']);
142
143     // Prepare a query for time items in tt_log table.
144     $fields = array(); // An array of fields for database query.
145     array_push($fields, 'l.id as id');
146     array_push($fields, '1 as type'); // Type 1 is for tt_log entries.
147     array_push($fields, 'l.date as date');
148     if($canViewReports || $isClient)
149       array_push($fields, 'u.name as user');
150     // Add client name if it is selected.
151     if ($options['show_client'] || $grouping_by_client)
152       array_push($fields, 'c.name as client');
153     // Add project name if it is selected.
154     if ($options['show_project'] || $grouping_by_project)
155       array_push($fields, 'p.name as project');
156     // Add task name if it is selected.
157     if ($options['show_task'] || $grouping_by_task)
158       array_push($fields, 't.name as task');
159     // Add custom field.
160     $include_cf_1 = $options['show_custom_field_1'] || $grouping_by_cf_1;
161     if ($include_cf_1) {
162       $custom_fields = new CustomFields($user->group_id);
163       $cf_1_type = $custom_fields->fields[0]['type'];
164       if ($cf_1_type == CustomFields::TYPE_TEXT) {
165         array_push($fields, 'cfl.value as cf_1');
166       } elseif ($cf_1_type == CustomFields::TYPE_DROPDOWN) {
167         array_push($fields, 'cfo.value as cf_1');
168       }
169     }
170     // Add start time.
171     if ($options['show_start']) {
172       array_push($fields, "l.start as unformatted_start");
173       array_push($fields, "TIME_FORMAT(l.start, '%k:%i') as start");
174     }
175     // Add finish time.
176     if ($options['show_end'])
177       array_push($fields, "TIME_FORMAT(sec_to_time(time_to_sec(l.start) + time_to_sec(l.duration)), '%k:%i') as finish");
178     // Add duration.
179     if ($options['show_duration'])
180       array_push($fields, "TIME_FORMAT(l.duration, '%k:%i') as duration");
181     // Add work units.
182     if ($options['show_work_units']) {
183       if ($user->unit_totals_only)
184         array_push($fields, "null as units");
185       else
186         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");
187     }
188     // Add note.
189     if ($options['show_note'])
190       array_push($fields, 'l.comment as note');
191     // Handle cost.
192     $includeCost = $options['show_cost'];
193     if ($includeCost) {
194       if (MODE_TIME == $user->tracking_mode)
195         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.
196       else
197         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.
198       array_push($fields, "null as expense"); 
199     }
200     // Add paid status.
201     if ($canViewReports && $options['show_paid'])
202       array_push($fields, 'l.paid as paid');
203     // Add IP address.
204     if ($canViewReports && $options['show_ip']) {
205       array_push($fields, 'l.created as created');
206       array_push($fields, 'l.created_ip as created_ip');
207       array_push($fields, 'l.modified as modified');
208       array_push($fields, 'l.modified_ip as modified_ip');
209     }
210     // Add invoice name if it is selected.
211     if (($canViewReports || $isClient) && $options['show_invoice'])
212       array_push($fields, 'i.name as invoice');
213
214     // Prepare sql query part for left joins.
215     $left_joins = null;
216     if ($options['show_client'] || $grouping_by_client)
217       $left_joins .= " left join tt_clients c on (c.id = l.client_id)";
218     if (($canViewReports || $isClient) && $options['show_invoice'])
219       $left_joins .= " left join tt_invoices i on (i.id = l.invoice_id and i.status = 1)";
220     if ($canViewReports || $isClient || $user->isPluginEnabled('ex'))
221        $left_joins .= " left join tt_users u on (u.id = l.user_id)";
222     if ($options['show_project'] || $grouping_by_project)
223       $left_joins .= " left join tt_projects p on (p.id = l.project_id)";
224     if ($options['show_task'] || $grouping_by_task)
225       $left_joins .= " left join tt_tasks t on (t.id = l.task_id)";
226     if ($include_cf_1) {
227       if ($cf_1_type == CustomFields::TYPE_TEXT)
228         $left_joins .= " left join tt_custom_field_log cfl on (l.id = cfl.log_id and cfl.status = 1)";
229       elseif ($cf_1_type == CustomFields::TYPE_DROPDOWN) {
230         $left_joins .=  " left join tt_custom_field_log cfl on (l.id = cfl.log_id and cfl.status = 1)".
231           " left join tt_custom_field_options cfo on (cfl.option_id = cfo.id)";
232       }
233     }
234     if ($includeCost && MODE_TIME != $user->tracking_mode)
235       $left_joins .= " left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id)";
236
237     $where = ttReportHelper::getWhere($options);
238
239     // Construct sql query for tt_log items.
240     $sql = "select ".join(', ', $fields)." from tt_log l $left_joins $where";
241     // If we don't have expense items (such as when the Expenses plugin is disabled), the above is all sql we need,
242     // with an exception of sorting part, that is added in the end.
243
244     // However, when we have expenses, we need to do a union with a separate query for expense items from tt_expense_items table.
245     if ($options['show_cost'] && $user->isPluginEnabled('ex')) { // if ex(penses) plugin is enabled
246
247       $fields = array(); // An array of fields for database query.
248       array_push($fields, 'ei.id');
249       array_push($fields, '2 as type'); // Type 2 is for tt_expense_items entries.
250       array_push($fields, 'ei.date');
251       if($canViewReports || $isClient)
252         array_push($fields, 'u.name as user');
253       // Add client name if it is selected.
254       if ($options['show_client'] || $grouping_by_client)
255         array_push($fields, 'c.name as client');
256       // Add project name if it is selected.
257       if ($options['show_project'] || $grouping_by_project)
258         array_push($fields, 'p.name as project');
259       if ($options['show_task'] || $grouping_by_task)
260         array_push($fields, 'null'); // null for task name. We need to match column count for union.
261       if ($options['show_custom_field_1'] || $grouping_by_cf_1)
262         array_push($fields, 'null'); // null for cf_1.
263       if ($options['show_start']) {
264         array_push($fields, 'null'); // null for unformatted_start.
265         array_push($fields, 'null'); // null for start.
266       }
267       if ($options['show_end'])
268         array_push($fields, 'null'); // null for finish.
269       if ($options['show_duration'])
270         array_push($fields, 'null'); // null for duration.
271       if ($options['show_work_units'])
272         array_push($fields, 'null as units'); // null for work units.
273       // Use the note field to print item name.
274       if ($options['show_note'])
275         array_push($fields, 'ei.name as note');
276       array_push($fields, 'ei.cost as cost');
277       array_push($fields, 'ei.cost as expense');
278       // Add paid status.
279       if ($canViewReports && $options['show_paid'])
280         array_push($fields, 'ei.paid as paid');
281       // Add IP address.
282       if ($canViewReports && $options['show_ip']) {
283         array_push($fields, 'ei.created as created');
284         array_push($fields, 'ei.created_ip as created_ip');
285         array_push($fields, 'ei.modified as modified');
286         array_push($fields, 'ei.modified_ip as modified_ip');
287       }
288       // Add invoice name if it is selected.
289       if (($canViewReports || $isClient) && $options['show_invoice'])
290         array_push($fields, 'i.name as invoice');
291
292       // Prepare sql query part for left joins.
293       $left_joins = null;
294       if ($canViewReports || $isClient)
295         $left_joins .= " left join tt_users u on (u.id = ei.user_id)";
296       if ($options['show_client'] || $grouping_by_client)
297         $left_joins .= " left join tt_clients c on (c.id = ei.client_id)";
298       if ($options['show_project'] || $grouping_by_project)
299         $left_joins .= " left join tt_projects p on (p.id = ei.project_id)";
300       if (($canViewReports || $isClient) && $options['show_invoice'])
301         $left_joins .= " left join tt_invoices i on (i.id = ei.invoice_id and i.status = 1)";
302
303       $where = ttReportHelper::getExpenseWhere($options);
304
305       // Construct sql query for expense items.
306       $sql_for_expense_items = "select ".join(', ', $fields)." from tt_expense_items ei $left_joins $where";
307
308       // Construct a union.
309       $sql = "($sql) union all ($sql_for_expense_items)";
310     }
311
312     // Determine sort part.
313     $sort_part = ' order by ';
314     if ($no_grouping)
315       $sort_part .= 'date';
316     else {
317       $sort_part2 .= ($options['group_by1'] != null && $options['group_by1'] != 'no_grouping') ? ', '.$options['group_by1'] : '';
318       $sort_part2 .= ($options['group_by2'] != null && $options['group_by2'] != 'no_grouping') ? ', '.$options['group_by2'] : '';
319       $sort_part2 .= ($options['group_by3'] != null && $options['group_by3'] != 'no_grouping') ? ', '.$options['group_by3'] : '';
320       if (!$grouping_by_date) $sort_part2 .= ', date';
321       $sort_part .= ltrim($sort_part2, ', '); // Remove leading comma and space.
322     }
323     if (($canViewReports || $isClient) && $options['users'] && !$grouping_by_user)
324       $sort_part .= ', user, type';
325     if ($options['show_start'])
326       $sort_part .= ', unformatted_start';
327     $sort_part .= ', id';
328
329     $sql .= $sort_part;
330     // By now we are ready with sql.
331
332     // Obtain items for report.
333     $res = $mdb2->query($sql);
334     if (is_a($res, 'PEAR_Error')) die($res->getMessage());
335
336     while ($val = $res->fetchRow()) {
337       if ($convertTo12Hour) {
338         if($val['start'] != '')
339           $val['start'] = ttTimeHelper::to12HourFormat($val['start']);
340         if($val['finish'] != '')
341           $val['finish'] = ttTimeHelper::to12HourFormat($val['finish']);
342       }
343       if (isset($val['cost'])) {
344         if ('.' != $user->decimal_mark)
345           $val['cost'] = str_replace('.', $user->decimal_mark, $val['cost']);
346       }
347       if (isset($val['expense'])) {
348         if ('.' != $user->decimal_mark)
349           $val['expense'] = str_replace('.', $user->decimal_mark, $val['expense']);
350       }
351
352       if (!$no_grouping) $val['grouped_by'] = ttReportHelper::makeGroupByKey($options, $val);
353       $val['date'] = ttDateToUserFormat($val['date']);
354
355       $report_items[] = $val;
356     }
357
358     return $report_items;
359   }
360
361   // putInSession stores tt_log and tt_expense_items ids from a report in user session
362   // as 2 comma-separated lists.
363   static function putInSession($report_items) {
364     unset($_SESSION['report_item_ids']);
365     unset($_SESSION['report_item_expense_ids']);
366
367     // Iterate through records and build 2 comma-separated lists.
368     foreach($report_items as $item) {
369       if ($item['type'] == 1)
370         $report_item_ids .= ','.$item['id'];
371       else if ($item['type'] == 2)
372          $report_item_expense_ids .= ','.$item['id'];
373     }
374     $report_item_ids = trim($report_item_ids, ',');
375     $report_item_expense_ids = trim($report_item_expense_ids, ',');
376
377     // The lists are reqdy. Put them in session.
378     if ($report_item_ids) $_SESSION['report_item_ids'] = $report_item_ids;
379     if ($report_item_expense_ids) $_SESSION['report_item_expense_ids'] = $report_item_expense_ids;
380   }
381
382   // getFromSession obtains tt_log and tt_expense_items ids stored in user session.
383   static function getFromSession() {
384     $items = array();
385     $report_item_ids = $_SESSION['report_item_ids'];
386     if ($report_item_ids)
387       $items['report_item_ids'] = explode(',', $report_item_ids);
388     $report_item_expense_ids = $_SESSION['report_item_expense_ids'];
389     if ($report_item_expense_ids)
390       $items['report_item_expense_ids'] = explode(',', $report_item_expense_ids);
391     return $items;
392   }
393
394   // getSubtotals calculates report items subtotals when a report is grouped by.
395   // Without expenses, it's a simple select with group by.
396   // With expenses, it becomes a select with group by from a combined set of records obtained with "union all".
397   static function getSubtotals($options) {
398     global $user;
399
400     $group_by_option = $options['group_by1'];
401     if ('no_grouping' == $group_by_option) return null;
402
403     $mdb2 = getConnection();
404
405     // Start with sql to obtain subtotals for time items. This simple sql will be used when we have no expenses.
406
407     // Determine group by field and a required join.
408     switch ($group_by_option) {
409       case 'date':
410         $group_field = 'l.date';
411         $group_join = '';
412         break;
413       case 'user':
414         $group_field = 'u.name';
415         $group_join = 'left join tt_users u on (l.user_id = u.id) ';
416         break;
417       case 'client':
418         $group_field = 'c.name';
419         $group_join = 'left join tt_clients c on (l.client_id = c.id) ';
420         break;
421       case 'project':
422         $group_field = 'p.name';
423         $group_join = 'left join tt_projects p on (l.project_id = p.id) ';
424         break;
425       case 'task':
426         $group_field = 't.name';
427         $group_join = 'left join tt_tasks t on (l.task_id = t.id) ';
428         break;
429       case 'cf_1':
430         $group_field = 'cfo.value';
431         $custom_fields = new CustomFields($user->group_id);
432         if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_TEXT)
433           $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) ';
434         elseif ($custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN)
435           $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) ';
436         break;
437     }
438
439     $where = ttReportHelper::getWhere($options);
440     if ($options['show_cost']) {
441       if (MODE_TIME == $user->tracking_mode) {
442         if ($group_by_option != 'user')
443           $left_join = 'left join tt_users u on (l.user_id = u.id)';
444         $sql = "select $group_field as group_field, sum(time_to_sec(l.duration)) as time";
445         if ($options['show_work_units']) {
446           if ($user->unit_totals_only)
447             $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";
448           else
449             $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";
450         }
451         $sql .= ", sum(cast(l.billable * coalesce(u.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10, 2))) as cost,
452           null as expenses from tt_log l
453           $group_join $left_join $where group by $group_field";
454       } else {
455         // If we are including cost and tracking projects, our query (the same as above) needs to join the tt_user_project_binds table.
456         $sql = "select $group_field as group_field, sum(time_to_sec(l.duration)) as time";
457         if ($options['show_work_units']) {
458           if ($user->unit_totals_only)
459             $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";
460           else
461             $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";
462         }
463         $sql .= ", sum(cast(l.billable * coalesce(upb.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10,2))) as cost,
464           null as expenses from tt_log l 
465           $group_join
466           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";
467       }
468     } else {
469       $sql = "select $group_field as group_field, sum(time_to_sec(l.duration)) as time";
470       if ($options['show_work_units']) {
471         if ($user->unit_totals_only)
472           $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";
473         else
474           $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";
475       }
476       $sql .= ", null as expenses from tt_log l 
477         $group_join $where group by $group_field";
478     }
479     // By now we have sql for time items.
480
481     // However, when we have expenses, we need to do a union with a separate query for expense items from tt_expense_items table.
482     if ($options['show_cost'] && $user->isPluginEnabled('ex')) { // if ex(penses) plugin is enabled
483
484       // Determine group by field and a required join.
485       $group_join = null;
486       $group_field = 'null';
487       switch ($group_by_option) {
488         case 'date':
489           $group_field = 'ei.date';
490           $group_join = '';
491           break;
492         case 'user':
493           $group_field = 'u.name';
494           $group_join = 'left join tt_users u on (ei.user_id = u.id) ';
495           break;
496         case 'client':
497           $group_field = 'c.name';
498           $group_join = 'left join tt_clients c on (ei.client_id = c.id) ';
499           break;
500         case 'project':
501           $group_field = 'p.name';
502           $group_join = 'left join tt_projects p on (ei.project_id = p.id) ';
503           break;
504       }
505
506       $where = ttReportHelper::getExpenseWhere($options);
507       $sql_for_expenses = "select $group_field as group_field, null as time";
508       if ($options['show_work_units']) $sql_for_expenses .= ", null as units";
509       $sql_for_expenses .= ", sum(ei.cost) as cost, sum(ei.cost) as expenses from tt_expense_items ei $group_join $where";
510       // Add a "group by" clause if we are grouping.
511       if ('null' != $group_field) $sql_for_expenses .= " group by $group_field";
512
513       // Create a combined query.
514       $combined = "select group_field, sum(time) as time";
515       if ($options['show_work_units']) $combined .= ", sum(units) as units";
516       $combined .= ", sum(cost) as cost, sum(expenses) as expenses from (($sql) union all ($sql_for_expenses)) t group by group_field";
517       $sql = $combined;
518     }
519
520     // Execute query.
521     $res = $mdb2->query($sql);
522     if (is_a($res, 'PEAR_Error')) die($res->getMessage());
523
524     while ($val = $res->fetchRow()) {
525       if ('date' == $group_by_option) {
526         $val['group_field'] = ttDateToUserFormat($val['group_field']);
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($options, $comment = null)
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
669     $items = ttReportHelper::getItems($options);
670     $group_by = $options['group_by1'];
671     if ($group_by && 'no_grouping' != $group_by)
672       $subtotals = ttReportHelper::getSubtotals($options);
673     $totals = ttReportHelper::getTotals($options);
674
675     // Use custom fields plugin if it is enabled.
676     if ($user->isPluginEnabled('cf'))
677       $custom_fields = new CustomFields($user->group_id);
678
679     // Define some styles to use in email.
680     $style_title = 'text-align: center; font-size: 15pt; font-family: Arial, Helvetica, sans-serif;';
681     $tableHeader = 'font-weight: bold; background-color: #a6ccf7; text-align: left;';
682     $tableHeaderCentered = 'font-weight: bold; background-color: #a6ccf7; text-align: center;';
683     $rowItem = 'background-color: #ffffff;';
684     $rowItemAlt = 'background-color: #f5f5f5;';
685     $rowSubtotal = 'background-color: #e0e0e0;';
686     $cellLeftAligned = 'text-align: left; vertical-align: top;';
687     $cellRightAligned = 'text-align: right; vertical-align: top;';
688     $cellLeftAlignedSubtotal = 'font-weight: bold; text-align: left; vertical-align: top;';
689     $cellRightAlignedSubtotal = 'font-weight: bold; text-align: right; vertical-align: top;';
690
691     // Start creating email body.
692     $body = '<html>';
693     $body .= '<head><meta http-equiv="content-type" content="text/html; charset='.CHARSET.'"></head>';
694     $body .= '<body>';
695
696     // Output title.
697     $body .= '<p style="'.$style_title.'">'.$i18n->get('form.mail.report_subject').': '.$totals['start_date'].' - '.$totals['end_date'].'</p>';
698
699     // Output comment.
700     if ($comment) $body .= '<p>'.htmlspecialchars($comment).'</p>';
701
702     if ($options['show_totals_only']) {
703       // Totals only report. Output subtotals.
704
705       // Determine group_by header.
706       if ('cf_1' == $group_by)
707         $group_by_header = htmlspecialchars($custom_fields->fields[0]['label']);
708       else {
709         $key = 'label.'.$group_by;
710         $group_by_header = $i18n->get($key);
711       }
712
713       $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
714       $body .= '<tr>';
715       $body .= '<td style="'.$tableHeader.'">'.$group_by_header.'</td>';
716       if ($options['show_duration'])
717         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.duration').'</td>';
718       if ($options['show_work_units'])
719         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.work_units_short').'</td>';
720       if ($options['show_cost'])
721         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.cost').'</td>';
722       $body .= '</tr>';
723       foreach($subtotals as $subtotal) {
724         $body .= '<tr style="'.$rowSubtotal.'">';
725         $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($subtotal['name'] ? htmlspecialchars($subtotal['name']) : '&nbsp;').'</td>';
726         if ($options['show_duration']) {
727           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
728           if ($subtotal['time'] <> '0:00') $body .= $subtotal['time'];
729           $body .= '</td>';
730         }
731         if ($options['show_work_units']) {
732           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
733           $body .= $subtotal['units'];
734           $body .= '</td>';
735         }
736         if ($options['show_cost']) {
737           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
738           $body .= ($canViewReports || $isClient) ? $subtotal['cost'] : $subtotal['expenses'];
739           $body .= '</td>';
740         }
741         $body .= '</tr>';
742       }
743
744       // Print totals.
745       $body .= '<tr><td>&nbsp;</td></tr>';
746       $body .= '<tr style="'.$rowSubtotal.'">';
747       $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.total').'</td>';
748       if ($options['show_duration']) {
749         $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
750         if ($totals['time'] <> '0:00') $body .= $totals['time'];
751         $body .= '</td>';
752       }
753       if ($options['show_work_units']) {
754         $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
755         $body .= $totals['units'];
756         $body .= '</td>';
757       }
758       if ($options['show_cost']) {
759         $body .= '<td nowrap style="'.$cellRightAlignedSubtotal.'">'.htmlspecialchars($user->currency).' ';
760         $body .= ($canViewReports || $isClient) ? $totals['cost'] : $totals['expenses'];
761         $body .= '</td>';
762       }
763       $body .= '</tr>';
764
765       $body .= '</table>';
766     } else {
767       // Regular report.
768
769       // Print table header.
770       $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
771       $body .= '<tr>';
772       $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.date').'</td>';
773       if ($canViewReports || $isClient)
774         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.user').'</td>';
775       if ($options['show_client'])
776         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.client').'</td>';
777       if ($options['show_project'])
778         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.project').'</td>';
779       if ($options['show_task'])
780         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.task').'</td>';
781       if ($options['show_custom_field_1'])
782         $body .= '<td style="'.$tableHeader.'">'.htmlspecialchars($custom_fields->fields[0]['label']).'</td>';
783       if ($options['show_start'])
784         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.start').'</td>';
785       if ($options['show_end'])
786         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.finish').'</td>';
787       if ($options['show_duration'])
788         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.duration').'</td>';
789       if ($options['show_work_units'])
790         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.work_units_short').'</td>';
791       if ($options['show_note'])
792         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.note').'</td>';
793       if ($options['show_cost'])
794         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.cost').'</td>';
795       if ($options['show_paid'])
796         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.paid').'</td>';
797       if ($options['show_ip'])
798         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.ip').'</td>';
799       if ($options['show_invoice'])
800         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.invoice').'</td>';
801       $body .= '</tr>';
802
803       // Initialize variables to print subtotals.
804       if ($items && 'no_grouping' != $group_by) {
805         $print_subtotals = true;
806         $first_pass = true;
807         $prev_grouped_by = '';
808         $cur_grouped_by = '';
809       }
810       // Initialize variables to alternate color of rows for different dates.
811       $prev_date = '';
812       $cur_date = '';
813       $row_style = $rowItem;
814
815       // Print report items.
816       if (is_array($items)) {
817         foreach ($items as $record) {
818           $cur_date = $record['date'];
819           // Print a subtotal row after a block of grouped items.
820           if ($print_subtotals) {
821             $cur_grouped_by = $record['grouped_by'];
822             if ($cur_grouped_by != $prev_grouped_by && !$first_pass) {
823               $body .= '<tr style="'.$rowSubtotal.'">';
824               $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.subtotal').'</td>';
825               $subtotal_name = htmlspecialchars($subtotals[$prev_grouped_by]['name']);
826               if ($canViewReports || $isClient) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'user' ? $subtotal_name : '').'</td>';
827               if ($options['show_client']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'client' ? $subtotal_name : '').'</td>';
828               if ($options['show_project']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'project' ? $subtotal_name : '').'</td>';
829               if ($options['show_task']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'task' ? $subtotal_name : '').'</td>';
830               if ($options['show_custom_field_1']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'cf_1' ? $subtotal_name : '').'</td>';
831               if ($options['show_start']) $body .= '<td></td>';
832               if ($options['show_end']) $body .= '<td></td>';
833               if ($options['show_duration']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['time'].'</td>';
834               if ($options['show_work_units']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['units'].'</td>';
835               if ($options['show_note']) $body .= '<td></td>';
836               if ($options['show_cost']) {
837                 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
838                 $body .= ($canViewReports || $isClient) ? $subtotals[$prev_grouped_by]['cost'] : $subtotals[$prev_grouped_by]['expenses'];
839                 $body .= '</td>';
840               }
841               if ($options['show_paid']) $body .= '<td></td>';
842               if ($options['show_ip']) $body .= '<td></td>';
843               if ($options['show_invoice']) $body .= '<td></td>';
844               $body .= '</tr>';
845               $body .= '<tr><td>&nbsp;</td></tr>';
846             }
847             $first_pass = false;
848           }
849
850           // Print a regular row.
851           if ($cur_date != $prev_date)
852             $row_style = ($row_style == $rowItem) ? $rowItemAlt : $rowItem;
853           $body .= '<tr style="'.$row_style.'">';
854           $body .= '<td style="'.$cellLeftAligned.'">'.$record['date'].'</td>';
855           if ($canViewReports || $isClient)
856             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['user']).'</td>';
857           if ($options['show_client'])
858             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['client']).'</td>';
859           if ($options['show_project'])
860             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['project']).'</td>';
861           if ($options['show_task'])
862             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['task']).'</td>';
863           if ($options['show_custom_field_1'])
864             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['cf_1']).'</td>';
865           if ($options['show_start'])
866             $body .= '<td nowrap style="'.$cellRightAligned.'">'.$record['start'].'</td>';
867           if ($options['show_end'])
868             $body .= '<td nowrap style="'.$cellRightAligned.'">'.$record['finish'].'</td>';
869           if ($options['show_duration'])
870             $body .= '<td style="'.$cellRightAligned.'">'.$record['duration'].'</td>';
871           if ($options['show_work_units'])
872             $body .= '<td style="'.$cellRightAligned.'">'.$record['units'].'</td>';
873           if ($options['show_note'])
874             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['note']).'</td>';
875           if ($options['show_cost'])
876             $body .= '<td style="'.$cellRightAligned.'">'.$record['cost'].'</td>';
877           if ($options['show_paid']) {
878             $body .= '<td style="'.$cellRightAligned.'">';
879             $body .= $record['paid'] == 1 ? $i18n->get('label.yes') : $i18n->get('label.no');
880             $body .= '</td>';
881           }
882           if ($options['show_ip']) {
883             $body .= '<td style="'.$cellRightAligned.'">';
884             $body .= $record['modified'] ? $record['modified_ip'].' '.$record['modified'] : $record['created_ip'].' '.$record['created'];
885             $body .= '</td>';
886           }
887           if ($options['show_invoice'])
888             $body .= '<td style="'.$cellRightAligned.'">'.htmlspecialchars($record['invoice']).'</td>';
889           $body .= '</tr>';
890
891           $prev_date = $record['date'];
892           if ($print_subtotals)
893             $prev_grouped_by = $record['grouped_by'];
894         }
895       }
896
897       // Print a terminating subtotal.
898       if ($print_subtotals) {
899         $body .= '<tr style="'.$rowSubtotal.'">';
900         $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.subtotal').'</td>';
901         $subtotal_name = htmlspecialchars($subtotals[$cur_grouped_by]['name']);
902         if ($canViewReports || $isClient) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'user' ? $subtotal_name : '').'</td>';
903         if ($options['show_client']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'client' ? $subtotal_name : '').'</td>';
904         if ($options['show_project']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'project' ? $subtotal_name : '').'</td>';
905         if ($options['show_task']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'task' ? $subtotal_name : '').'</td>';
906         if ($options['show_custom_field_1']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'cf_1' ? $subtotal_name : '').'</td>';
907         if ($options['show_start']) $body .= '<td></td>';
908         if ($options['show_end']) $body .= '<td></td>';
909         if ($options['show_duration']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$cur_grouped_by]['time'].'</td>';
910         if ($options['show_work_units']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$cur_grouped_by]['units'].'</td>';
911         if ($options['show_note']) $body .= '<td></td>';
912         if ($options['show_cost']) {
913           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
914           $body .= ($canViewReports || $isClient) ? $subtotals[$cur_grouped_by]['cost'] : $subtotals[$cur_grouped_by]['expenses'];
915           $body .= '</td>';
916         }
917         if ($options['show_paid']) $body .= '<td></td>';
918         if ($options['show_ip']) $body .= '<td></td>';
919         if ($options['show_invoice']) $body .= '<td></td>';
920         $body .= '</tr>';
921       }
922
923       // Print totals.
924       $body .= '<tr><td>&nbsp;</td></tr>';
925       $body .= '<tr style="'.$rowSubtotal.'">';
926       $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.total').'</td>';
927       if ($canViewReports || $isClient) $body .= '<td></td>';
928       if ($options['show_client']) $body .= '<td></td>';
929       if ($options['show_project']) $body .= '<td></td>';
930       if ($options['show_task']) $body .= '<td></td>';
931       if ($options['show_custom_field_1']) $body .= '<td></td>';
932       if ($options['show_start']) $body .= '<td></td>';
933       if ($options['show_end']) $body .= '<td></td>';
934       if ($options['show_duration']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$totals['time'].'</td>';
935       if ($options['show_work_units']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$totals['units'].'</td>';
936       if ($options['show_note']) $body .= '<td></td>';
937       if ($options['show_cost']) {
938         $body .= '<td nowrap style="'.$cellRightAlignedSubtotal.'">'.htmlspecialchars($user->currency).' ';
939         $body .= ($canViewReports || $isClient) ? $totals['cost'] : $totals['expenses'];
940         $body .= '</td>';
941       }
942       if ($options['show_paid']) $body .= '<td></td>';
943       if ($options['show_ip']) $body .= '<td></td>';
944       if ($options['show_invoice']) $body .= '<td></td>';
945       $body .= '</tr>';
946
947       $body .= '</table>';
948     }
949
950     // Output footer.
951     if (!defined('REPORT_FOOTER') || !(REPORT_FOOTER == false))
952       $body .= '<p style="text-align: center;">'.$i18n->get('form.mail.footer').'</p>';
953
954     // Finish creating email body.
955     $body .= '</body></html>';
956
957     return $body;
958   }
959
960   // checkFavReportCondition - checks whether it is okay to send fav report.
961   static function checkFavReportCondition($options, $condition)
962   {
963     $items = ttReportHelper::getItems($options);
964
965     $condition = trim(str_replace('count', '', $condition));
966
967     $greater_or_equal = ttStartsWith($condition, '>=');
968     if ($greater_or_equal) $condition = trim(str_replace('>=', '', $condition));
969
970     $less_or_equal = ttStartsWith($condition, '<=');
971     if ($less_or_equal) $condition = trim(str_replace('<=', '', $condition));
972
973     $not_equal = ttStartsWith($condition, '<>');
974     if ($not_equal) $condition = trim(str_replace('<>', '', $condition));
975
976     $greater = ttStartsWith($condition, '>');
977     if ($greater) $condition = trim(str_replace('>', '', $condition));
978
979     $less = ttStartsWith($condition, '<');
980     if ($less) $condition = trim(str_replace('<', '', $condition));
981
982     $equal = ttStartsWith($condition, '=');
983     if ($equal) $condition = trim(str_replace('=', '', $condition));
984
985     $count_required = (int) $condition;
986
987     if ($greater && count($items) > $count_required) return true;
988     if ($greater_or_equal && count($items) >= $count_required) return true;
989     if ($less && count($items) < $count_required) return true;
990     if ($less_or_equal && count($items) <= $count_required) return true;
991     if ($equal && count($items) == $count_required) return true;
992     if ($not_equal && count($items) <> $count_required) return true;
993
994     return false;
995   }
996
997   // sendFavReport - sends a favorite report to a specified email, called from cron.php
998   static function sendFavReport($options, $subject, $email, $cc) {
999     // We are called from cron.php, we have no $bean in session.
1000     // cron.php sets global $user and $i18n objects to match our favorite report user.
1001     global $user;
1002     global $i18n;
1003
1004     // Prepare report body.
1005     $body = ttReportHelper::prepareReportBody($options);
1006
1007     import('mail.Mailer');
1008     $mailer = new Mailer();
1009     $mailer->setCharSet(CHARSET);
1010     $mailer->setContentType('text/html');
1011     $mailer->setSender(SENDER);
1012     if (!empty($cc))
1013       $mailer->setReceiverCC($cc);
1014     if (!empty($user->bcc_email))
1015       $mailer->setReceiverBCC($user->bcc_email);
1016     $mailer->setReceiver($email);
1017     $mailer->setMailMode(MAIL_MODE);
1018     if (empty($subject)) $subject = $options['name'];
1019     if (!$mailer->send($subject, $body))
1020       return false;
1021
1022     return true;
1023   }
1024
1025   // getReportOptions - returns an array of report options constructed from session bean.
1026   //
1027   // Note: similarly to ttFavReportHelper::getReportOptions, this function is a part of
1028   // refactoring to simplify maintenance of report generating functions, as we currently
1029   // have 2 sets: normal reporting (from bean), and fav report emailing (from db fields).
1030   // Using options obtained from either db or bean shall allow us to use only one set of functions.
1031   static function getReportOptions($bean) {
1032     global $user;
1033
1034     // Prepare an array of report options.
1035     $options = array();
1036
1037     // Construct one by one.
1038     $options['name'] = null; // No name required.
1039     $options['user_id'] = $user->id; // Not sure if we need user_id here. Fav reports use it to recycle $user object in cron.php.
1040     $options['client_id'] = $bean->getAttribute('client');
1041     $options['cf_1_option_id'] = $bean->getAttribute('option');
1042     $options['project_id'] = $bean->getAttribute('project');
1043     $options['task_id'] = $bean->getAttribute('task');
1044     $options['billable'] = $bean->getAttribute('include_records');
1045     $options['invoice'] = $bean->getAttribute('invoice');
1046     $options['paid_status'] = $bean->getAttribute('paid_status');
1047     if (is_array($bean->getAttribute('users'))) $options['users'] = join(',', $bean->getAttribute('users'));
1048     $options['period'] = $bean->getAttribute('period');
1049     $options['period_start'] = $bean->getAttribute('start_date');
1050     $options['period_end'] = $bean->getAttribute('end_date');
1051     $options['show_client'] = $bean->getAttribute('chclient');
1052     $options['show_invoice'] = $bean->getAttribute('chinvoice');
1053     $options['show_paid'] = $bean->getAttribute('chpaid');
1054     $options['show_ip'] = $bean->getAttribute('chip');
1055     $options['show_project'] = $bean->getAttribute('chproject');
1056     $options['show_start'] = $bean->getAttribute('chstart');
1057     $options['show_duration'] = $bean->getAttribute('chduration');
1058     $options['show_cost'] = $bean->getAttribute('chcost');
1059     $options['show_task'] = $bean->getAttribute('chtask');
1060     $options['show_end'] = $bean->getAttribute('chfinish');
1061     $options['show_note'] = $bean->getAttribute('chnote');
1062     $options['show_custom_field_1'] = $bean->getAttribute('chcf_1');
1063     $options['show_work_units'] = $bean->getAttribute('chunits');
1064     $options['show_totals_only'] = $bean->getAttribute('chtotalsonly');
1065     $options['group_by1'] = $bean->getAttribute('group_by1');
1066     $options['group_by2'] = $bean->getAttribute('group_by2');
1067     $options['group_by3'] = $bean->getAttribute('group_by3');
1068     return $options;
1069   }
1070
1071   // verifyBean is a security function to make sure data in bean makes sense for a group.
1072   static function verifyBean($bean) {
1073     global $user;
1074
1075     // Check users.
1076     $users_in_bean = $bean->getAttribute('users');
1077     if (is_array($users_in_bean)) {
1078       $users_in_group = ttTeamHelper::getUsers();
1079       foreach ($users_in_group as $user_in_group) {
1080         $valid_ids[] = $user_in_group['id'];
1081       }
1082       foreach ($users_in_bean as $user_in_bean) {
1083         if (!in_array($user_in_bean, $valid_ids)) {
1084           return false;
1085         }
1086       }
1087     }
1088
1089     // TODO: add additional checks here. Perhaps do it before saving the bean for consistency.
1090     return true;
1091   }
1092
1093   // makeGroupByKey - builds a combined group by key from group_by1, group_by2 and group_by3 values
1094   // (passed in $options) and a row of data ($row obtained from a db query).
1095   static function makeGroupByKey($options, $row) {
1096     if ($options['group_by1'] != null && $options['group_by1'] != 'no_grouping') {
1097       // We have group_by1.
1098       $group_by1 = $options['group_by1'];
1099       $group_by1_value = $row[$group_by1];
1100       if ($group_by1 == 'date') $group_by1_value = ttDateToUserFormat($group_by1_value);
1101       $group_by_key .= ' - '.$group_by1_value;
1102     }
1103     if ($options['group_by2'] != null && $options['group_by2'] != 'no_grouping') {
1104       // We have group_by2.
1105       $group_by2 = $options['group_by2'];
1106       $group_by2_value = $row[$group_by2];
1107       if ($group_by2 == 'date') $group_by2_value = ttDateToUserFormat($group_by2_value);
1108       $group_by_key .= ' - '.$group_by2_value;
1109     }
1110     if ($options['group_by3'] != null && $options['group_by3'] != 'no_grouping') {
1111       // We have group_by3.
1112       $group_by3 = $options['group_by3'];
1113       $group_by3_value = $row[$group_by3];
1114       if ($group_by3 == 'date') $group_by3_value = ttDateToUserFormat($group_by3_value);
1115       $group_by_key .= ' - '.$group_by3_value;
1116     }
1117     $group_by_key = trim($group_by_key, ' -');
1118     return $group_by_key;
1119   }
1120 }