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