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