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