More refactoring in reports.
[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($bean, $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');
128     $isClient = $user->isClient();
129
130     $group_by_option = $options['group_by'];
131     $convertTo12Hour = ('%I:%M %p' == $user->time_format) && ($options['show_start'] || $options['show_end']);
132
133     // Prepare a query for time items in tt_log table.
134     $fields = array(); // An array of fields for database query.
135     array_push($fields, 'l.id as id');
136     array_push($fields, '1 as type'); // Type 1 is for tt_log entries.
137     array_push($fields, 'l.date as date');
138     if($canViewReports || $isClient)
139       array_push($fields, 'u.name as user');
140     // Add client name if it is selected.
141     if ($options['show_client'] || 'client' == $group_by_option)
142       array_push($fields, 'c.name as client');
143     // Add project name if it is selected.
144     if ($options['show_project'] || 'project' == $group_by_option)
145       array_push($fields, 'p.name as project');
146     // Add task name if it is selected.
147     if ($options['show_task'] || 'task' == $group_by_option)
148       array_push($fields, 't.name as task');
149     // Add custom field.
150     $include_cf_1 = $options['show_custom_field_1'] || 'cf_1' == $group_by_option;
151     if ($include_cf_1) {
152       $custom_fields = new CustomFields($user->group_id);
153       $cf_1_type = $custom_fields->fields[0]['type'];
154       if ($cf_1_type == CustomFields::TYPE_TEXT) {
155         array_push($fields, 'cfl.value as cf_1');
156       } elseif ($cf_1_type == CustomFields::TYPE_DROPDOWN) {
157         array_push($fields, 'cfo.value as cf_1');
158       }
159     }
160
161 // TODO: refactoring in progress down from here... The above is identical to getFavItems and is ready to merge.
162     // Add start time.
163     if ($bean->getAttribute('chstart')) {
164       array_push($fields, "l.start as unformatted_start");
165       array_push($fields, "TIME_FORMAT(l.start, '%k:%i') as start");
166     }
167     // Add finish time.
168     if ($bean->getAttribute('chfinish'))
169       array_push($fields, "TIME_FORMAT(sec_to_time(time_to_sec(l.start) + time_to_sec(l.duration)), '%k:%i') as finish");
170     // Add duration.
171     if ($bean->getAttribute('chduration'))
172       array_push($fields, "TIME_FORMAT(l.duration, '%k:%i') as duration");
173     // Add work units.
174     if ($bean->getAttribute('chunits')) {
175       if ($user->unit_totals_only)
176         array_push($fields, "null as units");
177       else
178        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");
179     }
180     // Add note.
181     if ($bean->getAttribute('chnote'))
182       array_push($fields, 'l.comment as note');
183     // Handle cost.
184     $includeCost = $bean->getAttribute('chcost');
185     if ($includeCost) {
186       if (MODE_TIME == $user->tracking_mode)
187         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.
188       else
189         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.
190       array_push($fields, "null as expense"); 
191     }
192     // Add paid status.
193     if ($canViewReports && $bean->getAttribute('chpaid'))
194       array_push($fields, 'l.paid as paid');
195     // Add IP address.
196     if ($canViewReports && $bean->getAttribute('chip')) {
197       array_push($fields, 'l.created as created');
198       array_push($fields, 'l.created_ip as created_ip');
199       array_push($fields, 'l.modified as modified');
200       array_push($fields, 'l.modified_ip as modified_ip');
201     }
202
203     // Add invoice name if it is selected.
204     if (($canViewReports || $isClient) && $bean->getAttribute('chinvoice'))
205       array_push($fields, 'i.name as invoice');
206
207     // Prepare sql query part for left joins.
208     $left_joins = null;
209     if ($bean->getAttribute('chclient') || 'client' == $group_by_option)
210       $left_joins .= " left join tt_clients c on (c.id = l.client_id)";
211     if (($canViewReports || $isClient) && $bean->getAttribute('chinvoice'))
212       $left_joins .= " left join tt_invoices i on (i.id = l.invoice_id and i.status = 1)";
213     if ($canViewReports || $isClient || $user->isPluginEnabled('ex'))
214        $left_joins .= " left join tt_users u on (u.id = l.user_id)";
215     if ($bean->getAttribute('chproject') || 'project' == $group_by_option)
216       $left_joins .= " left join tt_projects p on (p.id = l.project_id)";
217     if ($bean->getAttribute('chtask') || 'task' == $group_by_option)
218       $left_joins .= " left join tt_tasks t on (t.id = l.task_id)";
219     if ($include_cf_1) {
220       if ($cf_1_type == CustomFields::TYPE_TEXT)
221         $left_joins .= " left join tt_custom_field_log cfl on (l.id = cfl.log_id and cfl.status = 1)";
222       elseif ($cf_1_type == CustomFields::TYPE_DROPDOWN) {
223         $left_joins .=  " left join tt_custom_field_log cfl on (l.id = cfl.log_id and cfl.status = 1)".
224           " left join tt_custom_field_options cfo on (cfl.option_id = cfo.id)";
225       }
226     }
227     if ($includeCost && MODE_TIME != $user->tracking_mode)
228       $left_joins .= " left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id)";
229
230     $where = ttReportHelper::getWhere($options);
231
232     // Construct sql query for tt_log items.
233     $sql = "select ".join(', ', $fields)." from tt_log l $left_joins $where";
234     // If we don't have expense items (such as when the Expenses plugin is desabled), the above is all sql we need,
235     // with an exception of sorting part, that is added in the end.
236
237     // However, when we have expenses, we need to do a union with a separate query for expense items from tt_expense_items table.
238     if ($bean->getAttribute('chcost') && $user->isPluginEnabled('ex')) { // if ex(penses) plugin is enabled
239
240       $fields = array(); // An array of fields for database query.
241       array_push($fields, 'ei.id');
242       array_push($fields, '2 as type'); // Type 2 is for tt_expense_items entries.
243       array_push($fields, 'ei.date');
244       if($canViewReports || $isClient)
245         array_push($fields, 'u.name as user');
246       // Add client name if it is selected.
247       if ($bean->getAttribute('chclient') || 'client' == $group_by_option)
248         array_push($fields, 'c.name as client');
249       // Add project name if it is selected.
250       if ($bean->getAttribute('chproject') || 'project' == $group_by_option)
251         array_push($fields, 'p.name as project');
252       if ($bean->getAttribute('chtask') || 'task' == $group_by_option)
253         array_push($fields, 'null'); // null for task name. We need to match column count for union.
254       if ($bean->getAttribute('chcf_1') || 'cf_1' == $group_by_option)
255         array_push($fields, 'null'); // null for cf_1.
256       if ($bean->getAttribute('chstart')) {
257         array_push($fields, 'null'); // null for unformatted_start.
258         array_push($fields, 'null'); // null for start.
259       }
260       if ($bean->getAttribute('chfinish'))
261         array_push($fields, 'null'); // null for finish.
262       if ($bean->getAttribute('chduration'))
263         array_push($fields, 'null'); // null for duration.
264       // Add work units.
265       if ($bean->getAttribute('chunits'))
266         array_push($fields, 'null as units'); // null for work units.
267       // Use the note field to print item name.
268       if ($bean->getAttribute('chnote'))
269         array_push($fields, 'ei.name as note');
270       array_push($fields, 'ei.cost as cost');
271       array_push($fields, 'ei.cost as expense');
272       // Add paid status.
273       if ($canViewReports && $bean->getAttribute('chpaid'))
274         array_push($fields, 'ei.paid as paid');
275       // Add IP address.
276       if ($canViewReports && $bean->getAttribute('chip')) {
277         array_push($fields, 'ei.created as created');
278         array_push($fields, 'ei.created_ip as created_ip');
279         array_push($fields, 'ei.modified as modified');
280         array_push($fields, 'ei.modified_ip as modified_ip');
281       }
282
283       // Add invoice name if it is selected.
284       if (($canViewReports || $isClient) && $bean->getAttribute('chinvoice'))
285         array_push($fields, 'i.name as invoice');
286
287       // Prepare sql query part for left joins.
288       $left_joins = null;
289       if ($canViewReports || $isClient)
290         $left_joins .= " left join tt_users u on (u.id = ei.user_id)";
291       if ($bean->getAttribute('chclient') || 'client' == $group_by_option)
292         $left_joins .= " left join tt_clients c on (c.id = ei.client_id)";
293       if ($bean->getAttribute('chproject') || 'project' == $group_by_option)
294         $left_joins .= " left join tt_projects p on (p.id = ei.project_id)";
295       if (($canViewReports || $isClient) && $bean->getAttribute('chinvoice'))
296         $left_joins .= " left join tt_invoices i on (i.id = ei.invoice_id and i.status = 1)";
297
298       $where = ttReportHelper::getExpenseWhere($options);
299
300       // Construct sql query for expense items.
301       $sql_for_expense_items = "select ".join(', ', $fields)." from tt_expense_items ei $left_joins $where";
302
303       // Construct a union.
304       $sql = "($sql) union all ($sql_for_expense_items)";
305     }
306
307     // Determine sort part.
308     $sort_part = ' order by ';
309     if ('no_grouping' == $group_by_option || 'date' == $group_by_option)
310       $sort_part .= 'date';
311     else
312       $sort_part .= $group_by_option.', date';
313     if (($canViewReports || $isClient) && is_array($bean->getAttribute('users')) && 'user' != $group_by_option)
314       $sort_part .= ', user, type';
315     if ($bean->getAttribute('chstart'))
316       $sort_part .= ', unformatted_start';
317     $sort_part .= ', id';
318
319     $sql .= $sort_part;
320     // By now we are ready with sql.
321
322     // Obtain items for report.
323     $res = $mdb2->query($sql);
324     if (is_a($res, 'PEAR_Error')) die($res->getMessage());
325
326     while ($val = $res->fetchRow()) {
327       if ($convertTo12Hour) {
328         if($val['start'] != '')
329           $val['start'] = ttTimeHelper::to12HourFormat($val['start']);
330         if($val['finish'] != '')
331           $val['finish'] = ttTimeHelper::to12HourFormat($val['finish']);
332       }
333       if (isset($val['cost'])) {
334         if ('.' != $user->decimal_mark)
335           $val['cost'] = str_replace('.', $user->decimal_mark, $val['cost']);
336       }
337       if (isset($val['expense'])) {
338         if ('.' != $user->decimal_mark)
339           $val['expense'] = str_replace('.', $user->decimal_mark, $val['expense']);
340       }
341       if ('no_grouping' != $group_by_option) {
342         $val['grouped_by'] = $val[$group_by_option];
343         if ('date' == $group_by_option) {
344           // This is needed to get the date in user date format.
345           $o_date = new DateAndTime(DB_DATEFORMAT, $val['grouped_by']);
346           $val['grouped_by'] = $o_date->toString($user->date_format);
347           unset($o_date);
348         }
349       }
350
351       // This is needed to get the date in user date format.
352       $o_date = new DateAndTime(DB_DATEFORMAT, $val['date']);
353       $val['date'] = $o_date->toString($user->date_format);
354       unset($o_date);
355
356       $row = $val;
357       $report_items[] = $row;
358     }
359
360     return $report_items;
361   }
362
363   // putInSession stores tt_log and tt_expense_items ids from a report in user session
364   // as 2 comma-separated lists.
365   static function putInSession($report_items) {
366     unset($_SESSION['report_item_ids']);
367     unset($_SESSION['report_item_expense_ids']);
368
369     // Iterate through records and build 2 comma-separated lists.
370     foreach($report_items as $item) {
371       if ($item['type'] == 1)
372         $report_item_ids .= ','.$item['id'];
373       else if ($item['type'] == 2)
374          $report_item_expense_ids .= ','.$item['id'];
375     }
376     $report_item_ids = trim($report_item_ids, ',');
377     $report_item_expense_ids = trim($report_item_expense_ids, ',');
378
379     // The lists are reqdy. Put them in session.
380     if ($report_item_ids) $_SESSION['report_item_ids'] = $report_item_ids;
381     if ($report_item_expense_ids) $_SESSION['report_item_expense_ids'] = $report_item_expense_ids;
382   }
383
384   // getFromSession obtains tt_log and tt_expense_items ids stored in user session.
385   static function getFromSession() {
386     $items = array();
387     $report_item_ids = $_SESSION['report_item_ids'];
388     if ($report_item_ids)
389       $items['report_item_ids'] = explode(',', $report_item_ids);
390     $report_item_expense_ids = $_SESSION['report_item_expense_ids'];
391     if ($report_item_expense_ids)
392       $items['report_item_expense_ids'] = explode(',', $report_item_expense_ids);
393     return $items;
394   }
395
396   // getFavItems retrieves all items associated with a favorite report.
397   // It combines tt_log and tt_expense_items in one array for presentation in one table using mysql union all.
398   // Expense items use the "note" field for item name.
399   static function getFavItems($options) {
400     global $user;
401     $mdb2 = getConnection();
402
403     // Determine these once as they are used in multiple places in this function.
404     $canViewReports = $user->can('view_reports');
405     $isClient = $user->isClient();
406
407     $group_by_option = $options['group_by'];
408     $convertTo12Hour = ('%I:%M %p' == $user->time_format) && ($options['show_start'] || $options['show_end']);
409
410     // Prepare a query for time items in tt_log table.
411     $fields = array(); // An array of fields for database query.
412     array_push($fields, 'l.id as id');
413     array_push($fields, '1 as type'); // Type 1 is for tt_log entries.
414     array_push($fields, 'l.date as date');
415     if($canViewReports || $isClient)
416       array_push($fields, 'u.name as user');
417     // Add client name if it is selected.
418     if ($options['show_client'] || 'client' == $group_by_option)
419       array_push($fields, 'c.name as client');
420     // Add project name if it is selected.
421     if ($options['show_project'] || 'project' == $group_by_option)
422       array_push($fields, 'p.name as project');
423     // Add task name if it is selected.
424     if ($options['show_task'] || 'task' == $group_by_option)
425       array_push($fields, 't.name as task');
426     // Add custom field.
427     $include_cf_1 = $options['show_custom_field_1'] || 'cf_1' == $group_by_option;
428     if ($include_cf_1) {
429       $custom_fields = new CustomFields($user->group_id);
430       $cf_1_type = $custom_fields->fields[0]['type'];
431       if ($cf_1_type == CustomFields::TYPE_TEXT) {
432         array_push($fields, 'cfl.value as cf_1');
433       } elseif ($cf_1_type == CustomFields::TYPE_DROPDOWN) {
434         array_push($fields, 'cfo.value as cf_1');
435       }
436     }
437     // Add start time.
438     if ($options['show_start']) {
439       array_push($fields, "l.start as unformatted_start");
440       array_push($fields, "TIME_FORMAT(l.start, '%k:%i') as start");
441     }
442     // Add finish time.
443     if ($options['show_end'])
444       array_push($fields, "TIME_FORMAT(sec_to_time(time_to_sec(l.start) + time_to_sec(l.duration)), '%k:%i') as finish");
445     // Add duration.
446     if ($options['show_duration'])
447       array_push($fields, "TIME_FORMAT(l.duration, '%k:%i') as duration");
448     // Add work units.
449     if ($options['show_work_units']) {
450       if ($user->unit_totals_only)
451         array_push($fields, "null as units");
452       else
453         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");
454     }
455
456     // Add note.
457     if ($options['show_note'])
458       array_push($fields, 'l.comment as note');
459     // Handle cost.
460     $includeCost = $options['show_cost'];
461     if ($includeCost) {
462       if (MODE_TIME == $user->tracking_mode)
463         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.
464       else
465         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.
466       array_push($fields, "null as expense"); 
467     }
468     // Add paid status.
469     if ($canViewReports && $options['show_paid'])
470       array_push($fields, 'l.paid as paid');
471     // Add IP address.
472     if ($canViewReports && $options['show_ip']) {
473       array_push($fields, 'l.created as created');
474       array_push($fields, 'l.created_ip as created_ip');
475       array_push($fields, 'l.modified as modified');
476       array_push($fields, 'l.modified_ip as modified_ip');
477     }
478     // Add invoice name if it is selected.
479     if (($canViewReports || $isClient) && $options['show_invoice'])
480       array_push($fields, 'i.name as invoice');
481
482     // Prepare sql query part for left joins.
483     $left_joins = null;
484     if ($options['show_client'] || 'client' == $group_by_option)
485       $left_joins .= " left join tt_clients c on (c.id = l.client_id)";
486     if (($canViewReports || $isClient) && $options['show_invoice'])
487       $left_joins .= " left join tt_invoices i on (i.id = l.invoice_id and i.status = 1)";
488     if ($canViewReports || $isClient || $user->isPluginEnabled('ex'))
489        $left_joins .= " left join tt_users u on (u.id = l.user_id)";
490     if ($options['show_project'] || 'project' == $group_by_option)
491       $left_joins .= " left join tt_projects p on (p.id = l.project_id)";
492     if ($options['show_task'] || 'task' == $group_by_option)
493       $left_joins .= " left join tt_tasks t on (t.id = l.task_id)";
494     if ($include_cf_1) {
495       if ($cf_1_type == CustomFields::TYPE_TEXT)
496         $left_joins .= " left join tt_custom_field_log cfl on (l.id = cfl.log_id and cfl.status = 1)";
497       elseif ($cf_1_type == CustomFields::TYPE_DROPDOWN) {
498         $left_joins .=  " left join tt_custom_field_log cfl on (l.id = cfl.log_id and cfl.status = 1)".
499           " left join tt_custom_field_options cfo on (cfl.option_id = cfo.id)";
500       }
501     }
502     if ($includeCost && MODE_TIME != $user->tracking_mode)
503       $left_joins .= " left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id)";
504
505     $where = ttReportHelper::getWhere($options);
506
507     // Construct sql query for tt_log items.
508     $sql = "select ".join(', ', $fields)." from tt_log l $left_joins $where";
509     // If we don't have expense items (such as when the Expenses plugin is desabled), the above is all sql we need,
510     // with an exception of sorting part, that is added in the end.
511
512     // However, when we have expenses, we need to do a union with a separate query for expense items from tt_expense_items table.
513     if ($options['show_cost'] && $user->isPluginEnabled('ex')) { // if ex(penses) plugin is enabled
514
515       $fields = array(); // An array of fields for database query.
516       array_push($fields, 'ei.id');
517       array_push($fields, '2 as type'); // Type 2 is for tt_expense_items entries.
518       array_push($fields, 'ei.date');
519       if($canViewReports || $isClient)
520         array_push($fields, 'u.name as user');
521       // Add client name if it is selected.
522       if ($options['show_client'] || 'client' == $group_by_option)
523         array_push($fields, 'c.name as client');
524       // Add project name if it is selected.
525       if ($options['show_project'] || 'project' == $group_by_option)
526         array_push($fields, 'p.name as project');
527       if ($options['show_task'] || 'task' == $group_by_option)
528         array_push($fields, 'null'); // null for task name. We need to match column count for union.
529       if ($options['show_custom_field_1'] || 'cf_1' == $group_by_option)
530         array_push($fields, 'null'); // null for cf_1.
531       if ($options['show_start']) {
532         array_push($fields, 'null'); // null for unformatted_start.
533         array_push($fields, 'null'); // null for start.
534       }
535       if ($options['show_end'])
536         array_push($fields, 'null'); // null for finish.
537       if ($options['show_duration'])
538         array_push($fields, 'null'); // null for duration.
539       if ($options['show_work_units'])
540         array_push($fields, 'null as units'); // null for work units.
541       // Use the note field to print item name.
542       if ($options['show_note'])
543         array_push($fields, 'ei.name as note');
544       array_push($fields, 'ei.cost as cost');
545       array_push($fields, 'ei.cost as expense');
546       // Add paid status.
547       if ($canViewReports && $options['show_paid'])
548         array_push($fields, 'ei.paid as paid');
549       // Add IP address.
550       if ($canViewReports && $options['show_ip']) {
551         array_push($fields, 'ei.created as created');
552         array_push($fields, 'ei.created_ip as created_ip');
553         array_push($fields, 'ei.modified as modified');
554         array_push($fields, 'ei.modified_ip as modified_ip');
555       }
556       // Add invoice name if it is selected.
557       if (($canViewReports || $isClient) && $options['show_invoice'])
558         array_push($fields, 'i.name as invoice');
559
560       // Prepare sql query part for left joins.
561       $left_joins = null;
562       if ($canViewReports || $isClient)
563         $left_joins .= " left join tt_users u on (u.id = ei.user_id)";
564       if ($options['show_client'] || 'client' == $group_by_option)
565         $left_joins .= " left join tt_clients c on (c.id = ei.client_id)";
566       if ($options['show_project'] || 'project' == $group_by_option)
567         $left_joins .= " left join tt_projects p on (p.id = ei.project_id)";
568       if (($canViewReports || $isClient) && $options['show_invoice'])
569         $left_joins .= " left join tt_invoices i on (i.id = ei.invoice_id and i.status = 1)";
570
571       $where = ttReportHelper::getExpenseWhere($options);
572
573       // Construct sql query for expense items.
574       $sql_for_expense_items = "select ".join(', ', $fields)." from tt_expense_items ei $left_joins $where";
575
576       // Construct a union.
577       $sql = "($sql) union all ($sql_for_expense_items)";
578     }
579
580     // Determine sort part.
581     $sort_part = ' order by ';
582     if ($group_by_option == null || 'no_grouping' == $group_by_option || 'date' == $group_by_option) // TODO: fix DB for NULL values in group_by field.
583       $sort_part .= 'date';
584     else
585       $sort_part .= $group_by_option.', date';
586     if (($canViewReports || $isClient) /*&& is_array($bean->getAttribute('users'))*/ && 'user' != $group_by_option)
587       $sort_part .= ', user, type';
588     if ($options['show_start'])
589       $sort_part .= ', unformatted_start';
590     $sort_part .= ', id';
591
592     $sql .= $sort_part;
593     // By now we are ready with sql.
594
595     // Obtain items for report.
596     $res = $mdb2->query($sql);
597     if (is_a($res, 'PEAR_Error')) die($res->getMessage());
598
599     while ($val = $res->fetchRow()) {
600       if ($convertTo12Hour) {
601         if($val['start'] != '')
602           $val['start'] = ttTimeHelper::to12HourFormat($val['start']);
603         if($val['finish'] != '')
604           $val['finish'] = ttTimeHelper::to12HourFormat($val['finish']);
605       }
606       if (isset($val['cost'])) {
607         if ('.' != $user->decimal_mark)
608           $val['cost'] = str_replace('.', $user->decimal_mark, $val['cost']);
609       }
610       if (isset($val['expense'])) {
611         if ('.' != $user->decimal_mark)
612           $val['expense'] = str_replace('.', $user->decimal_mark, $val['expense']);
613       }
614       if ('no_grouping' != $group_by_option) {
615         $val['grouped_by'] = $val[$group_by_option];
616         if ('date' == $group_by_option) {
617           // This is needed to get the date in user date format.
618           $o_date = new DateAndTime(DB_DATEFORMAT, $val['grouped_by']);
619           $val['grouped_by'] = $o_date->toString($user->date_format);
620           unset($o_date);
621         }
622       }
623
624       // This is needed to get the date in user date format.
625       $o_date = new DateAndTime(DB_DATEFORMAT, $val['date']);
626       $val['date'] = $o_date->toString($user->date_format);
627       unset($o_date);
628
629       $row = $val;
630       $report_items[] = $row;
631     }
632
633     return $report_items;
634   }
635
636   // getSubtotals calculates report items subtotals when a report is grouped by.
637   // Without expenses, it's a simple select with group by.
638   // With expenses, it becomes a select with group by from a combined set of records obtained with "union all".
639   static function getSubtotals($bean, $options) {
640     global $user;
641
642     $group_by_option = $bean->getAttribute('group_by');
643     if ('no_grouping' == $group_by_option) return null;
644
645     $mdb2 = getConnection();
646
647     // Start with sql to obtain subtotals for time items. This simple sql will be used when we have no expenses.
648
649     // Determine group by field and a required join.
650     switch ($group_by_option) {
651       case 'date':
652         $group_field = 'l.date';
653         $group_join = '';
654         break;
655       case 'user':
656         $group_field = 'u.name';
657         $group_join = 'left join tt_users u on (l.user_id = u.id) ';
658         break;
659       case 'client':
660         $group_field = 'c.name';
661         $group_join = 'left join tt_clients c on (l.client_id = c.id) ';
662         break;
663       case 'project':
664         $group_field = 'p.name';
665         $group_join = 'left join tt_projects p on (l.project_id = p.id) ';
666         break;
667       case 'task':
668         $group_field = 't.name';
669         $group_join = 'left join tt_tasks t on (l.task_id = t.id) ';
670         break;
671       case 'cf_1':
672         $group_field = 'cfo.value';
673         $custom_fields = new CustomFields($user->group_id);
674         if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_TEXT)
675           $group_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) ';
676         elseif ($custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN)
677           $group_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) ';
678         break;
679     }
680
681     $where = ttReportHelper::getWhere($options);
682     if ($bean->getAttribute('chcost')) {
683       if (MODE_TIME == $user->tracking_mode) {
684         if ($group_by_option != 'user')
685           $left_join = 'left join tt_users u on (l.user_id = u.id)';
686         $sql = "select $group_field as group_field, sum(time_to_sec(l.duration)) as time";
687         if ($bean->getAttribute('chunits')) {
688           if ($user->unit_totals_only)
689             $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";
690           else
691             $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";
692         }
693         $sql .= ", sum(cast(l.billable * coalesce(u.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10, 2))) as cost,
694           null as expenses from tt_log l
695           $group_join $left_join $where group by $group_field";
696       } else {
697         // If we are including cost and tracking projects, our query (the same as above) needs to join the tt_user_project_binds table.
698         $sql = "select $group_field as group_field, sum(time_to_sec(l.duration)) as time";
699         if ($bean->getAttribute('chunits')) {
700           if ($user->unit_totals_only)
701             $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";
702           else
703             $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";
704         }
705         $sql .= ", sum(cast(l.billable * coalesce(upb.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10,2))) as cost,
706           null as expenses from tt_log l
707           $group_join
708           left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id) $where group by $group_field";
709       }
710     } else {
711       $sql = "select $group_field as group_field, sum(time_to_sec(l.duration)) as time";
712       if ($bean->getAttribute('chunits')) {
713         if ($user->unit_totals_only)
714           $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";
715         else
716           $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";
717       }
718       $sql .= ", null as expenses from tt_log l
719         $group_join $where group by $group_field";
720     }
721     // By now we have sql for time items.
722
723     // However, when we have expenses, we need to do a union with a separate query for expense items from tt_expense_items table.
724     if ($bean->getAttribute('chcost') && $user->isPluginEnabled('ex')) { // if ex(penses) plugin is enabled
725
726       // Determine group by field and a required join.
727       $group_join = null;
728       $group_field = 'null';
729       switch ($group_by_option) {
730         case 'date':
731           $group_field = 'ei.date';
732           $group_join = '';
733           break;
734         case 'user':
735           $group_field = 'u.name';
736           $group_join = 'left join tt_users u on (ei.user_id = u.id) ';
737           break;
738         case 'client':
739           $group_field = 'c.name';
740           $group_join = 'left join tt_clients c on (ei.client_id = c.id) ';
741           break;
742         case 'project':
743           $group_field = 'p.name';
744           $group_join = 'left join tt_projects p on (ei.project_id = p.id) ';
745           break;
746       }
747
748       $where = ttReportHelper::getExpenseWhere($options);
749       $sql_for_expenses = "select $group_field as group_field, null as time";
750       if ($bean->getAttribute('chunits')) $sql_for_expenses .= ", null as units";
751       $sql_for_expenses .= ", sum(ei.cost) as cost, sum(ei.cost) as expenses from tt_expense_items ei $group_join $where";
752       // Add a "group by" clause if we are grouping.
753       if ('null' != $group_field) $sql_for_expenses .= " group by $group_field";
754
755       // Create a combined query.
756       $combined = "select group_field, sum(time) as time";
757       if ($bean->getAttribute('chunits')) $combined .= ", sum(units) as units";
758       $combined .= ", sum(cost) as cost, sum(expenses) as expenses from (($sql) union all ($sql_for_expenses)) t group by group_field";
759       $sql = $combined;
760     }
761
762     // Execute query.
763     $res = $mdb2->query($sql);
764     if (is_a($res, 'PEAR_Error')) die($res->getMessage());
765
766     while ($val = $res->fetchRow()) {
767       if ('date' == $group_by_option) {
768         // This is needed to get the date in user date format.
769         $o_date = new DateAndTime(DB_DATEFORMAT, $val['group_field']);
770         $val['group_field'] = $o_date->toString($user->date_format);
771         unset($o_date);
772       }
773       $time = $val['time'] ? sec_to_time_fmt_hm($val['time']) : null;
774       if ($bean->getAttribute('chcost')) {
775         if ('.' != $user->decimal_mark) {
776           $val['cost'] = str_replace('.', $user->decimal_mark, $val['cost']);
777           $val['expenses'] = str_replace('.', $user->decimal_mark, $val['expenses']);
778         }
779         $subtotals[$val['group_field']] = array('name'=>$val['group_field'],'time'=>$time, 'units'=> $val['units'],'cost'=>$val['cost'],'expenses'=>$val['expenses']);
780       } else
781         $subtotals[$val['group_field']] = array('name'=>$val['group_field'],'time'=>$time, 'units'=> $val['units']);
782     }
783
784     return $subtotals;
785   }
786
787   // getFavSubtotals calculates report items subtotals when a favorite report is grouped by.
788   // Without expenses, it's a simple select with group by.
789   // With expenses, it becomes a select with group by from a combined set of records obtained with "union all".
790   static function getFavSubtotals($options) {
791     global $user;
792
793     $group_by_option = $options['group_by'];
794     if ('no_grouping' == $group_by_option) return null;
795
796     $mdb2 = getConnection();
797
798     // Start with sql to obtain subtotals for time items. This simple sql will be used when we have no expenses.
799
800     // Determine group by field and a required join.
801     switch ($group_by_option) {
802       case 'date':
803         $group_field = 'l.date';
804         $group_join = '';
805         break;
806       case 'user':
807         $group_field = 'u.name';
808         $group_join = 'left join tt_users u on (l.user_id = u.id) ';
809         break;
810       case 'client':
811         $group_field = 'c.name';
812         $group_join = 'left join tt_clients c on (l.client_id = c.id) ';
813         break;
814       case 'project':
815         $group_field = 'p.name';
816         $group_join = 'left join tt_projects p on (l.project_id = p.id) ';
817         break;
818       case 'task':
819         $group_field = 't.name';
820         $group_join = 'left join tt_tasks t on (l.task_id = t.id) ';
821         break;
822       case 'cf_1':
823         $group_field = 'cfo.value';
824         $custom_fields = new CustomFields($user->group_id);
825         if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_TEXT)
826           $group_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) ';
827         elseif ($custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN)
828           $group_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) ';
829         break;
830     }
831
832     $where = ttReportHelper::getWhere($options);
833     if ($options['show_cost']) {
834       if (MODE_TIME == $user->tracking_mode) {
835         if ($group_by_option != 'user')
836           $left_join = 'left join tt_users u on (l.user_id = u.id)';
837           $sql = "select $group_field as group_field, sum(time_to_sec(l.duration)) as time";
838           if ($options['show_work_units']) {
839             if ($user->unit_totals_only)
840               $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";
841             else
842               $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";
843           }
844           $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";
845           $sql .= ", sum(cast(l.billable * coalesce(u.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10, 2))) as cost,
846           null as expenses from tt_log l
847           $group_join $left_join $where group by $group_field";
848       } else {
849         // If we are including cost and tracking projects, our query (the same as above) needs to join the tt_user_project_binds table.
850         $sql = "select $group_field as group_field, sum(time_to_sec(l.duration)) as time";
851         if ($options['show_work_units']) {
852           if ($user->unit_totals_only)
853             $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";
854           else
855             $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";
856         }
857         $sql .= ", sum(cast(l.billable * coalesce(upb.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10,2))) as cost,
858           null as expenses from tt_log l 
859           $group_join
860           left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id) $where group by $group_field";
861       }
862     } else {
863       $sql = "select $group_field as group_field, sum(time_to_sec(l.duration)) as time";
864       if ($options['show_work_units']) {
865         if ($user->unit_totals_only)
866           $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";
867         else
868           $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";
869       }
870       $sql .= ", null as expenses from tt_log l 
871         $group_join $where group by $group_field";
872     }
873     // By now we have sql for time items.
874
875     // However, when we have expenses, we need to do a union with a separate query for expense items from tt_expense_items table.
876     if ($options['show_cost'] && $user->isPluginEnabled('ex')) { // if ex(penses) plugin is enabled
877
878       // Determine group by field and a required join.
879       $group_join = null;
880       $group_field = 'null';
881       switch ($group_by_option) {
882         case 'date':
883           $group_field = 'ei.date';
884           $group_join = '';
885           break;
886         case 'user':
887           $group_field = 'u.name';
888           $group_join = 'left join tt_users u on (ei.user_id = u.id) ';
889           break;
890         case 'client':
891           $group_field = 'c.name';
892           $group_join = 'left join tt_clients c on (ei.client_id = c.id) ';
893           break;
894         case 'project':
895           $group_field = 'p.name';
896           $group_join = 'left join tt_projects p on (ei.project_id = p.id) ';
897           break;
898       }
899
900       $where = ttReportHelper::getExpenseWhere($options);
901       $sql_for_expenses = "select $group_field as group_field, null as time";
902       if ($options['show_work_units']) $sql_for_expenses .= ", null as units";
903       $sql_for_expenses .= ", sum(ei.cost) as cost, sum(ei.cost) as expenses from tt_expense_items ei $group_join $where";
904       // Add a "group by" clause if we are grouping.
905       if ('null' != $group_field) $sql_for_expenses .= " group by $group_field";
906
907       // Create a combined query.
908       $combined = "select group_field, sum(time) as time";
909       if ($options['show_work_units']) $combined .= ", sum(units) as units";
910       $combined .= ", sum(cost) as cost, sum(expenses) as expenses from (($sql) union all ($sql_for_expenses)) t group by group_field";
911       $sql = $combined;
912     }
913
914     // Execute query.
915     $res = $mdb2->query($sql);
916     if (is_a($res, 'PEAR_Error')) die($res->getMessage());
917
918     while ($val = $res->fetchRow()) {
919       if ('date' == $group_by_option) {
920         // This is needed to get the date in user date format.
921         $o_date = new DateAndTime(DB_DATEFORMAT, $val['group_field']);
922         $val['group_field'] = $o_date->toString($user->date_format);
923         unset($o_date);
924       }
925       $time = $val['time'] ? sec_to_time_fmt_hm($val['time']) : null;
926       if ($options['show_cost']) {
927         if ('.' != $user->decimal_mark) {
928           $val['cost'] = str_replace('.', $user->decimal_mark, $val['cost']);
929           $val['expenses'] = str_replace('.', $user->decimal_mark, $val['expenses']);
930         }
931         $subtotals[$val['group_field']] = array('name'=>$val['group_field'],'time'=>$time, 'units'=> $val['units'], 'cost'=>$val['cost'],'expenses'=>$val['expenses']);
932       } else
933         $subtotals[$val['group_field']] = array('name'=>$val['group_field'],'time'=>$time, 'units'=> $val['units']);
934     }
935
936     return $subtotals;
937   }
938
939   // getTotals calculates total hours and cost for all report items.
940   static function getTotals($bean, $options)
941   {
942     global $user;
943
944     $mdb2 = getConnection();
945
946     $where = ttReportHelper::getWhere($options);
947
948     // Prepare parts.
949     $time_part = "sum(time_to_sec(l.duration)) as time";
950     if ($bean->getAttribute('chunits')) {
951       $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";
952     }
953     if ($bean->getAttribute('chcost')) {
954       if (MODE_TIME == $user->tracking_mode)
955         $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";
956       else
957         $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";
958     } else {
959       $cost_part = ", null as cost, null as expenses";
960     }
961     if ($bean->getAttribute('chcost')) {
962       if (MODE_TIME == $user->tracking_mode) {
963         $left_joins = "left join tt_users u on (l.user_id = u.id)";
964       } else {
965         $left_joins = "left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id)";
966       }
967     }
968     // Prepare a query for time items.
969     $sql = "select $time_part $units_part $cost_part from tt_log l $left_joins $where";
970
971     // If we have expenses, query becomes a bit more complex.
972     if ($bean->getAttribute('chcost') && $user->isPluginEnabled('ex')) {
973       $where = ttReportHelper::getExpenseWhere($options);
974       $sql_for_expenses = "select null as time";
975       if ($bean->getAttribute('chunits')) $sql_for_expenses .= ", null as units";
976       $sql_for_expenses .= ", sum(cost) as cost, sum(cost) as expenses from tt_expense_items ei $where";
977
978       // Create a combined query.
979       $combined = "select sum(time) as time";
980       if ($bean->getAttribute('chunits')) $combined .= ", sum(units) as units";
981       $combined .= ", sum(cost) as cost, sum(expenses) as expenses from (($sql) union all ($sql_for_expenses)) t";
982       $sql = $combined;
983     }
984
985     // Execute query.
986     $res = $mdb2->query($sql);
987     if (is_a($res, 'PEAR_Error')) die($res->getMessage());
988
989     $val = $res->fetchRow();
990     $total_time = $val['time'] ? sec_to_time_fmt_hm($val['time']) : null;
991     if ($bean->getAttribute('chcost')) {
992       $total_cost = $val['cost'];
993       if (!$total_cost) $total_cost = '0.00';
994       if ('.' != $user->decimal_mark)
995         $total_cost = str_replace('.', $user->decimal_mark, $total_cost);
996       $total_expenses = $val['expenses'];
997       if (!$total_expenses) $total_expenses = '0.00';
998       if ('.' != $user->decimal_mark)
999         $total_expenses = str_replace('.', $user->decimal_mark, $total_expenses);
1000     }
1001
1002     if ($bean->getAttribute('period'))
1003       $period = new Period($bean->getAttribute('period'), new DateAndTime($user->date_format));
1004     else {
1005       $period = new Period();
1006       $period->setPeriod(
1007         new DateAndTime($user->date_format, $bean->getAttribute('start_date')),
1008         new DateAndTime($user->date_format, $bean->getAttribute('end_date')));
1009     }
1010
1011     $totals['start_date'] = $period->getStartDate();
1012     $totals['end_date'] = $period->getEndDate();
1013     $totals['time'] = $total_time;
1014     $totals['units'] = $val['units'];
1015     $totals['cost'] = $total_cost;
1016     $totals['expenses'] = $total_expenses;
1017
1018     return $totals;
1019   }
1020
1021   // getFavTotals calculates total hours and cost for all favorite report items.
1022   static function getFavTotals($options)
1023   {
1024     global $user;
1025
1026     $mdb2 = getConnection();
1027
1028     $where = ttReportHelper::getWhere($options);
1029
1030     // Prepare parts.
1031     $time_part = "sum(time_to_sec(l.duration)) as time";
1032     if ($options['show_work_units']) {
1033       $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";
1034     }
1035     if ($options['show_cost']) {
1036       if (MODE_TIME == $user->tracking_mode)
1037         $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";
1038       else
1039         $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";
1040     } else {
1041       $cost_part = ", null as cost, null as expenses";
1042     }
1043     if ($options['show_cost']) {
1044       if (MODE_TIME == $user->tracking_mode) {
1045         $left_joins = "left join tt_users u on (l.user_id = u.id)";
1046       } else {
1047         $left_joins = "left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id)";
1048       }
1049     }
1050     // Prepare a query for time items.
1051     $sql = "select $time_part $units_part $cost_part from tt_log l $left_joins $where";
1052
1053     // If we have expenses, query becomes a bit more complex.
1054     if ($options['show_cost'] && $user->isPluginEnabled('ex')) {
1055       $where = ttReportHelper::getExpenseWhere($options);
1056       $sql_for_expenses = "select null as time";
1057       if ($options['show_work_units']) $sql_for_expenses .= ", null as units";
1058       $sql_for_expenses .= ", sum(cost) as cost, sum(cost) as expenses from tt_expense_items ei $where";
1059
1060       // Create a combined query.
1061       $combined = "select sum(time) as time";
1062       if ($options['show_work_units']) $combined .= ", sum(units) as units";
1063       $combined .= ", sum(cost) as cost, sum(expenses) as expenses from (($sql) union all ($sql_for_expenses)) t";
1064       $sql = $combined;
1065     }
1066
1067     // Execute query.
1068     $res = $mdb2->query($sql);
1069     if (is_a($res, 'PEAR_Error')) die($res->getMessage());
1070
1071     $val = $res->fetchRow();
1072     $total_time = $val['time'] ? sec_to_time_fmt_hm($val['time']) : null;
1073     if ($options['show_cost']) {
1074       $total_cost = $val['cost'];
1075       if (!$total_cost) $total_cost = '0.00';
1076       if ('.' != $user->decimal_mark)
1077         $total_cost = str_replace('.', $user->decimal_mark, $total_cost);
1078       $total_expenses = $val['expenses'];
1079       if (!$total_expenses) $total_expenses = '0.00';
1080       if ('.' != $user->decimal_mark)
1081         $total_expenses = str_replace('.', $user->decimal_mark, $total_expenses);
1082     }
1083
1084     if ($options['period'])
1085       $period = new Period($options['period'], new DateAndTime($user->date_format));
1086     else {
1087       $period = new Period();
1088       $period->setPeriod(
1089         new DateAndTime($user->date_format, $options['period_start']),
1090         new DateAndTime($user->date_format, $options['period_end']));
1091     }
1092
1093     $totals['start_date'] = $period->getStartDate();
1094     $totals['end_date'] = $period->getEndDate();
1095     $totals['time'] = $total_time;
1096     $totals['units'] = $val['units'];
1097     $totals['cost'] = $total_cost;
1098     $totals['expenses'] = $total_expenses;
1099
1100     return $totals;
1101   }
1102
1103   // The assignToInvoice assigns a set of records to a specific invoice.
1104   static function assignToInvoice($invoice_id, $time_log_ids, $expense_item_ids)
1105   {
1106     $mdb2 = getConnection();
1107     if ($time_log_ids) {
1108       $sql = "update tt_log set invoice_id = ".$mdb2->quote($invoice_id).
1109         " where id in(".join(', ', $time_log_ids).")";
1110       $affected = $mdb2->exec($sql);
1111       if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
1112     }
1113     if ($expense_item_ids) {
1114       $sql = "update tt_expense_items set invoice_id = ".$mdb2->quote($invoice_id).
1115         " where id in(".join(', ', $expense_item_ids).")";
1116       $affected = $mdb2->exec($sql);
1117       if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
1118     }
1119   }
1120
1121   // The markPaid marks a set of records as either paid or unpaid.
1122   static function markPaid($time_log_ids, $expense_item_ids, $paid = true)
1123   {
1124     $mdb2 = getConnection();
1125     $paid_val = (int) $paid;
1126     if ($time_log_ids) {
1127       $sql = "update tt_log set paid = $paid_val where id in(".join(', ', $time_log_ids).")";
1128       $affected = $mdb2->exec($sql);
1129       if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
1130     }
1131     if ($expense_item_ids) {
1132       $sql = "update tt_expense_items set paid = $paid_val where id in(".join(', ', $expense_item_ids).")";
1133       $affected = $mdb2->exec($sql);
1134       if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
1135     }
1136   }
1137
1138   // prepareReportBody - prepares an email body for report.
1139   static function prepareReportBody($bean, $comment)
1140   {
1141     global $user;
1142     global $i18n;
1143
1144     // Determine these once as they are used in multiple places in this function.
1145     $canViewReports = $user->can('view_reports');
1146     $isClient = $user->isClient();
1147     $options = ttReportHelper::getReportOptions($bean);
1148
1149     $items = ttReportHelper::getItems($bean, $options);
1150     $group_by = $bean->getAttribute('group_by');
1151     if ($group_by && 'no_grouping' != $group_by)
1152       $subtotals = ttReportHelper::getSubtotals($bean, $options);
1153     $totals = ttReportHelper::getTotals($bean, $options);
1154
1155     // Use custom fields plugin if it is enabled.
1156     if ($user->isPluginEnabled('cf'))
1157       $custom_fields = new CustomFields($user->group_id);
1158
1159     // Define some styles to use in email.
1160     $style_title = 'text-align: center; font-size: 15pt; font-family: Arial, Helvetica, sans-serif;';
1161     $tableHeader = 'font-weight: bold; background-color: #a6ccf7; text-align: left;';
1162     $tableHeaderCentered = 'font-weight: bold; background-color: #a6ccf7; text-align: center;';
1163     $rowItem = 'background-color: #ffffff;';
1164     $rowItemAlt = 'background-color: #f5f5f5;';
1165     $rowSubtotal = 'background-color: #e0e0e0;';
1166     $cellLeftAligned = 'text-align: left; vertical-align: top;';
1167     $cellRightAligned = 'text-align: right; vertical-align: top;';
1168     $cellLeftAlignedSubtotal = 'font-weight: bold; text-align: left; vertical-align: top;';
1169     $cellRightAlignedSubtotal = 'font-weight: bold; text-align: right; vertical-align: top;';
1170
1171     // Start creating email body.
1172     $body = '<html>';
1173     $body .= '<head><meta http-equiv="content-type" content="text/html; charset='.CHARSET.'"></head>';
1174     $body .= '<body>';
1175
1176     // Output title.
1177     $body .= '<p style="'.$style_title.'">'.$i18n->get('form.mail.report_subject').': '.$totals['start_date'].' - '.$totals['end_date'].'</p>';
1178
1179     // Output comment.
1180     if ($comment) $body .= '<p>'.htmlspecialchars($comment).'</p>';
1181
1182     if ($bean->getAttribute('chtotalsonly')) {
1183       // Totals only report. Output subtotals.
1184
1185       // Determine group_by header.
1186       if ('cf_1' == $group_by)
1187         $group_by_header = htmlspecialchars($custom_fields->fields[0]['label']);
1188       else {
1189         $key = 'label.'.$group_by;
1190         $group_by_header = $i18n->get($key);
1191       }
1192
1193       $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
1194       $body .= '<tr>';
1195       $body .= '<td style="'.$tableHeader.'">'.$group_by_header.'</td>';
1196       if ($bean->getAttribute('chduration'))
1197         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.duration').'</td>';
1198       if ($bean->getAttribute('chunits'))
1199         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.work_units_short').'</td>';
1200       if ($bean->getAttribute('chcost'))
1201         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.cost').'</td>';
1202       $body .= '</tr>';
1203       foreach($subtotals as $subtotal) {
1204         $body .= '<tr style="'.$rowSubtotal.'">';
1205         $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($subtotal['name'] ? htmlspecialchars($subtotal['name']) : '&nbsp;').'</td>';
1206         if ($bean->getAttribute('chduration')) {
1207           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1208           if ($subtotal['time'] <> '0:00') $body .= $subtotal['time'];
1209           $body .= '</td>';
1210         }
1211         if ($bean->getAttribute('chunits')) {
1212           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1213           $body .= $subtotal['units'];
1214           $body .= '</td>';
1215         }
1216         if ($bean->getAttribute('chcost')) {
1217           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1218           $body .= ($canViewReports || $isClient) ? $subtotal['cost'] : $subtotal['expenses'];
1219           $body .= '</td>';
1220         }
1221         $body .= '</tr>';
1222       }
1223
1224       // Print totals.
1225       $body .= '<tr><td>&nbsp;</td></tr>';
1226       $body .= '<tr style="'.$rowSubtotal.'">';
1227       $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.total').'</td>';
1228       if ($bean->getAttribute('chduration')) {
1229         $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1230         if ($totals['time'] <> '0:00') $body .= $totals['time'];
1231         $body .= '</td>';
1232       }
1233       if ($bean->getAttribute('chunits')) {
1234         $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1235         $body .= $totals['units'];
1236         $body .= '</td>';
1237       }
1238       if ($bean->getAttribute('chcost')) {
1239         $body .= '<td nowrap style="'.$cellRightAlignedSubtotal.'">'.htmlspecialchars($user->currency).' ';
1240         $body .= ($canViewReports || $isClient) ? $totals['cost'] : $totals['expenses'];
1241         $body .= '</td>';
1242       }
1243       $body .= '</tr>';
1244
1245       $body .= '</table>';
1246     } else {
1247       // Regular report.
1248
1249       // Print table header.
1250       $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
1251       $body .= '<tr>';
1252       $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.date').'</td>';
1253       if ($canViewReports || $isClient)
1254         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.user').'</td>';
1255       if ($bean->getAttribute('chclient'))
1256         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.client').'</td>';
1257       if ($bean->getAttribute('chproject'))
1258         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.project').'</td>';
1259       if ($bean->getAttribute('chtask'))
1260         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.task').'</td>';
1261       if ($bean->getAttribute('chcf_1'))
1262         $body .= '<td style="'.$tableHeader.'">'.htmlspecialchars($custom_fields->fields[0]['label']).'</td>';
1263       if ($bean->getAttribute('chstart'))
1264         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.start').'</td>';
1265       if ($bean->getAttribute('chfinish'))
1266         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.finish').'</td>';
1267       if ($bean->getAttribute('chduration'))
1268         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.duration').'</td>';
1269       if ($bean->getAttribute('chunits'))
1270         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.work_units_short').'</td>';
1271       if ($bean->getAttribute('chnote'))
1272         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.note').'</td>';
1273       if ($bean->getAttribute('chcost'))
1274         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.cost').'</td>';
1275       if ($bean->getAttribute('chpaid'))
1276         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.paid').'</td>';
1277       if ($bean->getAttribute('chip'))
1278         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.ip').'</td>';
1279       if ($bean->getAttribute('chinvoice'))
1280         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.invoice').'</td>';
1281       $body .= '</tr>';
1282
1283       // Initialize variables to print subtotals.
1284       if ($items && 'no_grouping' != $group_by) {
1285         $print_subtotals = true;
1286         $first_pass = true;
1287         $prev_grouped_by = '';
1288         $cur_grouped_by = '';
1289       }
1290       // Initialize variables to alternate color of rows for different dates.
1291       $prev_date = '';
1292       $cur_date = '';
1293       $row_style = $rowItem;
1294
1295       // Print report items.
1296       if (is_array($items)) {
1297         foreach ($items as $record) {
1298           $cur_date = $record['date'];
1299           // Print a subtotal row after a block of grouped items.
1300           if ($print_subtotals) {
1301             $cur_grouped_by = $record['grouped_by'];
1302             if ($cur_grouped_by != $prev_grouped_by && !$first_pass) {
1303               $body .= '<tr style="'.$rowSubtotal.'">';
1304               $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.subtotal').'</td>';
1305               $subtotal_name = htmlspecialchars($subtotals[$prev_grouped_by]['name']);
1306               if ($canViewReports || $isClient) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'user' ? $subtotal_name : '').'</td>';
1307               if ($bean->getAttribute('chclient')) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'client' ? $subtotal_name : '').'</td>';
1308               if ($bean->getAttribute('chproject')) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'project' ? $subtotal_name : '').'</td>';
1309               if ($bean->getAttribute('chtask')) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'task' ? $subtotal_name : '').'</td>';
1310               if ($bean->getAttribute('chcf_1')) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'cf_1' ? $subtotal_name : '').'</td>';
1311               if ($bean->getAttribute('chstart')) $body .= '<td></td>';
1312               if ($bean->getAttribute('chfinish')) $body .= '<td></td>';
1313               if ($bean->getAttribute('chduration')) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['time'].'</td>';
1314               if ($bean->getAttribute('chunits')) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['units'].'</td>';
1315               if ($bean->getAttribute('chnote')) $body .= '<td></td>';
1316               if ($bean->getAttribute('chcost')) {
1317                 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1318                 $body .= ($canViewReports || $isClient) ? $subtotals[$prev_grouped_by]['cost'] : $subtotals[$prev_grouped_by]['expenses'];
1319                 $body .= '</td>';
1320               }
1321               if ($bean->getAttribute('chpaid')) $body .= '<td></td>';
1322               if ($bean->getAttribute('chip')) $body .= '<td></td>';
1323               if ($bean->getAttribute('chinvoice')) $body .= '<td></td>';
1324               $body .= '</tr>';
1325               $body .= '<tr><td>&nbsp;</td></tr>';
1326             }
1327             $first_pass = false;
1328           }
1329
1330           // Print a regular row.
1331           if ($cur_date != $prev_date)
1332             $row_style = ($row_style == $rowItem) ? $rowItemAlt : $rowItem;
1333           $body .= '<tr style="'.$row_style.'">';
1334           $body .= '<td style="'.$cellLeftAligned.'">'.$record['date'].'</td>';
1335           if ($canViewReports || $isClient)
1336             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['user']).'</td>';
1337           if ($bean->getAttribute('chclient'))
1338             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['client']).'</td>';
1339           if ($bean->getAttribute('chproject'))
1340             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['project']).'</td>';
1341           if ($bean->getAttribute('chtask'))
1342             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['task']).'</td>';
1343           if ($bean->getAttribute('chcf_1'))
1344             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['cf_1']).'</td>';
1345           if ($bean->getAttribute('chstart'))
1346             $body .= '<td nowrap style="'.$cellRightAligned.'">'.$record['start'].'</td>';
1347           if ($bean->getAttribute('chfinish'))
1348             $body .= '<td nowrap style="'.$cellRightAligned.'">'.$record['finish'].'</td>';
1349           if ($bean->getAttribute('chduration'))
1350             $body .= '<td style="'.$cellRightAligned.'">'.$record['duration'].'</td>';
1351           if ($bean->getAttribute('chunits'))
1352             $body .= '<td style="'.$cellRightAligned.'">'.$record['units'].'</td>';
1353           if ($bean->getAttribute('chnote'))
1354             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['note']).'</td>';
1355           if ($bean->getAttribute('chcost'))
1356             $body .= '<td style="'.$cellRightAligned.'">'.$record['cost'].'</td>';
1357           if ($bean->getAttribute('chpaid')) {
1358             $body .= '<td style="'.$cellRightAligned.'">';
1359             $body .= $record['paid'] == 1 ? $i18n->get('label.yes') : $i18n->get('label.no');
1360             $body .= '</td>';
1361           }
1362           if ($bean->getAttribute('chip')) {
1363             $body .= '<td style="'.$cellRightAligned.'">';
1364             $body .= $record['modified'] ? $record['modified_ip'].' '.$record['modified'] : $record['created_ip'].' '.$record['created'];
1365             $body .= '</td>';
1366           }
1367           if ($bean->getAttribute('chinvoice'))
1368             $body .= '<td style="'.$cellRightAligned.'">'.htmlspecialchars($record['invoice']).'</td>';
1369           $body .= '</tr>';
1370
1371           $prev_date = $record['date'];
1372           if ($print_subtotals)
1373             $prev_grouped_by = $record['grouped_by'];
1374         }
1375       }
1376
1377       // Print a terminating subtotal.
1378       if ($print_subtotals) {
1379         $body .= '<tr style="'.$rowSubtotal.'">';
1380         $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.subtotal').'</td>';
1381         $subtotal_name = htmlspecialchars($subtotals[$cur_grouped_by]['name']);
1382         if ($canViewReports || $isClient) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'user' ? $subtotal_name : '').'</td>';
1383         if ($bean->getAttribute('chclient')) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'client' ? $subtotal_name : '').'</td>';
1384         if ($bean->getAttribute('chproject')) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'project' ? $subtotal_name : '').'</td>';
1385         if ($bean->getAttribute('chtask')) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'task' ? $subtotal_name : '').'</td>';
1386         if ($bean->getAttribute('chcf_1')) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'cf_1' ? $subtotal_name : '').'</td>';
1387         if ($bean->getAttribute('chstart')) $body .= '<td></td>';
1388         if ($bean->getAttribute('chfinish')) $body .= '<td></td>';
1389         if ($bean->getAttribute('chduration')) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$cur_grouped_by]['time'].'</td>';
1390         if ($bean->getAttribute('chunits')) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$cur_grouped_by]['units'].'</td>';
1391         if ($bean->getAttribute('chnote')) $body .= '<td></td>';
1392         if ($bean->getAttribute('chcost')) {
1393           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1394           $body .= ($canViewReports || $isClient) ? $subtotals[$cur_grouped_by]['cost'] : $subtotals[$cur_grouped_by]['expenses'];
1395           $body .= '</td>';
1396         }
1397         if ($bean->getAttribute('chpaid')) $body .= '<td></td>';
1398         if ($bean->getAttribute('chip')) $body .= '<td></td>';
1399         if ($bean->getAttribute('chinvoice')) $body .= '<td></td>';
1400         $body .= '</tr>';
1401       }
1402
1403       // Print totals.
1404       $body .= '<tr><td>&nbsp;</td></tr>';
1405       $body .= '<tr style="'.$rowSubtotal.'">';
1406       $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.total').'</td>';
1407       if ($canViewReports || $isClient) $body .= '<td></td>';
1408       if ($bean->getAttribute('chclient')) $body .= '<td></td>';
1409       if ($bean->getAttribute('chproject')) $body .= '<td></td>';
1410       if ($bean->getAttribute('chtask')) $body .= '<td></td>';
1411       if ($bean->getAttribute('chcf_1')) $body .= '<td></td>';
1412       if ($bean->getAttribute('chstart')) $body .= '<td></td>';
1413       if ($bean->getAttribute('chfinish')) $body .= '<td></td>';
1414       if ($bean->getAttribute('chduration')) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$totals['time'].'</td>';
1415       if ($bean->getAttribute('chunits')) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$totals['units'].'</td>';
1416       if ($bean->getAttribute('chnote')) $body .= '<td></td>';
1417       if ($bean->getAttribute('chcost')) {
1418         $body .= '<td nowrap style="'.$cellRightAlignedSubtotal.'">'.htmlspecialchars($user->currency).' ';
1419         $body .= ($canViewReports || $isClient) ? $totals['cost'] : $totals['expenses'];
1420         $body .= '</td>';
1421       }
1422       if ($bean->getAttribute('chpaid')) $body .= '<td></td>';
1423       if ($bean->getAttribute('chip')) $body .= '<td></td>';
1424       if ($bean->getAttribute('chinvoice')) $body .= '<td></td>';
1425       $body .= '</tr>';
1426
1427       $body .= '</table>';
1428     }
1429
1430     // Output footer.
1431     if (!defined('REPORT_FOOTER') || !(REPORT_FOOTER == false))
1432       $body .= '<p style="text-align: center;">'.$i18n->get('form.mail.footer').'</p>';
1433
1434     // Finish creating email body.
1435     $body .= '</body></html>';
1436
1437     return $body;
1438   }
1439
1440   // checkFavReportCondition - checks whether it is okay to send fav report.
1441   static function checkFavReportCondition($options, $condition)
1442   {
1443     $items = ttReportHelper::getFavItems($options);
1444
1445     $condition = str_replace('count', '', $condition);
1446     $count_required = (int) trim(str_replace('>', '', $condition));
1447
1448     if (count($items) > $count_required)
1449       return true; // Condition ok.
1450
1451     return false;
1452   }
1453
1454   // prepareFavReportBody - prepares an email body for a favorite report.
1455   static function prepareFavReportBody($options)
1456   {
1457     global $user;
1458     global $i18n;
1459
1460     // Determine these once as they are used in multiple places in this function.
1461     $canViewReports = $user->can('view_reports');
1462     $isClient = $user->isClient();
1463
1464     $items = ttReportHelper::getFavItems($options);
1465     $group_by = $options['group_by'];
1466     if ($group_by && 'no_grouping' != $group_by)
1467       $subtotals = ttReportHelper::getFavSubtotals($options);
1468     $totals = ttReportHelper::getFavTotals($options);
1469
1470     // Use custom fields plugin if it is enabled.
1471     if ($user->isPluginEnabled('cf'))
1472       $custom_fields = new CustomFields($user->group_id);
1473
1474     // Define some styles to use in email.
1475     $style_title = 'text-align: center; font-size: 15pt; font-family: Arial, Helvetica, sans-serif;';
1476     $tableHeader = 'font-weight: bold; background-color: #a6ccf7; text-align: left;';
1477     $tableHeaderCentered = 'font-weight: bold; background-color: #a6ccf7; text-align: center;';
1478     $rowItem = 'background-color: #ffffff;';
1479     $rowItemAlt = 'background-color: #f5f5f5;';
1480     $rowSubtotal = 'background-color: #e0e0e0;';
1481     $cellLeftAligned = 'text-align: left; vertical-align: top;';
1482     $cellRightAligned = 'text-align: right; vertical-align: top;';
1483     $cellLeftAlignedSubtotal = 'font-weight: bold; text-align: left; vertical-align: top;';
1484     $cellRightAlignedSubtotal = 'font-weight: bold; text-align: right; vertical-align: top;';
1485
1486     // Start creating email body.
1487     $body = '<html>';
1488     $body .= '<head><meta http-equiv="content-type" content="text/html; charset='.CHARSET.'"></head>';
1489     $body .= '<body>';
1490
1491     // Output title.
1492     $body .= '<p style="'.$style_title.'">'.$i18n->get('form.mail.report_subject').': '.$totals['start_date'].' - '.$totals['end_date'].'</p>';
1493
1494     // Output comment.
1495     // if ($comment) $body .= '<p>'.htmlspecialchars($comment).'</p>'; // No comment for fav. reports.
1496
1497     if ($options['show_totals_only']) {
1498       // Totals only report. Output subtotals.
1499
1500       // Determine group_by header.
1501       if ('cf_1' == $group_by)
1502         $group_by_header = htmlspecialchars($custom_fields->fields[0]['label']);
1503       else {
1504         $key = 'label.'.$group_by;
1505         $group_by_header = $i18n->get($key);
1506       }
1507
1508       $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
1509       $body .= '<tr>';
1510       $body .= '<td style="'.$tableHeader.'">'.$group_by_header.'</td>';
1511       if ($options['show_duration'])
1512         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.duration').'</td>';
1513       if ($options['show_work_units'])
1514         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.work_units_short').'</td>';
1515       if ($options['show_cost'])
1516         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.cost').'</td>';
1517       $body .= '</tr>';
1518       foreach($subtotals as $subtotal) {
1519         $body .= '<tr style="'.$rowSubtotal.'">';
1520         $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($subtotal['name'] ? htmlspecialchars($subtotal['name']) : '&nbsp;').'</td>';
1521         if ($options['show_duration']) {
1522           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1523           if ($subtotal['time'] <> '0:00') $body .= $subtotal['time'];
1524           $body .= '</td>';
1525         }
1526         if ($options['show_work_units']) {
1527           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1528           $body .= $subtotal['units'];
1529           $body .= '</td>';
1530         }
1531         if ($options['show_cost']) {
1532           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1533           $body .= ($canViewReports || $isClient) ? $subtotal['cost'] : $subtotal['expenses'];
1534           $body .= '</td>';
1535         }
1536         $body .= '</tr>';
1537       }
1538
1539       // Print totals.
1540       $body .= '<tr><td>&nbsp;</td></tr>';
1541       $body .= '<tr style="'.$rowSubtotal.'">';
1542       $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.total').'</td>';
1543       if ($options['show_duration']) {
1544         $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1545         if ($totals['time'] <> '0:00') $body .= $totals['time'];
1546         $body .= '</td>';
1547       }
1548       if ($options['show_work_units']) {
1549         $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1550         $body .= $totals['units'];
1551         $body .= '</td>';
1552       }
1553       if ($options['show_cost']) {
1554         $body .= '<td nowrap style="'.$cellRightAlignedSubtotal.'">'.htmlspecialchars($user->currency).' ';
1555         $body .= ($canViewReports || $isClient) ? $totals['cost'] : $totals['expenses'];
1556         $body .= '</td>';
1557       }
1558       $body .= '</tr>';
1559
1560       $body .= '</table>';
1561     } else {
1562       // Regular report.
1563
1564       // Print table header.
1565       $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
1566       $body .= '<tr>';
1567       $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.date').'</td>';
1568       if ($canViewReports || $isClient)
1569         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.user').'</td>';
1570       if ($options['show_client'])
1571         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.client').'</td>';
1572       if ($options['show_project'])
1573         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.project').'</td>';
1574       if ($options['show_task'])
1575         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.task').'</td>';
1576       if ($options['show_custom_field_1'])
1577         $body .= '<td style="'.$tableHeader.'">'.htmlspecialchars($custom_fields->fields[0]['label']).'</td>';
1578       if ($options['show_start'])
1579         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.start').'</td>';
1580       if ($options['show_end'])
1581         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.finish').'</td>';
1582       if ($options['show_duration'])
1583         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.duration').'</td>';
1584       if ($options['show_work_units'])
1585         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.work_units_short').'</td>';
1586       if ($options['show_note'])
1587         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.note').'</td>';
1588       if ($options['show_cost'])
1589         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.cost').'</td>';
1590       if ($options['show_paid'])
1591         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.paid').'</td>';
1592       if ($options['show_ip'])
1593         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.ip').'</td>';
1594       if ($options['show_invoice'])
1595         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.invoice').'</td>';
1596       $body .= '</tr>';
1597
1598       // Initialize variables to print subtotals.
1599       if ($items && 'no_grouping' != $group_by) {
1600         $print_subtotals = true;
1601         $first_pass = true;
1602         $prev_grouped_by = '';
1603         $cur_grouped_by = '';
1604       }
1605       // Initialize variables to alternate color of rows for different dates.
1606       $prev_date = '';
1607       $cur_date = '';
1608       $row_style = $rowItem;
1609
1610       // Print report items.
1611       if (is_array($items)) {
1612         foreach ($items as $record) {
1613           $cur_date = $record['date'];
1614           // Print a subtotal row after a block of grouped items.
1615           if ($print_subtotals) {
1616             $cur_grouped_by = $record['grouped_by'];
1617             if ($cur_grouped_by != $prev_grouped_by && !$first_pass) {
1618               $body .= '<tr style="'.$rowSubtotal.'">';
1619               $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.subtotal').'</td>';
1620               $subtotal_name = htmlspecialchars($subtotals[$prev_grouped_by]['name']);
1621               if ($canViewReports || $isClient) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'user' ? $subtotal_name : '').'</td>';
1622               if ($options['show_client']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'client' ? $subtotal_name : '').'</td>';
1623               if ($options['show_project']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'project' ? $subtotal_name : '').'</td>';
1624               if ($options['show_task']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'task' ? $subtotal_name : '').'</td>';
1625               if ($options['show_custom_field_1']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'cf_1' ? $subtotal_name : '').'</td>';
1626               if ($options['show_start']) $body .= '<td></td>';
1627               if ($options['show_end']) $body .= '<td></td>';
1628               if ($options['show_duration']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['time'].'</td>';
1629               if ($options['show_work_units']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['units'].'</td>';
1630               if ($options['show_note']) $body .= '<td></td>';
1631               if ($options['show_cost']) {
1632                 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1633                 $body .= ($canViewReports || $isClient) ? $subtotals[$prev_grouped_by]['cost'] : $subtotals[$prev_grouped_by]['expenses'];
1634                 $body .= '</td>';
1635               }
1636               if ($options['show_paid']) $body .= '<td></td>';
1637               if ($options['show_ip']) $body .= '<td></td>';
1638               if ($options['show_invoice']) $body .= '<td></td>';
1639               $body .= '</tr>';
1640               $body .= '<tr><td>&nbsp;</td></tr>';
1641             }
1642             $first_pass = false;
1643           }
1644
1645           // Print a regular row.
1646           if ($cur_date != $prev_date)
1647             $row_style = ($row_style == $rowItem) ? $rowItemAlt : $rowItem;
1648           $body .= '<tr style="'.$row_style.'">';
1649           $body .= '<td style="'.$cellLeftAligned.'">'.$record['date'].'</td>';
1650           if ($canViewReports || $isClient)
1651             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['user']).'</td>';
1652           if ($options['show_client'])
1653             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['client']).'</td>';
1654           if ($options['show_project'])
1655             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['project']).'</td>';
1656           if ($options['show_task'])
1657             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['task']).'</td>';
1658           if ($options['show_custom_field_1'])
1659             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['cf_1']).'</td>';
1660           if ($options['show_start'])
1661             $body .= '<td nowrap style="'.$cellRightAligned.'">'.$record['start'].'</td>';
1662           if ($options['show_end'])
1663             $body .= '<td nowrap style="'.$cellRightAligned.'">'.$record['finish'].'</td>';
1664           if ($options['show_duration'])
1665             $body .= '<td style="'.$cellRightAligned.'">'.$record['duration'].'</td>';
1666           if ($options['show_work_units'])
1667             $body .= '<td style="'.$cellRightAligned.'">'.$record['units'].'</td>';
1668           if ($options['show_note'])
1669             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['note']).'</td>';
1670           if ($options['show_cost'])
1671             $body .= '<td style="'.$cellRightAligned.'">'.$record['cost'].'</td>';
1672           if ($options['show_paid']) {
1673             $body .= '<td style="'.$cellRightAligned.'">';
1674             $body .= $record['paid'] == 1 ? $i18n->get('label.yes') : $i18n->get('label.no');
1675             $body .= '</td>';
1676           }
1677           if ($options['show_ip']) {
1678             $body .= '<td style="'.$cellRightAligned.'">';
1679             $body .= $record['modified'] ? $record['modified_ip'].' '.$record['modified'] : $record['created_ip'].' '.$record['created'];
1680             $body .= '</td>';
1681           }
1682           if ($options['show_invoice'])
1683             $body .= '<td style="'.$cellRightAligned.'">'.htmlspecialchars($record['invoice']).'</td>';
1684           $body .= '</tr>';
1685
1686           $prev_date = $record['date'];
1687           if ($print_subtotals)
1688             $prev_grouped_by = $record['grouped_by'];
1689         }
1690       }
1691
1692       // Print a terminating subtotal.
1693       if ($print_subtotals) {
1694         $body .= '<tr style="'.$rowSubtotal.'">';
1695         $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.subtotal').'</td>';
1696         $subtotal_name = htmlspecialchars($subtotals[$cur_grouped_by]['name']);
1697         if ($canViewReports || $isClient) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'user' ? $subtotal_name : '').'</td>';
1698         if ($options['show_client']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'client' ? $subtotal_name : '').'</td>';
1699         if ($options['show_project']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'project' ? $subtotal_name : '').'</td>';
1700         if ($options['show_task']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'task' ? $subtotal_name : '').'</td>';
1701         if ($options['show_custom_field_1']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'cf_1' ? $subtotal_name : '').'</td>';
1702         if ($options['show_start']) $body .= '<td></td>';
1703         if ($options['show_end']) $body .= '<td></td>';
1704         if ($options['show_duration']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$cur_grouped_by]['time'].'</td>';
1705         if ($options['show_work_units']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$cur_grouped_by]['units'].'</td>';
1706         if ($options['show_note']) $body .= '<td></td>';
1707         if ($options['show_cost']) {
1708           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1709           $body .= ($canViewReports || $isClient) ? $subtotals[$cur_grouped_by]['cost'] : $subtotals[$cur_grouped_by]['expenses'];
1710           $body .= '</td>';
1711         }
1712         if ($options['show_paid']) $body .= '<td></td>';
1713         if ($options['show_ip']) $body .= '<td></td>';
1714         if ($options['show_invoice']) $body .= '<td></td>';
1715         $body .= '</tr>';
1716       }
1717
1718       // Print totals.
1719       $body .= '<tr><td>&nbsp;</td></tr>';
1720       $body .= '<tr style="'.$rowSubtotal.'">';
1721       $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.total').'</td>';
1722       if ($canViewReports || $isClient) $body .= '<td></td>';
1723       if ($options['show_client']) $body .= '<td></td>';
1724       if ($options['show_project']) $body .= '<td></td>';
1725       if ($options['show_task']) $body .= '<td></td>';
1726       if ($options['show_custom_field_1']) $body .= '<td></td>';
1727       if ($options['show_start']) $body .= '<td></td>';
1728       if ($options['show_end']) $body .= '<td></td>';
1729       if ($options['show_duration']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$totals['time'].'</td>';
1730       if ($options['show_work_units']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$totals['units'].'</td>';
1731       if ($options['show_note']) $body .= '<td></td>';
1732       if ($options['show_cost']) {
1733         $body .= '<td nowrap style="'.$cellRightAlignedSubtotal.'">'.htmlspecialchars($user->currency).' ';
1734         $body .= ($canViewReports || $isClient) ? $totals['cost'] : $totals['expenses'];
1735         $body .= '</td>';
1736       }
1737       if ($options['show_paid']) $body .= '<td></td>';
1738       if ($options['show_ip']) $body .= '<td></td>';
1739       if ($options['show_invoice']) $body .= '<td></td>';
1740       $body .= '</tr>';
1741
1742       $body .= '</table>';
1743     }
1744
1745     // Output footer.
1746     if (!defined('REPORT_FOOTER') || !(REPORT_FOOTER == false))
1747       $body .= '<p style="text-align: center;">'.$i18n->get('form.mail.footer').'</p>';
1748
1749     // Finish creating email body.
1750     $body .= '</body></html>';
1751
1752     return $body;
1753   }
1754
1755   // sendFavReport - sends a favorite report to a specified email, called from cron.php
1756   static function sendFavReport($options, $subject, $email, $cc) {
1757     // We are called from cron.php, we have no $bean in session.
1758     // cron.php sets global $user and $i18n objects to match our favorite report user.
1759     global $user;
1760     global $i18n;
1761
1762     // Prepare report body.
1763     $body = ttReportHelper::prepareFavReportBody($options);
1764
1765     import('mail.Mailer');
1766     $mailer = new Mailer();
1767     $mailer->setCharSet(CHARSET);
1768     $mailer->setContentType('text/html');
1769     $mailer->setSender(SENDER);
1770     if (!empty($cc))
1771       $mailer->setReceiverCC($cc);
1772     if (!empty($user->bcc_email))
1773       $mailer->setReceiverBCC($user->bcc_email);
1774     $mailer->setReceiver($email);
1775     $mailer->setMailMode(MAIL_MODE);
1776     if (empty($subject)) $subject = $options['name'];
1777     if (!$mailer->send($subject, $body))
1778       return false;
1779
1780     return true;
1781   }
1782
1783   // getReportOptions - returns an array of report options constructed from session bean.
1784   //
1785   // Note: similarly to ttFavReportHelper::getReportOptions, this function is a part of
1786   // refactoring to simplify maintenance of report generating functions, as we currently
1787   // have 2 sets: normal reporting (from bean), and fav report emailing (from db fields).
1788   // Using options obtained from either db or bean shall allow us to use only one set of functions.
1789   static function getReportOptions($bean) {
1790     global $user;
1791
1792     // Prepare an array of report options.
1793     $options = array();
1794
1795     // Construct one by one.
1796     $options['name'] = null; // No name required.
1797     $options['user_id'] = $user->id; // Not sure if we need user_id here. Fav reports use it to recycle $user object in cron.php.
1798     $options['client_id'] = $bean->getAttribute('client');
1799     $options['cf_1_option_id'] = $bean->getAttribute('option');
1800     $options['project_id'] = $bean->getAttribute('project');
1801     $options['task_id'] = $bean->getAttribute('task');
1802     $options['billable'] = $bean->getAttribute('include_records');
1803     $options['invoice'] = $bean->getAttribute('invoice');
1804     $options['paid_status'] = $bean->getAttribute('paid_status');
1805     if (is_array($bean->getAttribute('users'))) $options['users'] = join(',', $bean->getAttribute('users'));
1806     $options['period'] = $bean->getAttribute('period');
1807     $options['period_start'] = $bean->getAttribute('start_date');
1808     $options['period_end'] = $bean->getAttribute('end_date');
1809     $options['show_client'] = $bean->getAttribute('chclient');
1810
1811 /*
1812  * TODO: remaining fields to fill in...
1813   `show_invoice` tinyint(4) NOT NULL default 0,          # whether to show invoice column
1814   `show_paid` tinyint(4) NOT NULL default 0,             # whether to show paid column
1815   `show_ip` tinyint(4) NOT NULL default 0,               # whether to show ip column
1816  */
1817     $options['show_project'] = $bean->getAttribute('chproject');
1818     $options['show_start'] = $bean->getAttribute('chstart');
1819 /*
1820   `show_duration` tinyint(4) NOT NULL default 0,         # whether to show duration field
1821   `show_cost` tinyint(4) NOT NULL default 0,             # whether to show cost field
1822  */
1823     $options['show_task'] = $bean->getAttribute('chtask');
1824     $options['show_end'] = $bean->getAttribute('chfinish');
1825 /*
1826   `show_note` tinyint(4) NOT NULL default 0,             # whether to show note column
1827   `show_custom_field_1` tinyint(4) NOT NULL default 0,   # whether to show custom field 1
1828  */
1829     $options['show_custom_field_1'] = $bean->getAttribute('chcf_1');
1830  /*
1831   `show_work_units` tinyint(4) NOT NULL default 0,       # whether to show work units
1832   `show_totals_only` tinyint(4) NOT NULL default 0,      # whether to show totals only
1833  **/
1834     $options['group_by'] = $bean->getAttribute('group_by');
1835 /*
1836  * TODO: remaining fields to fill in...
1837   `status` tinyint(4) default 1,                         # favorite report status
1838   PRIMARY KEY (`id`)
1839 );
1840      */
1841     return $options;
1842   }
1843
1844   // verifyBean is a security function to make sure data in bean makes sense for a group.
1845   static function verifyBean($bean) {
1846     global $user;
1847
1848     // Check users.
1849     $users_in_bean = $bean->getAttribute('users');
1850     if (is_array($users_in_bean)) {
1851       $users_in_group = ttTeamHelper::getUsers();
1852       foreach ($users_in_group as $user_in_group) {
1853         $valid_ids[] = $user_in_group['id'];
1854       }
1855       foreach ($users_in_bean as $user_in_bean) {
1856         if (!in_array($user_in_bean, $valid_ids)) {
1857           return false;
1858         }
1859       }
1860     }
1861
1862     // TODO: add additional checks here. Perhaps do it before saving the bean for consistency.
1863     return true;
1864   }
1865 }