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