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