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