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