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