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