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