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