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