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