Fixed date format for a subgroup report.
[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', 0);
195         $minutesInUnit = $user->getConfigInt('minutes_in_unit', 15);
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     $mdb2 = getConnection();
467
468     $trackingMode = $user->getTrackingMode();
469     $decimalMark = $user->getDecimalMark();
470     $where = ttReportHelper::getWhere($options);
471
472     // Prepare parts.
473     $time_part = "sum(time_to_sec(l.duration)) as time";
474     if ($options['show_work_units']) {
475       $unitTotalsOnly = $user->getConfigOption('unit_totals_only');
476       $firstUnitThreshold = $user->getConfigInt('1st_unit_threshold', 0);
477       $minutesInUnit = $user->getConfigInt('minutes_in_unit', 15);
478       $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";
479     }
480     if ($options['show_cost']) {
481       if (MODE_TIME == $trackingMode)
482         $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";
483       else
484         $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";
485     } else {
486       $cost_part = ", null as cost, null as expenses";
487     }
488     if ($options['show_cost']) {
489       if (MODE_TIME == $trackingMode) {
490         $left_joins = "left join tt_users u on (l.user_id = u.id)";
491       } else {
492         $left_joins = "left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id)";
493       }
494     }
495     // Prepare a query for time items.
496     $sql = "select $time_part $units_part $cost_part from tt_log l $left_joins $where";
497
498     // If we have expenses, query becomes a bit more complex.
499     if ($options['show_cost'] && $user->isPluginEnabled('ex')) {
500       $where = ttReportHelper::getExpenseWhere($options);
501       $sql_for_expenses = "select null as time";
502       if ($options['show_work_units']) $sql_for_expenses .= ", null as units";
503       $sql_for_expenses .= ", sum(cost) as cost, sum(cost) as expenses from tt_expense_items ei $where";
504
505       // Create a combined query.
506       $combined = "select sum(time) as time";
507       if ($options['show_work_units']) $combined .= ", sum(units) as units";
508       $combined .= ", sum(cost) as cost, sum(expenses) as expenses from (($sql) union all ($sql_for_expenses)) t";
509       $sql = $combined;
510     }
511
512     // Execute query.
513     $res = $mdb2->query($sql);
514     if (is_a($res, 'PEAR_Error')) die($res->getMessage());
515
516     $val = $res->fetchRow();
517     $total_time = $val['time'] ? sec_to_time_fmt_hm($val['time']) : null;
518     if ($options['show_cost']) {
519       $total_cost = $val['cost'];
520       if (!$total_cost) $total_cost = '0.00';
521       if ('.' != $decimalMark)
522         $total_cost = str_replace('.', $decimalMark, $total_cost);
523       $total_expenses = $val['expenses'];
524       if (!$total_expenses) $total_expenses = '0.00';
525       if ('.' != $decimalMark)
526         $total_expenses = str_replace('.', $decimalMark, $total_expenses);
527     }
528
529     $dateFormat = $user->getDateFormat();
530     if ($options['period'])
531       $period = new Period($options['period'], new DateAndTime($dateFormat));
532     else {
533       $period = new Period();
534       $period->setPeriod(
535         new DateAndTime($dateFormat, $options['period_start']),
536         new DateAndTime($dateFormat, $options['period_end']));
537     }
538
539     $totals['start_date'] = $period->getStartDate();
540     $totals['end_date'] = $period->getEndDate();
541     $totals['time'] = $total_time;
542     $totals['units'] = $val['units'];
543     $totals['cost'] = $total_cost;
544     $totals['expenses'] = $total_expenses;
545
546     return $totals;
547   }
548
549   // The assignToInvoice assigns a set of records to a specific invoice.
550   static function assignToInvoice($invoice_id, $time_log_ids, $expense_item_ids) {
551     global $user;
552     $mdb2 = getConnection();
553
554     $group_id = $user->getGroup();
555     $org_id = $user->org_id;
556
557     if ($time_log_ids) {
558       $sql = "update tt_log set invoice_id = ".$mdb2->quote($invoice_id).
559         " where id in(".join(', ', $time_log_ids).") and group_id = $group_id and org_id = $org_id";
560       $affected = $mdb2->exec($sql);
561       if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
562     }
563     if ($expense_item_ids) {
564       $sql = "update tt_expense_items set invoice_id = ".$mdb2->quote($invoice_id).
565         " where id in(".join(', ', $expense_item_ids).") and group_id = $group_id and org_id = $org_id";
566       $affected = $mdb2->exec($sql);
567       if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
568     }
569   }
570
571   // The markPaid marks a set of records as either paid or unpaid.
572   static function markPaid($time_log_ids, $expense_item_ids, $paid = true) {
573     global $user;
574     $mdb2 = getConnection();
575
576     $group_id = $user->getGroup();
577     $org_id = $user->org_id;
578
579     $paid_val = (int) $paid;
580     if ($time_log_ids) {
581       $sql = "update tt_log set paid = $paid_val".
582         " where id in(".join(', ', $time_log_ids).") and group_id = $group_id and org_id = $org_id";
583       $affected = $mdb2->exec($sql);
584       if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
585     }
586     if ($expense_item_ids) {
587       $sql = "update tt_expense_items set paid = $paid_val".
588         " where id in(".join(', ', $expense_item_ids).") and group_id = $group_id and org_id = $org_id";
589       $affected = $mdb2->exec($sql);
590       if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
591     }
592   }
593
594   // prepareReportBody - prepares an email body for report.
595   static function prepareReportBody($options, $comment = null)
596   {
597     global $user;
598     global $i18n;
599
600     // Determine these once as they are used in multiple places in this function.
601     $canViewReports = $user->can('view_reports') || $user->can('view_all_reports');
602     $isClient = $user->isClient();
603
604     $items = ttReportHelper::getItems($options);
605     $grouping = ttReportHelper::grouping($options);
606     if ($grouping)
607       $subtotals = ttReportHelper::getSubtotals($options);
608     $totals = ttReportHelper::getTotals($options);
609
610     // Use custom fields plugin if it is enabled.
611     if ($user->isPluginEnabled('cf'))
612       $custom_fields = new CustomFields();
613
614     // Define some styles to use in email.
615     $style_title = 'text-align: center; font-size: 15pt; font-family: Arial, Helvetica, sans-serif;';
616     $tableHeader = 'font-weight: bold; background-color: #a6ccf7; text-align: left;';
617     $tableHeaderCentered = 'font-weight: bold; background-color: #a6ccf7; text-align: center;';
618     $rowItem = 'background-color: #ffffff;';
619     $rowItemAlt = 'background-color: #f5f5f5;';
620     $rowSubtotal = 'background-color: #e0e0e0;';
621     $cellLeftAligned = 'text-align: left; vertical-align: top;';
622     $cellRightAligned = 'text-align: right; vertical-align: top;';
623     $cellLeftAlignedSubtotal = 'font-weight: bold; text-align: left; vertical-align: top;';
624     $cellRightAlignedSubtotal = 'font-weight: bold; text-align: right; vertical-align: top;';
625
626     // Start creating email body.
627     $body = '<html>';
628     $body .= '<head><meta http-equiv="content-type" content="text/html; charset='.CHARSET.'"></head>';
629     $body .= '<body>';
630
631     // Output title.
632     $body .= '<p style="'.$style_title.'">'.$i18n->get('form.mail.report_subject').': '.$totals['start_date'].' - '.$totals['end_date'].'</p>';
633
634     // Output comment.
635     if ($comment) $body .= '<p>'.htmlspecialchars($comment).'</p>';
636
637     if ($options['show_totals_only']) {
638       // Totals only report. Output subtotals.
639       $group_by_header = ttReportHelper::makeGroupByHeader($options);
640
641       $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
642       $body .= '<tr>';
643       $body .= '<td style="'.$tableHeader.'">'.$group_by_header.'</td>';
644       if ($options['show_duration'])
645         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.duration').'</td>';
646       if ($options['show_work_units'])
647         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.work_units_short').'</td>';
648       if ($options['show_cost'])
649         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.cost').'</td>';
650       $body .= '</tr>';
651       foreach($subtotals as $subtotal) {
652         $body .= '<tr style="'.$rowSubtotal.'">';
653         $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($subtotal['name'] ? htmlspecialchars($subtotal['name']) : '&nbsp;').'</td>';
654         if ($options['show_duration']) {
655           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
656           if ($subtotal['time'] <> '0:00') $body .= $subtotal['time'];
657           $body .= '</td>';
658         }
659         if ($options['show_work_units']) {
660           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
661           $body .= $subtotal['units'];
662           $body .= '</td>';
663         }
664         if ($options['show_cost']) {
665           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
666           $body .= ($canViewReports || $isClient) ? $subtotal['cost'] : $subtotal['expenses'];
667           $body .= '</td>';
668         }
669         $body .= '</tr>';
670       }
671
672       // Print totals.
673       $body .= '<tr><td>&nbsp;</td></tr>';
674       $body .= '<tr style="'.$rowSubtotal.'">';
675       $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.total').'</td>';
676       if ($options['show_duration']) {
677         $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
678         if ($totals['time'] <> '0:00') $body .= $totals['time'];
679         $body .= '</td>';
680       }
681       if ($options['show_work_units']) {
682         $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
683         $body .= $totals['units'];
684         $body .= '</td>';
685       }
686       if ($options['show_cost']) {
687         $body .= '<td nowrap style="'.$cellRightAlignedSubtotal.'">'.htmlspecialchars($user->currency).' ';
688         $body .= ($canViewReports || $isClient) ? $totals['cost'] : $totals['expenses'];
689         $body .= '</td>';
690       }
691       $body .= '</tr>';
692
693       $body .= '</table>';
694     } else {
695       // Regular report.
696
697       // Print table header.
698       $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
699       $body .= '<tr>';
700       $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.date').'</td>';
701       if ($canViewReports || $isClient)
702         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.user').'</td>';
703       if ($options['show_client'])
704         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.client').'</td>';
705       if ($options['show_project'])
706         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.project').'</td>';
707       if ($options['show_task'])
708         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.task').'</td>';
709       if ($options['show_custom_field_1'])
710         $body .= '<td style="'.$tableHeader.'">'.htmlspecialchars($custom_fields->fields[0]['label']).'</td>';
711       if ($options['show_start'])
712         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.start').'</td>';
713       if ($options['show_end'])
714         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.finish').'</td>';
715       if ($options['show_duration'])
716         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.duration').'</td>';
717       if ($options['show_work_units'])
718         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.work_units_short').'</td>';
719       if ($options['show_note'])
720         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.note').'</td>';
721       if ($options['show_cost'])
722         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.cost').'</td>';
723       if ($options['show_paid'])
724         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.paid').'</td>';
725       if ($options['show_ip'])
726         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.ip').'</td>';
727       if ($options['show_invoice'])
728         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.invoice').'</td>';
729       $body .= '</tr>';
730
731       // Initialize variables to print subtotals.
732       if ($items && $grouping) {
733         $print_subtotals = true;
734         $first_pass = true;
735         $prev_grouped_by = '';
736         $cur_grouped_by = '';
737       }
738       // Initialize variables to alternate color of rows for different dates.
739       $prev_date = '';
740       $cur_date = '';
741       $row_style = $rowItem;
742
743       // Print report items.
744       if (is_array($items)) {
745         foreach ($items as $record) {
746           $cur_date = $record['date'];
747           // Print a subtotal row after a block of grouped items.
748           if ($print_subtotals) {
749             $cur_grouped_by = $record['grouped_by'];
750             if ($cur_grouped_by != $prev_grouped_by && !$first_pass) {
751               $body .= '<tr style="'.$rowSubtotal.'">';
752               $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.subtotal').'</td>';
753               $subtotal_name = htmlspecialchars($subtotals[$prev_grouped_by]['name']);
754               if ($canViewReports || $isClient) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['user'].'</td>';
755               if ($options['show_client']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['client'].'</td>';
756               if ($options['show_project']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['project'].'</td>';
757               if ($options['show_task']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['task'].'</td>';
758               if ($options['show_custom_field_1']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['cf_1'].'</td>';
759               if ($options['show_start']) $body .= '<td></td>';
760               if ($options['show_end']) $body .= '<td></td>';
761               if ($options['show_duration']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['time'].'</td>';
762               if ($options['show_work_units']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['units'].'</td>';
763               if ($options['show_note']) $body .= '<td></td>';
764               if ($options['show_cost']) {
765                 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
766                 $body .= ($canViewReports || $isClient) ? $subtotals[$prev_grouped_by]['cost'] : $subtotals[$prev_grouped_by]['expenses'];
767                 $body .= '</td>';
768               }
769               if ($options['show_paid']) $body .= '<td></td>';
770               if ($options['show_ip']) $body .= '<td></td>';
771               if ($options['show_invoice']) $body .= '<td></td>';
772               $body .= '</tr>';
773               $body .= '<tr><td>&nbsp;</td></tr>';
774             }
775             $first_pass = false;
776           }
777
778           // Print a regular row.
779           if ($cur_date != $prev_date)
780             $row_style = ($row_style == $rowItem) ? $rowItemAlt : $rowItem;
781           $body .= '<tr style="'.$row_style.'">';
782           $body .= '<td style="'.$cellLeftAligned.'">'.$record['date'].'</td>';
783           if ($canViewReports || $isClient)
784             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['user']).'</td>';
785           if ($options['show_client'])
786             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['client']).'</td>';
787           if ($options['show_project'])
788             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['project']).'</td>';
789           if ($options['show_task'])
790             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['task']).'</td>';
791           if ($options['show_custom_field_1'])
792             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['cf_1']).'</td>';
793           if ($options['show_start'])
794             $body .= '<td nowrap style="'.$cellRightAligned.'">'.$record['start'].'</td>';
795           if ($options['show_end'])
796             $body .= '<td nowrap style="'.$cellRightAligned.'">'.$record['finish'].'</td>';
797           if ($options['show_duration'])
798             $body .= '<td style="'.$cellRightAligned.'">'.$record['duration'].'</td>';
799           if ($options['show_work_units'])
800             $body .= '<td style="'.$cellRightAligned.'">'.$record['units'].'</td>';
801           if ($options['show_note'])
802             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['note']).'</td>';
803           if ($options['show_cost'])
804             $body .= '<td style="'.$cellRightAligned.'">'.$record['cost'].'</td>';
805           if ($options['show_paid']) {
806             $body .= '<td style="'.$cellRightAligned.'">';
807             $body .= $record['paid'] == 1 ? $i18n->get('label.yes') : $i18n->get('label.no');
808             $body .= '</td>';
809           }
810           if ($options['show_ip']) {
811             $body .= '<td style="'.$cellRightAligned.'">';
812             $body .= $record['modified'] ? $record['modified_ip'].' '.$record['modified'] : $record['created_ip'].' '.$record['created'];
813             $body .= '</td>';
814           }
815           if ($options['show_invoice'])
816             $body .= '<td style="'.$cellRightAligned.'">'.htmlspecialchars($record['invoice']).'</td>';
817           $body .= '</tr>';
818
819           $prev_date = $record['date'];
820           if ($print_subtotals)
821             $prev_grouped_by = $record['grouped_by'];
822         }
823       }
824
825       // Print a terminating subtotal.
826       if ($print_subtotals) {
827         $body .= '<tr style="'.$rowSubtotal.'">';
828         $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.subtotal').'</td>';
829         $subtotal_name = htmlspecialchars($subtotals[$cur_grouped_by]['name']);
830         if ($canViewReports || $isClient) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['user'].'</td>';
831         if ($options['show_client']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['client'].'</td>';
832         if ($options['show_project']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['project'].'</td>';
833         if ($options['show_task']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['task'].'</td>';
834         if ($options['show_custom_field_1']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['cf_1'].'</td>';
835         if ($options['show_start']) $body .= '<td></td>';
836         if ($options['show_end']) $body .= '<td></td>';
837         if ($options['show_duration']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$cur_grouped_by]['time'].'</td>';
838         if ($options['show_work_units']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$cur_grouped_by]['units'].'</td>';
839         if ($options['show_note']) $body .= '<td></td>';
840         if ($options['show_cost']) {
841           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
842           $body .= ($canViewReports || $isClient) ? $subtotals[$cur_grouped_by]['cost'] : $subtotals[$cur_grouped_by]['expenses'];
843           $body .= '</td>';
844         }
845         if ($options['show_paid']) $body .= '<td></td>';
846         if ($options['show_ip']) $body .= '<td></td>';
847         if ($options['show_invoice']) $body .= '<td></td>';
848         $body .= '</tr>';
849       }
850
851       // Print totals.
852       $body .= '<tr><td>&nbsp;</td></tr>';
853       $body .= '<tr style="'.$rowSubtotal.'">';
854       $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.total').'</td>';
855       if ($canViewReports || $isClient) $body .= '<td></td>';
856       if ($options['show_client']) $body .= '<td></td>';
857       if ($options['show_project']) $body .= '<td></td>';
858       if ($options['show_task']) $body .= '<td></td>';
859       if ($options['show_custom_field_1']) $body .= '<td></td>';
860       if ($options['show_start']) $body .= '<td></td>';
861       if ($options['show_end']) $body .= '<td></td>';
862       if ($options['show_duration']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$totals['time'].'</td>';
863       if ($options['show_work_units']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$totals['units'].'</td>';
864       if ($options['show_note']) $body .= '<td></td>';
865       if ($options['show_cost']) {
866         $body .= '<td nowrap style="'.$cellRightAlignedSubtotal.'">'.htmlspecialchars($user->currency).' ';
867         $body .= ($canViewReports || $isClient) ? $totals['cost'] : $totals['expenses'];
868         $body .= '</td>';
869       }
870       if ($options['show_paid']) $body .= '<td></td>';
871       if ($options['show_ip']) $body .= '<td></td>';
872       if ($options['show_invoice']) $body .= '<td></td>';
873       $body .= '</tr>';
874
875       $body .= '</table>';
876     }
877
878     // Output footer.
879     if (!defined('REPORT_FOOTER') || !(REPORT_FOOTER == false))
880       $body .= '<p style="text-align: center;">'.$i18n->get('form.mail.footer').'</p>';
881
882     // Finish creating email body.
883     $body .= '</body></html>';
884
885     return $body;
886   }
887
888   // checkFavReportCondition - checks whether it is okay to send fav report.
889   static function checkFavReportCondition($options, $condition)
890   {
891     $items = ttReportHelper::getItems($options);
892
893     $condition = trim(str_replace('count', '', $condition));
894
895     $greater_or_equal = ttStartsWith($condition, '>=');
896     if ($greater_or_equal) $condition = trim(str_replace('>=', '', $condition));
897
898     $less_or_equal = ttStartsWith($condition, '<=');
899     if ($less_or_equal) $condition = trim(str_replace('<=', '', $condition));
900
901     $not_equal = ttStartsWith($condition, '<>');
902     if ($not_equal) $condition = trim(str_replace('<>', '', $condition));
903
904     $greater = ttStartsWith($condition, '>');
905     if ($greater) $condition = trim(str_replace('>', '', $condition));
906
907     $less = ttStartsWith($condition, '<');
908     if ($less) $condition = trim(str_replace('<', '', $condition));
909
910     $equal = ttStartsWith($condition, '=');
911     if ($equal) $condition = trim(str_replace('=', '', $condition));
912
913     $count_required = (int) $condition;
914
915     if ($greater && count($items) > $count_required) return true;
916     if ($greater_or_equal && count($items) >= $count_required) return true;
917     if ($less && count($items) < $count_required) return true;
918     if ($less_or_equal && count($items) <= $count_required) return true;
919     if ($equal && count($items) == $count_required) return true;
920     if ($not_equal && count($items) <> $count_required) return true;
921
922     return false;
923   }
924
925   // sendFavReport - sends a favorite report to a specified email, called from cron.php
926   static function sendFavReport($options, $subject, $email, $cc) {
927     // We are called from cron.php, we have no $bean in session.
928     // cron.php sets global $user and $i18n objects to match our favorite report user.
929     global $user;
930     global $i18n;
931
932     // Prepare report body.
933     $body = ttReportHelper::prepareReportBody($options);
934
935     import('mail.Mailer');
936     $mailer = new Mailer();
937     $mailer->setCharSet(CHARSET);
938     $mailer->setContentType('text/html');
939     $mailer->setSender(SENDER);
940     if (!empty($cc))
941       $mailer->setReceiverCC($cc);
942     if (!empty($user->bcc_email))
943       $mailer->setReceiverBCC($user->bcc_email);
944     $mailer->setReceiver($email);
945     $mailer->setMailMode(MAIL_MODE);
946     if (empty($subject)) $subject = $options['name'];
947     if (!$mailer->send($subject, $body))
948       return false;
949
950     return true;
951   }
952
953   // getReportOptions - returns an array of report options constructed from session bean.
954   //
955   // Note: similarly to ttFavReportHelper::getReportOptions, this function is a part of
956   // refactoring to simplify maintenance of report generating functions, as we currently
957   // have 2 sets: normal reporting (from bean), and fav report emailing (from db fields).
958   // Using options obtained from either db or bean shall allow us to use only one set of functions.
959   static function getReportOptions($bean) {
960     global $user;
961
962     // Prepare an array of report options.
963     $options = array();
964
965     // Construct one by one.
966     $options['name'] = null; // No name required.
967     $options['user_id'] = $user->id; // Not sure if we need user_id here. Fav reports use it to recycle $user object in cron.php.
968     $options['client_id'] = $bean->getAttribute('client');
969     $options['cf_1_option_id'] = $bean->getAttribute('option');
970     $options['project_id'] = $bean->getAttribute('project');
971     $options['task_id'] = $bean->getAttribute('task');
972     $options['billable'] = $bean->getAttribute('include_records');
973     $options['invoice'] = $bean->getAttribute('invoice');
974     $options['paid_status'] = $bean->getAttribute('paid_status');
975     if (is_array($bean->getAttribute('users'))) $options['users'] = join(',', $bean->getAttribute('users'));
976     $options['period'] = $bean->getAttribute('period');
977     $options['period_start'] = $bean->getAttribute('start_date');
978     $options['period_end'] = $bean->getAttribute('end_date');
979     $options['show_client'] = $bean->getAttribute('chclient');
980     $options['show_invoice'] = $bean->getAttribute('chinvoice');
981     $options['show_paid'] = $bean->getAttribute('chpaid');
982     $options['show_ip'] = $bean->getAttribute('chip');
983     $options['show_project'] = $bean->getAttribute('chproject');
984     $options['show_start'] = $bean->getAttribute('chstart');
985     $options['show_duration'] = $bean->getAttribute('chduration');
986     $options['show_cost'] = $bean->getAttribute('chcost');
987     $options['show_task'] = $bean->getAttribute('chtask');
988     $options['show_end'] = $bean->getAttribute('chfinish');
989     $options['show_note'] = $bean->getAttribute('chnote');
990     $options['show_custom_field_1'] = $bean->getAttribute('chcf_1');
991     $options['show_work_units'] = $bean->getAttribute('chunits');
992     $options['show_totals_only'] = $bean->getAttribute('chtotalsonly');
993     $options['group_by1'] = $bean->getAttribute('group_by1');
994     $options['group_by2'] = $bean->getAttribute('group_by2');
995     $options['group_by3'] = $bean->getAttribute('group_by3');
996     return $options;
997   }
998
999   // verifyBean is a security function to make sure data in bean makes sense for a group.
1000   static function verifyBean($bean) {
1001     global $user;
1002
1003     // Check users.
1004     $users_in_bean = $bean->getAttribute('users');
1005     if (is_array($users_in_bean)) {
1006       $users_in_group = ttGroupHelper::getUsers();
1007       foreach ($users_in_group as $user_in_group) {
1008         $valid_ids[] = $user_in_group['id'];
1009       }
1010       foreach ($users_in_bean as $user_in_bean) {
1011         if (!in_array($user_in_bean, $valid_ids)) {
1012           return false;
1013         }
1014       }
1015     }
1016
1017     // TODO: add additional checks here. Perhaps do it before saving the bean for consistency.
1018     return true;
1019   }
1020
1021   // makeGroupByKey builds a combined group by key from group_by1, group_by2 and group_by3 values
1022   // (passed in $options) and a row of data ($row obtained from a db query).
1023   static function makeGroupByKey($options, $row) {
1024     if ($options['group_by1'] != null && $options['group_by1'] != 'no_grouping') {
1025       // We have group_by1.
1026       $group_by1 = $options['group_by1'];
1027       $group_by1_value = $row[$group_by1];
1028       //if ($group_by1 == 'date') $group_by1_value = ttDateToUserFormat($group_by1_value);
1029       if (empty($group_by1_value)) $group_by1_value = 'Null'; // To match what comes out of makeConcatPart.
1030       $group_by_key .= ' - '.$group_by1_value;
1031     }
1032     if ($options['group_by2'] != null && $options['group_by2'] != 'no_grouping') {
1033       // We have group_by2.
1034       $group_by2 = $options['group_by2'];
1035       $group_by2_value = $row[$group_by2];
1036       //if ($group_by2 == 'date') $group_by2_value = ttDateToUserFormat($group_by2_value);
1037       if (empty($group_by2_value)) $group_by2_value = 'Null'; // To match what comes out of makeConcatPart.
1038       $group_by_key .= ' - '.$group_by2_value;
1039     }
1040     if ($options['group_by3'] != null && $options['group_by3'] != 'no_grouping') {
1041       // We have group_by3.
1042       $group_by3 = $options['group_by3'];
1043       $group_by3_value = $row[$group_by3];
1044       //if ($group_by3 == 'date') $group_by3_value = ttDateToUserFormat($group_by3_value);
1045       if (empty($group_by3_value)) $group_by3_value = 'Null'; // To match what comes out of makeConcatPart.
1046       $group_by_key .= ' - '.$group_by3_value;
1047     }
1048     $group_by_key = trim($group_by_key, ' -');
1049     return $group_by_key;
1050   }
1051
1052   // makeGroupByPart builds a combined group by part for sql query for time items using group_by1,
1053   // group_by2, and group_by3 values passed in $options.
1054   static function makeGroupByPart($options) {
1055     if (!ttReportHelper::grouping($options)) return null;
1056
1057     $group_by1 = $options['group_by1'];
1058     $group_by2 = $options['group_by2'];
1059     $group_by3 = $options['group_by3'];
1060
1061     switch ($group_by1) {
1062       case 'date':
1063         $group_by_parts .= ', l.date';
1064         break;
1065       case 'user':
1066         $group_by_parts .= ', u.name';
1067         break;
1068       case 'client':
1069         $group_by_parts .= ', c.name';
1070         break;
1071       case 'project':
1072         $group_by_parts .= ', p.name';
1073         break;
1074       case 'task':
1075         $group_by_parts .= ', t.name';
1076         break;
1077       case 'cf_1':
1078         $group_by_parts .= ', cfo.value';
1079         break;
1080     }
1081     switch ($group_by2) {
1082       case 'date':
1083         $group_by_parts .= ', l.date';
1084         break;
1085       case 'user':
1086         $group_by_parts .= ', u.name';
1087         break;
1088       case 'client':
1089         $group_by_parts .= ', c.name';
1090         break;
1091       case 'project':
1092         $group_by_parts .= ', p.name';
1093         break;
1094       case 'task':
1095         $group_by_parts .= ', t.name';
1096         break;
1097       case 'cf_1':
1098         $group_by_parts .= ', cfo.value';
1099         break;
1100     }
1101     switch ($group_by3) {
1102       case 'date':
1103         $group_by_parts .= ', l.date';
1104         break;
1105       case 'user':
1106         $group_by_parts .= ', u.name';
1107         break;
1108       case 'client':
1109         $group_by_parts .= ', c.name';
1110         break;
1111       case 'project':
1112         $group_by_parts .= ', p.name';
1113         break;
1114       case 'task':
1115         $group_by_parts .= ', t.name';
1116         break;
1117       case 'cf_1':
1118         $group_by_parts .= ', cfo.value';
1119         break;
1120     }
1121     // Remove garbage from the beginning.
1122     $group_by_parts = ltrim($group_by_parts, ', ');
1123     $group_by_part = "group by $group_by_parts";
1124     return $group_by_part;
1125   }
1126
1127   // makeGroupByExpensesPart builds a combined group by part for sql query for expense items using
1128   // group_by1, group_by2, and group_by3 values passed in $options.
1129   static function makeGroupByExpensesPart($options) {
1130     $no_grouping = ($options['group_by1'] == null || $options['group_by1'] == 'no_grouping') &&
1131       ($options['group_by2'] == null || $options['group_by2'] == 'no_grouping') &&
1132       ($options['group_by3'] == null || $options['group_by3'] == 'no_grouping');
1133     if ($no_grouping) return null;
1134
1135     $group_by1 = $options['group_by1'];
1136     $group_by2 = $options['group_by2'];
1137     $group_by3 = $options['group_by3'];
1138
1139     switch ($group_by1) {
1140       case 'date':
1141         $group_by_parts .= ', ei.date';
1142         break;
1143       case 'user':
1144         $group_by_parts .= ', u.name';
1145         break;
1146       case 'client':
1147         $group_by_parts .= ', c.name';
1148         break;
1149       case 'project':
1150         $group_by_parts .= ', p.name';
1151         break;
1152     }
1153     switch ($group_by2) {
1154       case 'date':
1155         $group_by_parts .= ', ei.date';
1156         break;
1157       case 'user':
1158         $group_by_parts .= ', u.name';
1159         break;
1160       case 'client':
1161         $group_by_parts .= ', c.name';
1162         break;
1163       case 'project':
1164         $group_by_parts .= ', p.name';
1165         break;
1166     }
1167     switch ($group_by3) {
1168       case 'date':
1169         $group_by_parts .= ', ei.date';
1170         break;
1171       case 'user':
1172         $group_by_parts .= ', u.name';
1173         break;
1174       case 'client':
1175         $group_by_parts .= ', c.name';
1176         break;
1177       case 'project':
1178         $group_by_parts .= ', p.name';
1179         break;
1180     }
1181     // Remove garbage from the beginning.
1182     $group_by_parts = ltrim($group_by_parts, ', ');
1183     if ($group_by_parts)
1184       $group_by_part = "group by $group_by_parts";
1185     return $group_by_part;
1186   }
1187
1188   // makeConcatPart builds a concatenation part for getSubtotals query (for time items).
1189   static function makeConcatPart($options) {
1190     $group_by1 = $options['group_by1'];
1191     $group_by2 = $options['group_by2'];
1192     $group_by3 = $options['group_by3'];
1193
1194     switch ($group_by1) {
1195       case 'date':
1196         $what_to_concat .= ", ' - ', l.date";
1197         break;
1198       case 'user':
1199         $what_to_concat .= ", ' - ', u.name";
1200         $fields_part .= ', u.name as user';
1201         break;
1202       case 'client':
1203         $what_to_concat .= ", ' - ', coalesce(c.name, 'Null')";
1204         $fields_part .= ', c.name as client';
1205         break;
1206       case 'project':
1207         $what_to_concat .= ", ' - ', coalesce(p.name, 'Null')";
1208         $fields_part .= ', p.name as project';
1209         break;
1210       case 'task':
1211         $what_to_concat .= ", ' - ', coalesce(t.name, 'Null')";
1212         $fields_part .= ', t.name as task';
1213         break;
1214       case 'cf_1':
1215         $what_to_concat .= ", ' - ', coalesce(cfo.value, 'Null')";
1216         $fields_part .= ', cfo.value as cf_1';
1217         break;
1218     }
1219     switch ($group_by2) {
1220       case 'date':
1221         $what_to_concat .= ", ' - ', l.date";
1222         break;
1223       case 'user':
1224         $what_to_concat .= ", ' - ', u.name";
1225         $fields_part .= ', u.name as user';
1226         break;
1227       case 'client':
1228         $what_to_concat .= ", ' - ', coalesce(c.name, 'Null')";
1229         $fields_part .= ', c.name as client';
1230         break;
1231       case 'project':
1232         $what_to_concat .= ", ' - ', coalesce(p.name, 'Null')";
1233         $fields_part .= ', p.name as project';
1234         break;
1235       case 'task':
1236         $what_to_concat .= ", ' - ', coalesce(t.name, 'Null')";
1237         $fields_part .= ', t.name as task';
1238         break;
1239       case 'cf_1':
1240         $what_to_concat .= ", ' - ', coalesce(cfo.value, 'Null')";
1241         $fields_part .= ', cfo.value as cf_1';
1242         break;
1243     }
1244     switch ($group_by3) {
1245       case 'date':
1246         $what_to_concat .= ", ' - ', l.date";
1247         break;
1248       case 'user':
1249         $what_to_concat .= ", ' - ', u.name";
1250         $fields_part .= ', u.name as user';
1251         break;
1252       case 'client':
1253         $what_to_concat .= ", ' - ', coalesce(c.name, 'Null')";
1254         $fields_part .= ', c.name as client';
1255         break;
1256       case 'project':
1257         $what_to_concat .= ", ' - ', coalesce(p.name, 'Null')";
1258         $fields_part .= ', p.name as project';
1259         break;
1260       case 'task':
1261         $what_to_concat .= ", ' - ', coalesce(t.name, 'Null')";
1262         $fields_part .= ', t.name as task';
1263         break;
1264       case 'cf_1':
1265         $what_to_concat .= ", ' - ', coalesce(cfo.value, 'Null')";
1266         $fields_part .= ', cfo.value as cf_1';
1267         break;
1268     }
1269     // Remove garbage from both ends.
1270     $what_to_concat = trim($what_to_concat, "', -");
1271     $concat_part = "concat($what_to_concat) as group_field";
1272     $concat_part = trim($concat_part, ' -');
1273     return "$concat_part $fields_part";
1274   }
1275
1276   // makeConcatPart builds a concatenation part for getSubtotals query (for expense items).
1277   static function makeConcatExpensesPart($options) {
1278     $group_by1 = $options['group_by1'];
1279     $group_by2 = $options['group_by2'];
1280     $group_by3 = $options['group_by3'];
1281
1282     switch ($group_by1) {
1283       case 'date':
1284         $what_to_concat .= ", ' - ', ei.date";
1285         break;
1286       case 'user':
1287         $what_to_concat .= ", ' - ', u.name";
1288         $fields_part .= ', u.name as user';
1289         break;
1290       case 'client':
1291         $what_to_concat .= ", ' - ', coalesce(c.name, 'Null')";
1292         $fields_part .= ', c.name as client';
1293         break;
1294       case 'project':
1295         $what_to_concat .= ", ' - ', coalesce(p.name, 'Null')";
1296         $fields_part .= ', p.name as project';
1297         break;
1298
1299       case 'task':
1300         $what_to_concat .= ", ' - ', 'Null'";
1301         $fields_part .= ', null as task';
1302         break;
1303
1304       case 'cf_1':
1305         $what_to_concat .= ", ' - ', 'Null'";
1306         $fields_part .= ', null as cf_1';
1307         break;
1308     }
1309     switch ($group_by2) {
1310       case 'date':
1311         $what_to_concat .= ", ' - ', ei.date";
1312         break;
1313       case 'user':
1314         $what_to_concat .= ", ' - ', u.name";
1315         $fields_part .= ', u.name as user';
1316         break;
1317       case 'client':
1318         $what_to_concat .= ", ' - ', coalesce(c.name, 'Null')";
1319         $fields_part .= ', c.name as client';
1320         break;
1321       case 'project':
1322         $what_to_concat .= ", ' - ', coalesce(p.name, 'Null')";
1323         $fields_part .= ', p.name as project';
1324         break;
1325
1326       case 'task':
1327         $what_to_concat .= ", ' - ', 'Null'";
1328         $fields_part .= ', null as task';
1329         break;
1330
1331       case 'cf_1':
1332         $what_to_concat .= ", ' - ', 'Null'";
1333         $fields_part .= ', null as cf_1';
1334         break;
1335     }
1336     switch ($group_by3) {
1337       case 'date':
1338         $what_to_concat .= ", ' - ', ei.date";
1339         break;
1340       case 'user':
1341         $what_to_concat .= ", ' - ', u.name";
1342         $fields_part .= ', u.name as user';
1343         break;
1344       case 'client':
1345         $what_to_concat .= ", ' - ', coalesce(c.name, 'Null')";
1346         $fields_part .= ', c.name as client';
1347         break;
1348       case 'project':
1349         $what_to_concat .= ", ' - ', coalesce(p.name, 'Null')";
1350         $fields_part .= ', p.name as project';
1351         break;
1352
1353       case 'task':
1354         $what_to_concat .= ", ' - ', 'Null'";
1355         $fields_part .= ', null as task';
1356         break;
1357
1358       case 'cf_1':
1359         $what_to_concat .= ", ' - ', 'Null'";
1360         $fields_part .= ', null as cf_1';
1361         break;
1362     }
1363     // Remove garbage from the beginning.
1364     if ($what_to_concat)
1365         $what_to_concat = substr($what_to_concat, 8);
1366     $concat_part = "concat($what_to_concat) as group_field";
1367     return "$concat_part $fields_part";
1368   }
1369
1370   // makeCombinedSelectPart builds a list of fields for a combined select on a union for getSubtotals.
1371   // This is used when we include expenses.
1372   static function makeCombinedSelectPart($options) {
1373     $group_by1 = $options['group_by1'];
1374     $group_by2 = $options['group_by2'];
1375     $group_by3 = $options['group_by3'];
1376
1377     $fields = "group_field";
1378
1379     switch ($group_by1) {
1380       case 'user':
1381         $fields .= ', user';
1382         break;
1383       case 'client':
1384         $fields_part .= ', client';
1385         break;
1386       case 'project':
1387         $fields .= ', project';
1388         break;
1389
1390       case 'task':
1391         $fields .= ', task';
1392         break;
1393
1394       case 'cf_1':
1395         $fields .= ', cf_1';
1396         break;
1397     }
1398     switch ($group_by2) {
1399       case 'user':
1400         $fields .= ', user';
1401         break;
1402       case 'client':
1403         $fields_part .= ', client';
1404         break;
1405       case 'project':
1406         $fields .= ', project';
1407         break;
1408
1409       case 'task':
1410         $fields .= ', task';
1411         break;
1412
1413       case 'cf_1':
1414         $fields .= ', cf_1';
1415         break;
1416     }
1417     switch ($group_by3) {
1418       case 'user':
1419         $fields .= ', user';
1420         break;
1421       case 'client':
1422         $fields_part .= ', client';
1423         break;
1424       case 'project':
1425         $fields .= ', project';
1426         break;
1427
1428       case 'task':
1429         $fields .= ', task';
1430         break;
1431
1432       case 'cf_1':
1433         $fields .= ', cf_1';
1434         break;
1435     }
1436     return $fields;
1437   }
1438
1439   // makeJoinPart builds a left join part for getSubtotals query (for time items).
1440   static function makeJoinPart($options) {
1441     global $user;
1442
1443     $trackingMode = $user->getTrackingMode();
1444     if (ttReportHelper::groupingBy('user', $options) || MODE_TIME == $trackingMode) {
1445       $join .= ' left join tt_users u on (l.user_id = u.id)';
1446     }
1447     if (ttReportHelper::groupingBy('client', $options)) {
1448       $join .= ' left join tt_clients c on (l.client_id = c.id)';
1449     }
1450     if (ttReportHelper::groupingBy('project', $options)) {
1451       $join .= ' left join tt_projects p on (l.project_id = p.id)';
1452     }
1453     if (ttReportHelper::groupingBy('task', $options)) {
1454       $join .= ' left join tt_tasks t on (l.task_id = t.id)';
1455     }
1456     if (ttReportHelper::groupingBy('cf_1', $options)) {
1457       $custom_fields = new CustomFields();
1458       if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_TEXT)
1459         $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)';
1460       elseif ($custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN)
1461         $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)';
1462     }
1463     if ($options['show_cost'] && $trackingMode != MODE_TIME) {
1464       $join .= ' left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id)';
1465     }
1466     return $join;
1467   }
1468
1469   // makeWorkUnitPart builds an sql part for work units for time items.
1470   static function makeWorkUnitPart($options) {
1471     global $user;
1472
1473     $workUnits = $options['show_work_units'];
1474     if ($workUnits) {
1475       $unitTotalsOnly = $user->getConfigOption('unit_totals_only');
1476       $firstUnitThreshold = $user->getConfigInt('1st_unit_threshold', 0);
1477       $minutesInUnit = $user->getConfigInt('minutes_in_unit', 15);
1478       if ($unitTotalsOnly)
1479         $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";
1480       else
1481         $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";
1482     }
1483     return $work_unit_part;
1484   }
1485
1486   // makeCostPart builds a cost part for time items.
1487   static function makeCostPart($options) {
1488     global $user;
1489
1490     if ($options['show_cost']) {
1491       if (MODE_TIME == $user->getTrackingMode())
1492         $cost_part = ", sum(cast(l.billable * coalesce(u.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10, 2))) as cost";
1493       else
1494         $cost_part .= ", sum(cast(l.billable * coalesce(upb.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10,2))) as cost";
1495     }
1496     return $cost_part;
1497   }
1498
1499   // makeJoinExpensesPart builds a left join part for getSubtotals query for expense items.
1500   static function makeJoinExpensesPart($options) {
1501     if (ttReportHelper::groupingBy('user', $options)) {
1502       $join .= ' left join tt_users u on (ei.user_id = u.id)';
1503     }
1504     if (ttReportHelper::groupingBy('client', $options)) {
1505       $join .= ' left join tt_clients c on (ei.client_id = c.id)';
1506     }
1507     if (ttReportHelper::groupingBy('project', $options)) {
1508       $join .= ' left join tt_projects p on (ei.project_id = p.id)';
1509     }
1510     return $join;
1511   }
1512
1513   // grouping determines if we are grouping the report by either group_by1,
1514   // group_by2, or group_by3 values passed in $options.
1515   static function grouping($options) {
1516     $grouping = ($options['group_by1'] != null && $options['group_by1'] != 'no_grouping') ||
1517       ($options['group_by2'] != null && $options['group_by2'] != 'no_grouping') ||
1518       ($options['group_by3'] != null && $options['group_by3'] != 'no_grouping');
1519     return $grouping;
1520   }
1521
1522   // groupingBy determines if we are grouping a report by a value of $what
1523   // ('date', 'user', 'project', etc.) by checking group_by1, group_by2,
1524   // and group_by3 values passed in $options.
1525   static function groupingBy($what, $options) {
1526     $grouping = ($options['group_by1'] == $what) || ($options['group_by2'] == $what) || ($options['group_by3'] == $what);
1527     return $grouping;
1528   }
1529
1530   // makeGroupByHeader builds a column header for a totals-only report using group_by1,
1531   // group_by2, and group_by3 values passed in $options.
1532   static function makeGroupByHeader($options) {
1533     global $i18n;
1534     global $custom_fields;
1535
1536     $no_grouping = ($options['group_by1'] == null || $options['group_by1'] == 'no_grouping') &&
1537       ($options['group_by2'] == null || $options['group_by2'] == 'no_grouping') &&
1538       ($options['group_by3'] == null || $options['group_by3'] == 'no_grouping');
1539     if ($no_grouping) return null;
1540
1541     if ($options['group_by1'] != null && $options['group_by1'] != 'no_grouping') {
1542       // We have group_by1.
1543       $group_by1 = $options['group_by1'];
1544       if ('cf_1' == $group_by1)
1545         $group_by_header .= ' - '.$custom_fields->fields[0]['label'];
1546       else {
1547         $key = 'label.'.$group_by1;
1548         $group_by_header .= ' - '.$i18n->get($key);
1549       }
1550     }
1551     if ($options['group_by2'] != null && $options['group_by2'] != 'no_grouping') {
1552       // We have group_by2.
1553       $group_by2 = $options['group_by2'];
1554       if ('cf_1' == $group_by2)
1555         $group_by_header .= ' - '.$custom_fields->fields[0]['label'];
1556       else {
1557         $key = 'label.'.$group_by2;
1558         $group_by_header .= ' - '.$i18n->get($key);
1559       }
1560     }
1561     if ($options['group_by3'] != null && $options['group_by3'] != 'no_grouping') {
1562       // We have group_by3.
1563       $group_by3 = $options['group_by3'];
1564       if ('cf_1' == $group_by3)
1565         $group_by_header .= ' - '.$custom_fields->fields[0]['label'];
1566       else {
1567         $key = 'label.'.$group_by3;
1568         $group_by_header .= ' - '.$i18n->get($key);
1569       }
1570     }
1571     $group_by_header = ltrim($group_by_header, ' -');
1572     return $group_by_header;
1573   }
1574
1575   // makeGroupByXmlTag creates an xml tag for a totals only report using group_by1,
1576   // group_by2, and group_by3 values passed in $options.
1577   static function makeGroupByXmlTag($options) {
1578     if ($options['group_by1'] != null && $options['group_by1'] != 'no_grouping') {
1579       // We have group_by1.
1580       $tag .= '_'.$options['group_by1'];
1581     }
1582     if ($options['group_by2'] != null && $options['group_by2'] != 'no_grouping') {
1583       // We have group_by2.
1584       $tag .= '_'.$options['group_by2'];
1585     }
1586     if ($options['group_by3'] != null && $options['group_by3'] != 'no_grouping') {
1587       // We have group_by3.
1588       $tag .= '_'.$options['group_by3'];
1589     }
1590     $tag = ltrim($tag, '_');
1591     return $tag;
1592   }
1593
1594   // makeGroupByLabel builds a label for one row in a "Totals only" report of grouped by items.
1595   // It does one thing: if we are grouping by date, the date format is converted for user.
1596   static function makeGroupByLabel($key, $options) {
1597     if (!ttReportHelper::groupingBy('date', $options))
1598       return $key; // No need to format.
1599
1600     global $user;
1601     if ($user->getDateFormat() == DB_DATEFORMAT)
1602       return $key; // No need to format.
1603
1604     $label = $key;
1605     if (preg_match('/\d\d\d\d-\d\d-\d\d/', $key, $matches)) {
1606       // Replace the first found match of a date in DB_DATEFORMAT.
1607       // This is not entirely clean but better than nothing for a label in a row.
1608       $userDate = ttDateToUserFormat($matches[0]);
1609       $label = str_replace($matches[0], $userDate, $key);
1610     }
1611     return $label;
1612   }
1613 }