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