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.
11 // | There are only two ways to violate the license:
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).
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).
21 // | This license applies to this document only, not any other software
22 // | that it may be combined with.
24 // +----------------------------------------------------------------------+
26 // | https://www.anuko.com/time_tracker/credits.htm
27 // +----------------------------------------------------------------------+
29 import('ttClientHelper');
30 import('DateAndTime');
32 import('ttTimeHelper');
34 require_once(dirname(__FILE__).'/../../plugins/CustomFields.class.php');
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.
44 // Class ttReportHelper is used for help with reports.
45 class ttReportHelper {
47 // getWhere prepares a WHERE clause for a report query.
48 static function getWhere($options) {
51 $group_id = $user->getGroup();
52 $org_id = $user->org_id;
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";
60 // Prepare 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';
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)";
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";
88 // Prepare sql query part for where.
89 $dateFormat = $user->getDateFormat();
90 if ($options['period'])
91 $period = new Period($options['period'], new DateAndTime($dateFormat));
93 $period = new Period();
95 new DateAndTime($dateFormat, $options['period_start']),
96 new DateAndTime($dateFormat, $options['period_end']));
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";
103 // getExpenseWhere prepares WHERE clause for expenses query in a report.
104 static function getExpenseWhere($options) {
107 $group_id = $user->getGroup();
108 $org_id = $user->org_id;
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.
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';
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)";
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";
135 // Prepare sql query part for where.
136 $dateFormat = $user->getDateFormat();
137 if ($options['period'])
138 $period = new Period($options['period'], new DateAndTime($dateFormat));
140 $period = new Period();
142 new DateAndTime($dateFormat, $options['period_start']),
143 new DateAndTime($dateFormat, $options['period_end']));
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";
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) {
155 $mdb2 = getConnection();
157 $group_id = $user->getGroup();
158 $org_id = $user->org_id;
160 // Determine these once as they are used in multiple places in this function.
161 $canViewReports = $user->can('view_reports') || $user->can('view_all_reports');
162 $isClient = $user->isClient();
164 $grouping = ttReportHelper::grouping($options);
166 $grouping_by_date = ttReportHelper::groupingBy('date', $options);
167 $grouping_by_client = ttReportHelper::groupingBy('client', $options);
168 $grouping_by_project = ttReportHelper::groupingBy('project', $options);
169 $grouping_by_task = ttReportHelper::groupingBy('task', $options);
170 $grouping_by_user = ttReportHelper::groupingBy('user', $options);
171 $grouping_by_cf_1 = ttReportHelper::groupingBy('cf_1', $options);
173 $convertTo12Hour = ('%I:%M %p' == $user->getTimeFormat()) && ($options['show_start'] || $options['show_end']);
174 $trackingMode = $user->getTrackingMode();
175 $decimalMark = $user->getDecimalMark();
177 // Prepare a query for time items in tt_log table.
178 $fields = array(); // An array of fields for database query.
179 array_push($fields, 'l.id');
180 array_push($fields, 'l.user_id');
181 array_push($fields, '1 as type'); // Type 1 is for tt_log entries.
182 array_push($fields, 'l.date');
183 if($canViewReports || $isClient)
184 array_push($fields, 'u.name as user');
185 // Add client name if it is selected.
186 if ($options['show_client'] || $grouping_by_client)
187 array_push($fields, 'c.name as client');
188 // Add project name if it is selected.
189 if ($options['show_project'] || $grouping_by_project)
190 array_push($fields, 'p.name as project');
191 // Add task name if it is selected.
192 if ($options['show_task'] || $grouping_by_task)
193 array_push($fields, 't.name as task');
195 $include_cf_1 = $options['show_custom_field_1'] || $grouping_by_cf_1;
197 $custom_fields = new CustomFields();
198 $cf_1_type = $custom_fields->fields[0]['type'];
199 if ($cf_1_type == CustomFields::TYPE_TEXT) {
200 array_push($fields, 'cfl.value as cf_1');
201 } elseif ($cf_1_type == CustomFields::TYPE_DROPDOWN) {
202 array_push($fields, 'cfo.value as cf_1');
206 if ($options['show_start']) {
207 array_push($fields, "l.start as unformatted_start");
208 array_push($fields, "TIME_FORMAT(l.start, '%k:%i') as start");
211 if ($options['show_end'])
212 array_push($fields, "TIME_FORMAT(sec_to_time(time_to_sec(l.start) + time_to_sec(l.duration)), '%k:%i') as finish");
214 if ($options['show_duration'])
215 array_push($fields, "TIME_FORMAT(l.duration, '%k:%i') as duration");
217 if ($options['show_work_units']) {
218 if ($user->getConfigOption('unit_totals_only'))
219 array_push($fields, "null as units");
221 $firstUnitThreshold = $user->getConfigInt('1st_unit_threshold', 0);
222 $minutesInUnit = $user->getConfigInt('minutes_in_unit', 15);
223 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");
227 if ($options['show_note'])
228 array_push($fields, 'l.comment as note');
230 $includeCost = $options['show_cost'];
232 if (MODE_TIME == $trackingMode)
233 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.
235 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.
236 array_push($fields, "null as expense");
239 if ($options['show_approved'])
240 array_push($fields, 'l.approved');
242 if ($canViewReports && $options['show_paid'])
243 array_push($fields, 'l.paid');
245 if ($canViewReports && $options['show_ip']) {
246 array_push($fields, 'l.created');
247 array_push($fields, 'l.created_ip');
248 array_push($fields, 'l.modified');
249 array_push($fields, 'l.modified_ip');
251 // Add invoice name if it is selected.
252 if (($canViewReports || $isClient) && $options['show_invoice'])
253 array_push($fields, 'i.name as invoice');
254 // Add timesheet name if it is selected.
255 if ($options['show_timesheet'])
256 array_push($fields, 'ts.name as timesheet_name');
258 if ($options['show_files'])
259 array_push($fields, 'if(Sub1.entity_id is null, 0, 1) as has_files');
261 // Prepare sql query part for left joins.
263 if ($options['show_client'] || $grouping_by_client)
264 $left_joins .= " left join tt_clients c on (c.id = l.client_id)";
265 if (($canViewReports || $isClient) && $options['show_invoice'])
266 $left_joins .= " left join tt_invoices i on (i.id = l.invoice_id and i.status = 1)";
267 if ($canViewReports || $isClient || $user->isPluginEnabled('ex'))
268 $left_joins .= " left join tt_users u on (u.id = l.user_id)";
269 if ($options['show_project'] || $grouping_by_project)
270 $left_joins .= " left join tt_projects p on (p.id = l.project_id)";
271 if ($options['show_task'] || $grouping_by_task)
272 $left_joins .= " left join tt_tasks t on (t.id = l.task_id)";
274 if ($cf_1_type == CustomFields::TYPE_TEXT)
275 $left_joins .= " left join tt_custom_field_log cfl on (l.id = cfl.log_id and cfl.status = 1)";
276 elseif ($cf_1_type == CustomFields::TYPE_DROPDOWN) {
277 $left_joins .= " left join tt_custom_field_log cfl on (l.id = cfl.log_id and cfl.status = 1)".
278 " left join tt_custom_field_options cfo on (cfl.option_id = cfo.id)";
281 if ($includeCost && MODE_TIME != $trackingMode)
282 $left_joins .= " left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id)";
283 if ($options['show_files']) {
284 $left_joins .= " left join (select distinct entity_id from tt_files".
285 " where entity_type = 'time' and group_id = $group_id and org_id = $org_id and status = 1) Sub1".
286 " on (l.id = Sub1.entity_id)";
289 // Prepare sql query part for inner joins.
291 if ($user->isPluginEnabled('ts')) {
292 $timesheet_option = $options['timesheet'];
293 if ($timesheet_option == TIMESHEET_PENDING)
294 $inner_joins .= " inner join tt_timesheets ts on (l.timesheet_id = ts.id and ts.submit_status = 1 and ts.approve_status is null)";
295 else if ($timesheet_option == TIMESHEET_APPROVED)
296 $inner_joins .= " inner join tt_timesheets ts on (l.timesheet_id = ts.id and ts.approve_status = 1)";
297 else if ($timesheet_option == TIMESHEET_NOT_APPROVED)
298 $inner_joins .= " inner join tt_timesheets ts on (l.timesheet_id = ts.id and ts.approve_status = 0)";
299 else if ($options['show_timesheet'])
300 $inner_joins .= " left join tt_timesheets ts on (l.timesheet_id = ts.id)"; // Left join for timesheet nme.
303 $where = ttReportHelper::getWhere($options);
305 // Construct sql query for tt_log items.
306 $sql = "select ".join(', ', $fields)." from tt_log l $left_joins $inner_joins $where";
307 // If we don't have expense items (such as when the Expenses plugin is disabled), the above is all sql we need,
308 // with an exception of sorting part, that is added in the end.
310 // However, when we have expenses, we need to do a union with a separate query for expense items from tt_expense_items table.
311 if ($options['show_cost'] && $user->isPluginEnabled('ex')) { // if ex(penses) plugin is enabled
313 $fields = array(); // An array of fields for database query.
314 array_push($fields, 'ei.id');
315 array_push($fields, 'ei.user_id');
316 array_push($fields, '2 as type'); // Type 2 is for tt_expense_items entries.
317 array_push($fields, 'ei.date');
318 if($canViewReports || $isClient)
319 array_push($fields, 'u.name as user');
320 // Add client name if it is selected.
321 if ($options['show_client'] || $grouping_by_client)
322 array_push($fields, 'c.name as client');
323 // Add project name if it is selected.
324 if ($options['show_project'] || $grouping_by_project)
325 array_push($fields, 'p.name as project');
326 if ($options['show_task'] || $grouping_by_task)
327 array_push($fields, 'null'); // null for task name. We need to match column count for union.
328 if ($options['show_custom_field_1'] || $grouping_by_cf_1)
329 array_push($fields, 'null'); // null for cf_1.
330 if ($options['show_start']) {
331 array_push($fields, 'null'); // null for unformatted_start.
332 array_push($fields, 'null'); // null for start.
334 if ($options['show_end'])
335 array_push($fields, 'null'); // null for finish.
336 if ($options['show_duration'])
337 array_push($fields, 'null'); // null for duration.
338 if ($options['show_work_units'])
339 array_push($fields, 'null as units'); // null for work units.
340 // Use the note field to print item name.
341 if ($options['show_note'])
342 array_push($fields, 'ei.name as note');
343 array_push($fields, 'ei.cost as cost');
344 array_push($fields, 'ei.cost as expense');
346 if ($options['show_approved'])
347 array_push($fields, 'ei.approved');
349 if ($canViewReports && $options['show_paid'])
350 array_push($fields, 'ei.paid');
352 if ($canViewReports && $options['show_ip']) {
353 array_push($fields, 'ei.created');
354 array_push($fields, 'ei.created_ip');
355 array_push($fields, 'ei.modified');
356 array_push($fields, 'ei.modified_ip');
358 // Add invoice name if it is selected.
359 if (($canViewReports || $isClient) && $options['show_invoice'])
360 array_push($fields, 'i.name as invoice');
361 if ($options['show_timesheet'])
362 array_push($fields, 'null as timesheet_name');
364 if ($options['show_files'])
365 array_push($fields, 'if(Sub1.entity_id is null, 0, 1) as has_files');
367 // Prepare sql query part for left joins.
369 if ($canViewReports || $isClient)
370 $left_joins .= " left join tt_users u on (u.id = ei.user_id)";
371 if ($options['show_client'] || $grouping_by_client)
372 $left_joins .= " left join tt_clients c on (c.id = ei.client_id)";
373 if ($options['show_project'] || $grouping_by_project)
374 $left_joins .= " left join tt_projects p on (p.id = ei.project_id)";
375 if (($canViewReports || $isClient) && $options['show_invoice'])
376 $left_joins .= " left join tt_invoices i on (i.id = ei.invoice_id and i.status = 1)";
377 if ($options['show_files']) {
378 $left_joins .= " left join (select distinct entity_id from tt_files".
379 " where entity_type = 'expense' and group_id = $group_id and org_id = $org_id and status = 1) Sub1".
380 " on (ei.id = Sub1.entity_id)";
383 $where = ttReportHelper::getExpenseWhere($options);
385 // Construct sql query for expense items.
386 $sql_for_expense_items = "select ".join(', ', $fields)." from tt_expense_items ei $left_joins $where";
388 // Construct a union.
389 $sql = "($sql) union all ($sql_for_expense_items)";
392 // Determine sort part.
393 $sort_part = ' order by ';
395 $sort_part2 .= ($options['group_by1'] != null && $options['group_by1'] != 'no_grouping') ? ', '.$options['group_by1'] : '';
396 $sort_part2 .= ($options['group_by2'] != null && $options['group_by2'] != 'no_grouping') ? ', '.$options['group_by2'] : '';
397 $sort_part2 .= ($options['group_by3'] != null && $options['group_by3'] != 'no_grouping') ? ', '.$options['group_by3'] : '';
398 if (!$grouping_by_date) $sort_part2 .= ', date';
399 $sort_part .= ltrim($sort_part2, ', '); // Remove leading comma and space.
401 $sort_part .= 'date';
403 if (($canViewReports || $isClient) && $options['users'] && !$grouping_by_user)
404 $sort_part .= ', user, type';
405 if ($options['show_start'])
406 $sort_part .= ', unformatted_start';
407 $sort_part .= ', id';
410 // By now we are ready with sql.
412 // Obtain items for report.
413 $res = $mdb2->query($sql);
414 if (is_a($res, 'PEAR_Error')) die($res->getMessage());
416 while ($val = $res->fetchRow()) {
417 if ($convertTo12Hour) {
418 if($val['start'] != '')
419 $val['start'] = ttTimeHelper::to12HourFormat($val['start']);
420 if($val['finish'] != '')
421 $val['finish'] = ttTimeHelper::to12HourFormat($val['finish']);
423 if (isset($val['cost'])) {
424 if ('.' != $decimalMark)
425 $val['cost'] = str_replace('.', $decimalMark, $val['cost']);
427 if (isset($val['expense'])) {
428 if ('.' != $decimalMark)
429 $val['expense'] = str_replace('.', $decimalMark, $val['expense']);
432 if ($grouping) $val['grouped_by'] = ttReportHelper::makeGroupByKey($options, $val);
433 $val['date'] = ttDateToUserFormat($val['date']);
435 $report_items[] = $val;
438 return $report_items;
441 // putInSession stores tt_log and tt_expense_items ids from a report in user session
442 // as 2 comma-separated lists.
443 static function putInSession($report_items) {
444 unset($_SESSION['report_item_ids']);
445 unset($_SESSION['report_item_expense_ids']);
447 // Iterate through records and build 2 comma-separated lists.
448 foreach($report_items as $item) {
449 if ($item['type'] == 1)
450 $report_item_ids .= ','.$item['id'];
451 else if ($item['type'] == 2)
452 $report_item_expense_ids .= ','.$item['id'];
454 $report_item_ids = trim($report_item_ids, ',');
455 $report_item_expense_ids = trim($report_item_expense_ids, ',');
457 // The lists are reqdy. Put them in session.
458 if ($report_item_ids) $_SESSION['report_item_ids'] = $report_item_ids;
459 if ($report_item_expense_ids) $_SESSION['report_item_expense_ids'] = $report_item_expense_ids;
462 // getFromSession obtains tt_log and tt_expense_items ids stored in user session.
463 static function getFromSession() {
465 $report_item_ids = $_SESSION['report_item_ids'];
466 if ($report_item_ids)
467 $items['report_item_ids'] = explode(',', $report_item_ids);
468 $report_item_expense_ids = $_SESSION['report_item_expense_ids'];
469 if ($report_item_expense_ids)
470 $items['report_item_expense_ids'] = explode(',', $report_item_expense_ids);
474 // getSubtotals calculates report items subtotals when a report is grouped by.
475 // Without expenses, it's a simple select with group by.
476 // With expenses, it becomes a select with group by from a combined set of records obtained with "union all".
477 static function getSubtotals($options) {
479 $mdb2 = getConnection();
481 $concat_part = ttReportHelper::makeConcatPart($options);
482 $work_unit_part = ttReportHelper::makeWorkUnitPart($options);
483 $join_part = ttReportHelper::makeJoinPart($options);
484 $cost_part = ttReportHelper::makeCostPart($options);
485 $where = ttReportHelper::getWhere($options);
486 $group_by_part = ttReportHelper::makeGroupByPart($options);
488 $parts = "$concat_part, sum(time_to_sec(l.duration)) as time, null as expenses".$work_unit_part.$cost_part;
489 $sql = "select $parts from tt_log l $join_part $where $group_by_part";
490 // By now we have sql for time items.
492 // However, when we have expenses, we need to do a union with a separate query for expense items from tt_expense_items table.
493 if ($options['show_cost'] && $user->isPluginEnabled('ex')) { // if ex(penses) plugin is enabled
495 $concat_part = ttReportHelper::makeConcatExpensesPart($options);
496 $join_part = ttReportHelper::makeJoinExpensesPart($options);
497 $where = ttReportHelper::getExpenseWhere($options);
498 $group_by_expenses_part = ttReportHelper::makeGroupByExpensesPart($options);
499 $sql_for_expenses = "select $concat_part, null as time";
500 if ($options['show_work_units']) $sql_for_expenses .= ", null as units";
501 $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";
503 // Create a combined query.
504 $fields = ttReportHelper::makeCombinedSelectPart($options);
505 $combined = "select $fields, sum(time) as time";
506 if ($options['show_work_units']) $combined .= ", sum(units) as units";
507 $combined .= ", sum(cost) as cost, sum(expenses) as expenses from (($sql) union all ($sql_for_expenses)) t group by $fields";
512 $res = $mdb2->query($sql);
513 if (is_a($res, 'PEAR_Error')) die($res->getMessage());
514 while ($val = $res->fetchRow()) {
515 $time = $val['time'] ? sec_to_time_fmt_hm($val['time']) : null;
516 $rowLabel = ttReportHelper::makeGroupByLabel($val['group_field'], $options);
517 if ($options['show_cost']) {
518 $decimalMark = $user->getDecimalMark();
519 if ('.' != $decimalMark) {
520 $val['cost'] = str_replace('.', $decimalMark, $val['cost']);
521 $val['expenses'] = str_replace('.', $decimalMark, $val['expenses']);
523 $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']);
525 $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']);
531 // getTotals calculates total hours and cost for all report items.
532 static function getTotals($options)
535 $mdb2 = getConnection();
537 $trackingMode = $user->getTrackingMode();
538 $decimalMark = $user->getDecimalMark();
539 $where = ttReportHelper::getWhere($options);
542 $time_part = "sum(time_to_sec(l.duration)) as time";
543 if ($options['show_work_units']) {
544 $unitTotalsOnly = $user->getConfigOption('unit_totals_only');
545 $firstUnitThreshold = $user->getConfigInt('1st_unit_threshold', 0);
546 $minutesInUnit = $user->getConfigInt('minutes_in_unit', 15);
547 $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";
549 if ($options['show_cost']) {
550 if (MODE_TIME == $trackingMode)
551 $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";
553 $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";
555 $cost_part = ", null as cost, null as expenses";
557 if ($options['show_cost']) {
558 if (MODE_TIME == $trackingMode) {
559 $left_joins = "left join tt_users u on (l.user_id = u.id)";
561 $left_joins = "left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id)";
564 // Prepare sql query part for inner joins.
566 if ($user->isPluginEnabled('ts') && $options['timesheet']) {
567 $timesheet_option = $options['timesheet'];
568 if ($timesheet_option == TIMESHEET_PENDING)
569 $inner_joins .= " inner join tt_timesheets ts on (l.timesheet_id = ts.id and ts.submit_status = 1 and ts.approve_status is null)";
570 else if ($timesheet_option == TIMESHEET_APPROVED)
571 $inner_joins .= " inner join tt_timesheets ts on (l.timesheet_id = ts.id and ts.approve_status = 1)";
572 else if ($timesheet_option == TIMESHEET_NOT_APPROVED)
573 $inner_joins .= " inner join tt_timesheets ts on (l.timesheet_id = ts.id and ts.approve_status = 0)";
575 // Prepare a query for time items.
576 $sql = "select $time_part $units_part $cost_part from tt_log l $left_joins $inner_joins $where";
578 // If we have expenses, query becomes a bit more complex.
579 if ($options['show_cost'] && $user->isPluginEnabled('ex')) {
580 $where = ttReportHelper::getExpenseWhere($options);
581 $sql_for_expenses = "select null as time";
582 if ($options['show_work_units']) $sql_for_expenses .= ", null as units";
583 $sql_for_expenses .= ", sum(cost) as cost, sum(cost) as expenses from tt_expense_items ei $where";
585 // Create a combined query.
586 $combined = "select sum(time) as time";
587 if ($options['show_work_units']) $combined .= ", sum(units) as units";
588 $combined .= ", sum(cost) as cost, sum(expenses) as expenses from (($sql) union all ($sql_for_expenses)) t";
593 $res = $mdb2->query($sql);
594 if (is_a($res, 'PEAR_Error')) die($res->getMessage());
596 $val = $res->fetchRow();
597 $total_time = $val['time'] ? sec_to_time_fmt_hm($val['time']) : null;
598 if ($options['show_cost']) {
599 $total_cost = $val['cost'];
600 if (!$total_cost) $total_cost = '0.00';
601 if ('.' != $decimalMark)
602 $total_cost = str_replace('.', $decimalMark, $total_cost);
603 $total_expenses = $val['expenses'];
604 if (!$total_expenses) $total_expenses = '0.00';
605 if ('.' != $decimalMark)
606 $total_expenses = str_replace('.', $decimalMark, $total_expenses);
609 $dateFormat = $user->getDateFormat();
610 if ($options['period'])
611 $period = new Period($options['period'], new DateAndTime($dateFormat));
613 $period = new Period();
615 new DateAndTime($dateFormat, $options['period_start']),
616 new DateAndTime($dateFormat, $options['period_end']));
619 $totals['start_date'] = $period->getStartDate();
620 $totals['end_date'] = $period->getEndDate();
621 $totals['time'] = $total_time;
622 $totals['units'] = $val['units'];
623 $totals['cost'] = $total_cost;
624 $totals['expenses'] = $total_expenses;
629 // The assignToInvoice assigns a set of records to a specific invoice.
630 static function assignToInvoice($invoice_id, $time_log_ids, $expense_item_ids) {
632 $mdb2 = getConnection();
634 $group_id = $user->getGroup();
635 $org_id = $user->org_id;
638 $sql = "update tt_log set invoice_id = ".$mdb2->quote($invoice_id).
639 " where id in(".join(', ', $time_log_ids).") and group_id = $group_id and org_id = $org_id";
640 $affected = $mdb2->exec($sql);
641 if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
643 if ($expense_item_ids) {
644 $sql = "update tt_expense_items set invoice_id = ".$mdb2->quote($invoice_id).
645 " where id in(".join(', ', $expense_item_ids).") and group_id = $group_id and org_id = $org_id";
646 $affected = $mdb2->exec($sql);
647 if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
651 // The assignToTimesheet assigns a set of tt_log records to a specific timesheet.
652 static function assignToTimesheet($timesheet_id, $time_log_ids) {
654 $mdb2 = getConnection();
656 $user_id = $user->getUser();
657 $group_id = $user->getGroup();
658 $org_id = $user->org_id;
661 // Use inner join as a protection mechanism not to do anything with "acted upon" timesheets.
662 // Allow oprations only with pending timesheets.
664 // Assigning a timesheet to records.
665 $inner_join = " inner join tt_timesheets ts on (ts.id = $timesheet_id".
666 " and ts.user_id = $user_id and ts.approve_status is null". // Timesheet to assign to is pending.
667 // Part below: existing timesheet either not exists or is also pending.
668 " and (l.timesheet_id is null or (l.timesheet_id = ts.id and ts.approve_status is null)))";
670 $inner_join = " inner join tt_timesheets ts on (ts.id = l.timesheet_id".
671 " and ts.user_id = $user_id and ts.approve_status is null)"; // Do not deassign from acted-upon timesheets.
674 $sql = "update tt_log l $inner_join".
675 " set l.timesheet_id = ".$mdb2->quote($timesheet_id).
676 " 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";
677 $affected = $mdb2->exec($sql);
678 if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
682 // The markApproved marks a set of records as either approved or unapproved.
683 static function markApproved($time_log_ids, $expense_item_ids, $approved = true) {
685 $mdb2 = getConnection();
687 $group_id = $user->getGroup();
688 $org_id = $user->org_id;
690 $approved_val = (int) $approved;
692 $sql = "update tt_log set approved = $approved_val".
693 " where id in(".join(', ', $time_log_ids).") and group_id = $group_id and org_id = $org_id";
694 $affected = $mdb2->exec($sql);
695 if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
697 if ($expense_item_ids) {
698 $sql = "update tt_expense_items set approved = $approved_val".
699 " where id in(".join(', ', $expense_item_ids).") and group_id = $group_id and org_id = $org_id";
700 $affected = $mdb2->exec($sql);
701 if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
705 // The markPaid marks a set of records as either paid or unpaid.
706 static function markPaid($time_log_ids, $expense_item_ids, $paid = true) {
708 $mdb2 = getConnection();
710 $group_id = $user->getGroup();
711 $org_id = $user->org_id;
713 $paid_val = (int) $paid;
715 $sql = "update tt_log set paid = $paid_val".
716 " where id in(".join(', ', $time_log_ids).") and group_id = $group_id and org_id = $org_id";
717 $affected = $mdb2->exec($sql);
718 if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
720 if ($expense_item_ids) {
721 $sql = "update tt_expense_items set paid = $paid_val".
722 " where id in(".join(', ', $expense_item_ids).") and group_id = $group_id and org_id = $org_id";
723 $affected = $mdb2->exec($sql);
724 if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
728 // prepareReportBody - prepares an email body for report.
729 static function prepareReportBody($options, $comment = null)
734 // Determine these once as they are used in multiple places in this function.
735 $canViewReports = $user->can('view_reports') || $user->can('view_all_reports');
736 $isClient = $user->isClient();
738 $items = ttReportHelper::getItems($options);
739 $grouping = ttReportHelper::grouping($options);
741 $subtotals = ttReportHelper::getSubtotals($options);
742 $totals = ttReportHelper::getTotals($options);
744 // Use custom fields plugin if it is enabled.
745 if ($user->isPluginEnabled('cf'))
746 $custom_fields = new CustomFields();
748 // Define some styles to use in email.
749 $style_title = 'text-align: center; font-size: 15pt; font-family: Arial, Helvetica, sans-serif;';
750 $tableHeader = 'font-weight: bold; background-color: #a6ccf7; text-align: left;';
751 $tableHeaderCentered = 'font-weight: bold; background-color: #a6ccf7; text-align: center;';
752 $rowItem = 'background-color: #ffffff;';
753 $rowItemAlt = 'background-color: #f5f5f5;';
754 $rowSubtotal = 'background-color: #e0e0e0;';
755 $cellLeftAligned = 'text-align: left; vertical-align: top;';
756 $cellRightAligned = 'text-align: right; vertical-align: top;';
757 $cellLeftAlignedSubtotal = 'font-weight: bold; text-align: left; vertical-align: top;';
758 $cellRightAlignedSubtotal = 'font-weight: bold; text-align: right; vertical-align: top;';
760 // Determine column span for note field.
762 if ($user->can('view_reports') || $user->can('view_all_reports') || $user->isClient()) $colspan++;
763 if ($options['show_client']) $colspan++;
764 if ($options['show_project']) $colspan++;
765 if ($options['show_task']) $colspan++;
766 if ($options['show_custom_field_1']) $colspan++;
767 if ($options['show_start']) $colspan++;
768 if ($options['show_end']) $colspan++;
769 if ($options['show_duration']) $colspan++;
770 if ($options['show_work_units']) $colspan++;
771 if ($options['show_cost']) $colspan++;
772 if ($options['show_approved']) $colspan++;
773 if ($options['show_paid']) $colspan++;
774 if ($options['show_ip']) $colspan++;
775 if ($options['show_invoice']) $colspan++;
776 if ($options['show_timesheet']) $colspan++;
778 // Start creating email body.
780 $body .= '<head><meta http-equiv="content-type" content="text/html; charset='.CHARSET.'"></head>';
784 $body .= '<p style="'.$style_title.'">'.$i18n->get('form.mail.report_subject').': '.$totals['start_date'].' - '.$totals['end_date'].'</p>';
787 if ($comment) $body .= '<p>'.htmlspecialchars($comment).'</p>';
789 if ($options['show_totals_only']) {
790 // Totals only report. Output subtotals.
791 $group_by_header = ttReportHelper::makeGroupByHeader($options);
793 $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
795 $body .= '<td style="'.$tableHeader.'">'.$group_by_header.'</td>';
796 if ($options['show_duration'])
797 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.duration').'</td>';
798 if ($options['show_work_units'])
799 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.work_units_short').'</td>';
800 if ($options['show_cost'])
801 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.cost').'</td>';
803 foreach($subtotals as $subtotal) {
804 $body .= '<tr style="'.$rowSubtotal.'">';
805 $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($subtotal['name'] ? htmlspecialchars($subtotal['name']) : ' ').'</td>';
806 if ($options['show_duration']) {
807 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
808 if ($subtotal['time'] <> '0:00') $body .= $subtotal['time'];
811 if ($options['show_work_units']) {
812 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
813 $body .= $subtotal['units'];
816 if ($options['show_cost']) {
817 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
818 $body .= ($canViewReports || $isClient) ? $subtotal['cost'] : $subtotal['expenses'];
825 $body .= '<tr><td> </td></tr>';
826 $body .= '<tr style="'.$rowSubtotal.'">';
827 $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.total').'</td>';
828 if ($options['show_duration']) {
829 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
830 if ($totals['time'] <> '0:00') $body .= $totals['time'];
833 if ($options['show_work_units']) {
834 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
835 $body .= $totals['units'];
838 if ($options['show_cost']) {
839 $body .= '<td nowrap style="'.$cellRightAlignedSubtotal.'">'.htmlspecialchars($user->currency).' ';
840 $body .= ($canViewReports || $isClient) ? $totals['cost'] : $totals['expenses'];
849 // Print table header.
850 $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
852 $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.date').'</td>';
853 if ($canViewReports || $isClient)
854 $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.user').'</td>';
855 if ($options['show_client'])
856 $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.client').'</td>';
857 if ($options['show_project'])
858 $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.project').'</td>';
859 if ($options['show_task'])
860 $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.task').'</td>';
861 if ($options['show_custom_field_1'])
862 $body .= '<td style="'.$tableHeader.'">'.htmlspecialchars($custom_fields->fields[0]['label']).'</td>';
863 if ($options['show_start'])
864 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.start').'</td>';
865 if ($options['show_end'])
866 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.finish').'</td>';
867 if ($options['show_duration'])
868 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.duration').'</td>';
869 if ($options['show_work_units'])
870 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.work_units_short').'</td>';
871 if ($options['show_cost'])
872 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.cost').'</td>';
873 if ($options['show_approved'])
874 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.approved').'</td>';
875 if ($options['show_paid'])
876 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.paid').'</td>';
877 if ($options['show_ip'])
878 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.ip').'</td>';
879 if ($options['show_invoice'])
880 $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.invoice').'</td>';
881 if ($options['show_timesheet'])
882 $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.timesheet').'</td>';
885 // Initialize variables to print subtotals.
886 if ($items && $grouping) {
887 $print_subtotals = true;
889 $prev_grouped_by = '';
890 $cur_grouped_by = '';
892 // Initialize variables to alternate color of rows for different dates.
895 $row_style = $rowItem;
897 // Print report items.
898 if (is_array($items)) {
899 foreach ($items as $record) {
900 $cur_date = $record['date'];
901 // Print a subtotal row after a block of grouped items.
902 if ($print_subtotals) {
903 $cur_grouped_by = $record['grouped_by'];
904 if ($cur_grouped_by != $prev_grouped_by && !$first_pass) {
905 $body .= '<tr style="'.$rowSubtotal.'">';
906 $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.subtotal').'</td>';
907 $subtotal_name = htmlspecialchars($subtotals[$prev_grouped_by]['name']);
908 if ($canViewReports || $isClient) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['user'].'</td>';
909 if ($options['show_client']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['client'].'</td>';
910 if ($options['show_project']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['project'].'</td>';
911 if ($options['show_task']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['task'].'</td>';
912 if ($options['show_custom_field_1']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['cf_1'].'</td>';
913 if ($options['show_start']) $body .= '<td></td>';
914 if ($options['show_end']) $body .= '<td></td>';
915 if ($options['show_duration']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['time'].'</td>';
916 if ($options['show_work_units']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['units'].'</td>';
917 if ($options['show_cost']) {
918 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
919 $body .= ($canViewReports || $isClient) ? $subtotals[$prev_grouped_by]['cost'] : $subtotals[$prev_grouped_by]['expenses'];
922 if ($options['show_approved']) $body .= '<td></td>';
923 if ($options['show_paid']) $body .= '<td></td>';
924 if ($options['show_ip']) $body .= '<td></td>';
925 if ($options['show_invoice']) $body .= '<td></td>';
926 if ($options['show_timesheet']) $body .= '<td></td>';
928 $body .= '<tr><td> </td></tr>';
933 // Print a regular row.
934 if ($cur_date != $prev_date)
935 $row_style = ($row_style == $rowItem) ? $rowItemAlt : $rowItem;
936 $body .= '<tr style="'.$row_style.'">';
937 $body .= '<td style="'.$cellLeftAligned.'">'.$record['date'].'</td>';
938 if ($canViewReports || $isClient)
939 $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['user']).'</td>';
940 if ($options['show_client'])
941 $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['client']).'</td>';
942 if ($options['show_project'])
943 $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['project']).'</td>';
944 if ($options['show_task'])
945 $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['task']).'</td>';
946 if ($options['show_custom_field_1'])
947 $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['cf_1']).'</td>';
948 if ($options['show_start'])
949 $body .= '<td nowrap style="'.$cellRightAligned.'">'.$record['start'].'</td>';
950 if ($options['show_end'])
951 $body .= '<td nowrap style="'.$cellRightAligned.'">'.$record['finish'].'</td>';
952 if ($options['show_duration'])
953 $body .= '<td style="'.$cellRightAligned.'">'.$record['duration'].'</td>';
954 if ($options['show_work_units'])
955 $body .= '<td style="'.$cellRightAligned.'">'.$record['units'].'</td>';
956 if ($options['show_cost'])
957 $body .= '<td style="'.$cellRightAligned.'">'.$record['cost'].'</td>';
958 if ($options['show_approved']) {
959 $body .= '<td style="'.$cellRightAligned.'">';
960 $body .= $record['approved'] == 1 ? $i18n->get('label.yes') : $i18n->get('label.no');
963 if ($options['show_paid']) {
964 $body .= '<td style="'.$cellRightAligned.'">';
965 $body .= $record['paid'] == 1 ? $i18n->get('label.yes') : $i18n->get('label.no');
968 if ($options['show_ip']) {
969 $body .= '<td style="'.$cellRightAligned.'">';
970 $body .= $record['modified'] ? $record['modified_ip'].' '.$record['modified'] : $record['created_ip'].' '.$record['created'];
973 if ($options['show_invoice'])
974 $body .= '<td style="'.$cellRightAligned.'">'.htmlspecialchars($record['invoice']).'</td>';
975 if ($options['show_timesheet'])
976 $body .= '<td style="'.$cellRightAligned.'">'.htmlspecialchars($record['timesheet']).'</td>';
978 if ($options['show_note'] && $record['note']) {
979 $body .= '<tr style="'.$row_style.'">';
980 $body .= '<td style="'.$cellRightAligned.'">'.$i18n->get('label.note').':</td>';
981 $body .= '<td colspan="'.$colspan.'">'.$record['note'].'</td>';
984 $prev_date = $record['date'];
985 if ($print_subtotals)
986 $prev_grouped_by = $record['grouped_by'];
990 // Print a terminating subtotal.
991 if ($print_subtotals) {
992 $body .= '<tr style="'.$rowSubtotal.'">';
993 $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.subtotal').'</td>';
994 $subtotal_name = htmlspecialchars($subtotals[$cur_grouped_by]['name']);
995 if ($canViewReports || $isClient) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['user'].'</td>';
996 if ($options['show_client']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['client'].'</td>';
997 if ($options['show_project']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['project'].'</td>';
998 if ($options['show_task']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['task'].'</td>';
999 if ($options['show_custom_field_1']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['cf_1'].'</td>';
1000 if ($options['show_start']) $body .= '<td></td>';
1001 if ($options['show_end']) $body .= '<td></td>';
1002 if ($options['show_duration']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$cur_grouped_by]['time'].'</td>';
1003 if ($options['show_work_units']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$cur_grouped_by]['units'].'</td>';
1004 if ($options['show_cost']) {
1005 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1006 $body .= ($canViewReports || $isClient) ? $subtotals[$cur_grouped_by]['cost'] : $subtotals[$cur_grouped_by]['expenses'];
1009 if ($options['show_approved']) $body .= '<td></td>';
1010 if ($options['show_paid']) $body .= '<td></td>';
1011 if ($options['show_ip']) $body .= '<td></td>';
1012 if ($options['show_invoice']) $body .= '<td></td>';
1013 if ($options['show_timesheet']) $body .= '<td></td>';
1018 $body .= '<tr><td> </td></tr>';
1019 $body .= '<tr style="'.$rowSubtotal.'">';
1020 $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.total').'</td>';
1021 if ($canViewReports || $isClient) $body .= '<td></td>';
1022 if ($options['show_client']) $body .= '<td></td>';
1023 if ($options['show_project']) $body .= '<td></td>';
1024 if ($options['show_task']) $body .= '<td></td>';
1025 if ($options['show_custom_field_1']) $body .= '<td></td>';
1026 if ($options['show_start']) $body .= '<td></td>';
1027 if ($options['show_end']) $body .= '<td></td>';
1028 if ($options['show_duration']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$totals['time'].'</td>';
1029 if ($options['show_work_units']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$totals['units'].'</td>';
1030 if ($options['show_cost']) {
1031 $body .= '<td nowrap style="'.$cellRightAlignedSubtotal.'">'.htmlspecialchars($user->currency).' ';
1032 $body .= ($canViewReports || $isClient) ? $totals['cost'] : $totals['expenses'];
1035 if ($options['show_approved']) $body .= '<td></td>';
1036 if ($options['show_paid']) $body .= '<td></td>';
1037 if ($options['show_ip']) $body .= '<td></td>';
1038 if ($options['show_invoice']) $body .= '<td></td>';
1039 if ($options['show_timesheet']) $body .= '<td></td>';
1042 $body .= '</table>';
1046 if (!defined('REPORT_FOOTER') || !(REPORT_FOOTER == false))
1047 $body .= '<p style="text-align: center;">'.$i18n->get('form.mail.footer').'</p>';
1049 // Finish creating email body.
1050 $body .= '</body></html>';
1055 // checkFavReportCondition - checks whether it is okay to send fav report.
1056 static function checkFavReportCondition($options, $condition)
1058 $items = ttReportHelper::getItems($options);
1060 $condition = trim(str_replace('count', '', $condition));
1062 $greater_or_equal = ttStartsWith($condition, '>=');
1063 if ($greater_or_equal) $condition = trim(str_replace('>=', '', $condition));
1065 $less_or_equal = ttStartsWith($condition, '<=');
1066 if ($less_or_equal) $condition = trim(str_replace('<=', '', $condition));
1068 $not_equal = ttStartsWith($condition, '<>');
1069 if ($not_equal) $condition = trim(str_replace('<>', '', $condition));
1071 $greater = ttStartsWith($condition, '>');
1072 if ($greater) $condition = trim(str_replace('>', '', $condition));
1074 $less = ttStartsWith($condition, '<');
1075 if ($less) $condition = trim(str_replace('<', '', $condition));
1077 $equal = ttStartsWith($condition, '=');
1078 if ($equal) $condition = trim(str_replace('=', '', $condition));
1080 $count_required = (int) $condition;
1082 if ($greater && count($items) > $count_required) return true;
1083 if ($greater_or_equal && count($items) >= $count_required) return true;
1084 if ($less && count($items) < $count_required) return true;
1085 if ($less_or_equal && count($items) <= $count_required) return true;
1086 if ($equal && count($items) == $count_required) return true;
1087 if ($not_equal && count($items) <> $count_required) return true;
1092 // sendFavReport - sends a favorite report to a specified email, called from cron.php
1093 static function sendFavReport($options, $subject, $email, $cc) {
1094 // We are called from cron.php, we have no $bean in session.
1095 // cron.php sets global $user and $i18n objects to match our favorite report user.
1099 // Prepare report body.
1100 $body = ttReportHelper::prepareReportBody($options);
1102 import('mail.Mailer');
1103 $mailer = new Mailer();
1104 $mailer->setCharSet(CHARSET);
1105 $mailer->setContentType('text/html');
1106 $mailer->setSender(SENDER);
1108 $mailer->setReceiverCC($cc);
1109 if (!empty($user->bcc_email))
1110 $mailer->setReceiverBCC($user->bcc_email);
1111 $mailer->setReceiver($email);
1112 $mailer->setMailMode(MAIL_MODE);
1113 if (empty($subject)) $subject = $options['name'];
1114 if (!$mailer->send($subject, $body))
1120 // getReportOptions - returns an array of report options constructed from session bean.
1122 // Note: similarly to ttFavReportHelper::getReportOptions, this function is a part of
1123 // refactoring to simplify maintenance of report generating functions, as we currently
1124 // have 2 sets: normal reporting (from bean), and fav report emailing (from db fields).
1125 // Using options obtained from either db or bean shall allow us to use only one set of functions.
1126 static function getReportOptions($bean) {
1129 // Prepare an array of report options.
1132 // Construct one by one.
1133 $options['name'] = null; // No name required.
1134 $options['user_id'] = $user->id; // Not sure if we need user_id here. Fav reports use it to recycle $user object in cron.php.
1135 $options['client_id'] = $bean->getAttribute('client');
1136 $options['cf_1_option_id'] = $bean->getAttribute('option');
1137 $options['project_id'] = $bean->getAttribute('project');
1138 $options['task_id'] = $bean->getAttribute('task');
1139 $options['billable'] = $bean->getAttribute('include_records');
1140 $options['invoice'] = $bean->getAttribute('invoice');
1141 $options['paid_status'] = $bean->getAttribute('paid_status');
1142 $options['approved'] = $bean->getAttribute('approved');
1143 if ($user->isPluginEnabled('ap') && $user->isClient() && !$user->can('view_client_unapproved'))
1144 $options['approved'] = 1; // Restrict clients to approved records only.
1145 $options['timesheet'] = $bean->getAttribute('timesheet');
1146 if (is_array($bean->getAttribute('users'))) $options['users'] = join(',', $bean->getAttribute('users'));
1147 $options['period'] = $bean->getAttribute('period');
1148 $options['period_start'] = $bean->getAttribute('start_date');
1149 $options['period_end'] = $bean->getAttribute('end_date');
1150 $options['show_client'] = $bean->getAttribute('chclient');
1151 $options['show_invoice'] = $bean->getAttribute('chinvoice');
1152 $options['show_approved'] = $bean->getAttribute('chapproved');
1153 $options['show_paid'] = $bean->getAttribute('chpaid');
1154 $options['show_ip'] = $bean->getAttribute('chip');
1155 $options['show_project'] = $bean->getAttribute('chproject');
1156 $options['show_start'] = $bean->getAttribute('chstart');
1157 $options['show_duration'] = $bean->getAttribute('chduration');
1158 $options['show_cost'] = $bean->getAttribute('chcost');
1159 $options['show_task'] = $bean->getAttribute('chtask');
1160 $options['show_end'] = $bean->getAttribute('chfinish');
1161 $options['show_note'] = $bean->getAttribute('chnote');
1162 $options['show_custom_field_1'] = $bean->getAttribute('chcf_1');
1163 $options['show_work_units'] = $bean->getAttribute('chunits');
1164 $options['show_timesheet'] = $bean->getAttribute('chtimesheet');
1165 $options['show_files'] = $bean->getAttribute('chfiles');
1166 $options['show_totals_only'] = $bean->getAttribute('chtotalsonly');
1167 $options['group_by1'] = $bean->getAttribute('group_by1');
1168 $options['group_by2'] = $bean->getAttribute('group_by2');
1169 $options['group_by3'] = $bean->getAttribute('group_by3');
1173 // verifyBean is a security function to make sure data in bean makes sense for a group.
1174 static function verifyBean($bean) {
1178 $users_in_bean = $bean->getAttribute('users');
1179 if (is_array($users_in_bean)) {
1180 $users_in_group = ttGroupHelper::getUsers();
1181 foreach ($users_in_group as $user_in_group) {
1182 $valid_ids[] = $user_in_group['id'];
1184 foreach ($users_in_bean as $user_in_bean) {
1185 if (!in_array($user_in_bean, $valid_ids)) {
1191 // TODO: add additional checks here. Perhaps do it before saving the bean for consistency.
1195 // makeGroupByKey builds a combined group by key from group_by1, group_by2 and group_by3 values
1196 // (passed in $options) and a row of data ($row obtained from a db query).
1197 static function makeGroupByKey($options, $row) {
1198 if ($options['group_by1'] != null && $options['group_by1'] != 'no_grouping') {
1199 // We have group_by1.
1200 $group_by1 = $options['group_by1'];
1201 $group_by1_value = $row[$group_by1];
1202 //if ($group_by1 == 'date') $group_by1_value = ttDateToUserFormat($group_by1_value);
1203 if (empty($group_by1_value)) $group_by1_value = 'Null'; // To match what comes out of makeConcatPart.
1204 $group_by_key .= ' - '.$group_by1_value;
1206 if ($options['group_by2'] != null && $options['group_by2'] != 'no_grouping') {
1207 // We have group_by2.
1208 $group_by2 = $options['group_by2'];
1209 $group_by2_value = $row[$group_by2];
1210 //if ($group_by2 == 'date') $group_by2_value = ttDateToUserFormat($group_by2_value);
1211 if (empty($group_by2_value)) $group_by2_value = 'Null'; // To match what comes out of makeConcatPart.
1212 $group_by_key .= ' - '.$group_by2_value;
1214 if ($options['group_by3'] != null && $options['group_by3'] != 'no_grouping') {
1215 // We have group_by3.
1216 $group_by3 = $options['group_by3'];
1217 $group_by3_value = $row[$group_by3];
1218 //if ($group_by3 == 'date') $group_by3_value = ttDateToUserFormat($group_by3_value);
1219 if (empty($group_by3_value)) $group_by3_value = 'Null'; // To match what comes out of makeConcatPart.
1220 $group_by_key .= ' - '.$group_by3_value;
1222 $group_by_key = trim($group_by_key, ' -');
1223 return $group_by_key;
1226 // makeGroupByPart builds a combined group by part for sql query for time items using group_by1,
1227 // group_by2, and group_by3 values passed in $options.
1228 static function makeGroupByPart($options) {
1229 if (!ttReportHelper::grouping($options)) return null;
1231 $group_by1 = $options['group_by1'];
1232 $group_by2 = $options['group_by2'];
1233 $group_by3 = $options['group_by3'];
1235 switch ($group_by1) {
1237 $group_by_parts .= ', l.date';
1240 $group_by_parts .= ', u.name';
1243 $group_by_parts .= ', c.name';
1246 $group_by_parts .= ', p.name';
1249 $group_by_parts .= ', t.name';
1252 $group_by_parts .= ', cfo.value';
1255 switch ($group_by2) {
1257 $group_by_parts .= ', l.date';
1260 $group_by_parts .= ', u.name';
1263 $group_by_parts .= ', c.name';
1266 $group_by_parts .= ', p.name';
1269 $group_by_parts .= ', t.name';
1272 $group_by_parts .= ', cfo.value';
1275 switch ($group_by3) {
1277 $group_by_parts .= ', l.date';
1280 $group_by_parts .= ', u.name';
1283 $group_by_parts .= ', c.name';
1286 $group_by_parts .= ', p.name';
1289 $group_by_parts .= ', t.name';
1292 $group_by_parts .= ', cfo.value';
1295 // Remove garbage from the beginning.
1296 $group_by_parts = ltrim($group_by_parts, ', ');
1297 $group_by_part = "group by $group_by_parts";
1298 return $group_by_part;
1301 // makeGroupByExpensesPart builds a combined group by part for sql query for expense items using
1302 // group_by1, group_by2, and group_by3 values passed in $options.
1303 static function makeGroupByExpensesPart($options) {
1304 $no_grouping = ($options['group_by1'] == null || $options['group_by1'] == 'no_grouping') &&
1305 ($options['group_by2'] == null || $options['group_by2'] == 'no_grouping') &&
1306 ($options['group_by3'] == null || $options['group_by3'] == 'no_grouping');
1307 if ($no_grouping) return null;
1309 $group_by1 = $options['group_by1'];
1310 $group_by2 = $options['group_by2'];
1311 $group_by3 = $options['group_by3'];
1313 switch ($group_by1) {
1315 $group_by_parts .= ', ei.date';
1318 $group_by_parts .= ', u.name';
1321 $group_by_parts .= ', c.name';
1324 $group_by_parts .= ', p.name';
1327 switch ($group_by2) {
1329 $group_by_parts .= ', ei.date';
1332 $group_by_parts .= ', u.name';
1335 $group_by_parts .= ', c.name';
1338 $group_by_parts .= ', p.name';
1341 switch ($group_by3) {
1343 $group_by_parts .= ', ei.date';
1346 $group_by_parts .= ', u.name';
1349 $group_by_parts .= ', c.name';
1352 $group_by_parts .= ', p.name';
1355 // Remove garbage from the beginning.
1356 $group_by_parts = ltrim($group_by_parts, ', ');
1357 if ($group_by_parts)
1358 $group_by_part = "group by $group_by_parts";
1359 return $group_by_part;
1362 // makeConcatPart builds a concatenation part for getSubtotals query (for time items).
1363 static function makeConcatPart($options) {
1364 $group_by1 = $options['group_by1'];
1365 $group_by2 = $options['group_by2'];
1366 $group_by3 = $options['group_by3'];
1368 switch ($group_by1) {
1370 $what_to_concat .= ", ' - ', l.date";
1373 $what_to_concat .= ", ' - ', u.name";
1374 $fields_part .= ', u.name as user';
1377 $what_to_concat .= ", ' - ', coalesce(c.name, 'Null')";
1378 $fields_part .= ', c.name as client';
1381 $what_to_concat .= ", ' - ', coalesce(p.name, 'Null')";
1382 $fields_part .= ', p.name as project';
1385 $what_to_concat .= ", ' - ', coalesce(t.name, 'Null')";
1386 $fields_part .= ', t.name as task';
1389 $what_to_concat .= ", ' - ', coalesce(cfo.value, 'Null')";
1390 $fields_part .= ', cfo.value as cf_1';
1393 switch ($group_by2) {
1395 $what_to_concat .= ", ' - ', l.date";
1398 $what_to_concat .= ", ' - ', u.name";
1399 $fields_part .= ', u.name as user';
1402 $what_to_concat .= ", ' - ', coalesce(c.name, 'Null')";
1403 $fields_part .= ', c.name as client';
1406 $what_to_concat .= ", ' - ', coalesce(p.name, 'Null')";
1407 $fields_part .= ', p.name as project';
1410 $what_to_concat .= ", ' - ', coalesce(t.name, 'Null')";
1411 $fields_part .= ', t.name as task';
1414 $what_to_concat .= ", ' - ', coalesce(cfo.value, 'Null')";
1415 $fields_part .= ', cfo.value as cf_1';
1418 switch ($group_by3) {
1420 $what_to_concat .= ", ' - ', l.date";
1423 $what_to_concat .= ", ' - ', u.name";
1424 $fields_part .= ', u.name as user';
1427 $what_to_concat .= ", ' - ', coalesce(c.name, 'Null')";
1428 $fields_part .= ', c.name as client';
1431 $what_to_concat .= ", ' - ', coalesce(p.name, 'Null')";
1432 $fields_part .= ', p.name as project';
1435 $what_to_concat .= ", ' - ', coalesce(t.name, 'Null')";
1436 $fields_part .= ', t.name as task';
1439 $what_to_concat .= ", ' - ', coalesce(cfo.value, 'Null')";
1440 $fields_part .= ', cfo.value as cf_1';
1443 // Remove garbage from both ends.
1444 $what_to_concat = trim($what_to_concat, "', -");
1445 $concat_part = "concat($what_to_concat) as group_field";
1446 $concat_part = trim($concat_part, ' -');
1447 return "$concat_part $fields_part";
1450 // makeConcatPart builds a concatenation part for getSubtotals query (for expense items).
1451 static function makeConcatExpensesPart($options) {
1452 $group_by1 = $options['group_by1'];
1453 $group_by2 = $options['group_by2'];
1454 $group_by3 = $options['group_by3'];
1456 switch ($group_by1) {
1458 $what_to_concat .= ", ' - ', ei.date";
1461 $what_to_concat .= ", ' - ', u.name";
1462 $fields_part .= ', u.name as user';
1465 $what_to_concat .= ", ' - ', coalesce(c.name, 'Null')";
1466 $fields_part .= ', c.name as client';
1469 $what_to_concat .= ", ' - ', coalesce(p.name, 'Null')";
1470 $fields_part .= ', p.name as project';
1474 $what_to_concat .= ", ' - ', 'Null'";
1475 $fields_part .= ', null as task';
1479 $what_to_concat .= ", ' - ', 'Null'";
1480 $fields_part .= ', null as cf_1';
1483 switch ($group_by2) {
1485 $what_to_concat .= ", ' - ', ei.date";
1488 $what_to_concat .= ", ' - ', u.name";
1489 $fields_part .= ', u.name as user';
1492 $what_to_concat .= ", ' - ', coalesce(c.name, 'Null')";
1493 $fields_part .= ', c.name as client';
1496 $what_to_concat .= ", ' - ', coalesce(p.name, 'Null')";
1497 $fields_part .= ', p.name as project';
1501 $what_to_concat .= ", ' - ', 'Null'";
1502 $fields_part .= ', null as task';
1506 $what_to_concat .= ", ' - ', 'Null'";
1507 $fields_part .= ', null as cf_1';
1510 switch ($group_by3) {
1512 $what_to_concat .= ", ' - ', ei.date";
1515 $what_to_concat .= ", ' - ', u.name";
1516 $fields_part .= ', u.name as user';
1519 $what_to_concat .= ", ' - ', coalesce(c.name, 'Null')";
1520 $fields_part .= ', c.name as client';
1523 $what_to_concat .= ", ' - ', coalesce(p.name, 'Null')";
1524 $fields_part .= ', p.name as project';
1528 $what_to_concat .= ", ' - ', 'Null'";
1529 $fields_part .= ', null as task';
1533 $what_to_concat .= ", ' - ', 'Null'";
1534 $fields_part .= ', null as cf_1';
1537 // Remove garbage from the beginning.
1538 if ($what_to_concat)
1539 $what_to_concat = substr($what_to_concat, 8);
1540 $concat_part = "concat($what_to_concat) as group_field";
1541 return "$concat_part $fields_part";
1544 // makeCombinedSelectPart builds a list of fields for a combined select on a union for getSubtotals.
1545 // This is used when we include expenses.
1546 static function makeCombinedSelectPart($options) {
1547 $group_by1 = $options['group_by1'];
1548 $group_by2 = $options['group_by2'];
1549 $group_by3 = $options['group_by3'];
1551 $fields = "group_field";
1553 switch ($group_by1) {
1555 $fields .= ', user';
1558 $fields_part .= ', client';
1561 $fields .= ', project';
1565 $fields .= ', task';
1569 $fields .= ', cf_1';
1572 switch ($group_by2) {
1574 $fields .= ', user';
1577 $fields_part .= ', client';
1580 $fields .= ', project';
1584 $fields .= ', task';
1588 $fields .= ', cf_1';
1591 switch ($group_by3) {
1593 $fields .= ', user';
1596 $fields_part .= ', client';
1599 $fields .= ', project';
1603 $fields .= ', task';
1607 $fields .= ', cf_1';
1613 // makeJoinPart builds a left join part for getSubtotals query (for time items).
1614 static function makeJoinPart($options) {
1617 $trackingMode = $user->getTrackingMode();
1618 if (ttReportHelper::groupingBy('user', $options) || MODE_TIME == $trackingMode) {
1619 $join .= ' left join tt_users u on (l.user_id = u.id)';
1621 if (ttReportHelper::groupingBy('client', $options)) {
1622 $join .= ' left join tt_clients c on (l.client_id = c.id)';
1624 if (ttReportHelper::groupingBy('project', $options)) {
1625 $join .= ' left join tt_projects p on (l.project_id = p.id)';
1627 if (ttReportHelper::groupingBy('task', $options)) {
1628 $join .= ' left join tt_tasks t on (l.task_id = t.id)';
1630 if (ttReportHelper::groupingBy('cf_1', $options)) {
1631 $custom_fields = new CustomFields();
1632 if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_TEXT)
1633 $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)';
1634 elseif ($custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN)
1635 $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)';
1637 if ($options['show_cost'] && $trackingMode != MODE_TIME) {
1638 $join .= ' left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id)';
1640 // Prepare inner joins.
1641 $inner_joins = null;
1642 if ($user->isPluginEnabled('ts') && $options['timesheet']) {
1643 $timesheet_option = $options['timesheet'];
1644 if ($timesheet_option == TIMESHEET_PENDING)
1645 $inner_joins .= " inner join tt_timesheets ts on (l.timesheet_id = ts.id and ts.submit_status = 1 and ts.approve_status is null)";
1646 else if ($timesheet_option == TIMESHEET_APPROVED)
1647 $inner_joins .= " inner join tt_timesheets ts on (l.timesheet_id = ts.id and ts.approve_status = 1)";
1648 else if ($timesheet_option == TIMESHEET_NOT_APPROVED)
1649 $inner_joins .= " inner join tt_timesheets ts on (l.timesheet_id = ts.id and ts.approve_status = 0)";
1651 $join .= $inner_joins;
1655 // makeWorkUnitPart builds an sql part for work units for time items.
1656 static function makeWorkUnitPart($options) {
1659 $workUnits = $options['show_work_units'];
1661 $unitTotalsOnly = $user->getConfigOption('unit_totals_only');
1662 $firstUnitThreshold = $user->getConfigInt('1st_unit_threshold', 0);
1663 $minutesInUnit = $user->getConfigInt('minutes_in_unit', 15);
1664 if ($unitTotalsOnly)
1665 $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";
1667 $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";
1669 return $work_unit_part;
1672 // makeCostPart builds a cost part for time items.
1673 static function makeCostPart($options) {
1676 if ($options['show_cost']) {
1677 if (MODE_TIME == $user->getTrackingMode())
1678 $cost_part = ", sum(cast(l.billable * coalesce(u.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10, 2))) as cost";
1680 $cost_part .= ", sum(cast(l.billable * coalesce(upb.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10,2))) as cost";
1685 // makeJoinExpensesPart builds a left join part for getSubtotals query for expense items.
1686 static function makeJoinExpensesPart($options) {
1689 if (ttReportHelper::groupingBy('user', $options)) {
1690 $join .= ' left join tt_users u on (ei.user_id = u.id)';
1692 if (ttReportHelper::groupingBy('client', $options)) {
1693 $join .= ' left join tt_clients c on (ei.client_id = c.id)';
1695 if (ttReportHelper::groupingBy('project', $options)) {
1696 $join .= ' left join tt_projects p on (ei.project_id = p.id)';
1701 // grouping determines if we are grouping the report by either group_by1,
1702 // group_by2, or group_by3 values passed in $options.
1703 static function grouping($options) {
1704 $grouping = ($options['group_by1'] != null && $options['group_by1'] != 'no_grouping') ||
1705 ($options['group_by2'] != null && $options['group_by2'] != 'no_grouping') ||
1706 ($options['group_by3'] != null && $options['group_by3'] != 'no_grouping');
1710 // groupingBy determines if we are grouping a report by a value of $what
1711 // ('date', 'user', 'project', etc.) by checking group_by1, group_by2,
1712 // and group_by3 values passed in $options.
1713 static function groupingBy($what, $options) {
1714 $grouping = ($options['group_by1'] == $what) || ($options['group_by2'] == $what) || ($options['group_by3'] == $what);
1718 // makeGroupByHeader builds a column header for a totals-only report using group_by1,
1719 // group_by2, and group_by3 values passed in $options.
1720 static function makeGroupByHeader($options) {
1722 global $custom_fields;
1724 $no_grouping = ($options['group_by1'] == null || $options['group_by1'] == 'no_grouping') &&
1725 ($options['group_by2'] == null || $options['group_by2'] == 'no_grouping') &&
1726 ($options['group_by3'] == null || $options['group_by3'] == 'no_grouping');
1727 if ($no_grouping) return null;
1729 if ($options['group_by1'] != null && $options['group_by1'] != 'no_grouping') {
1730 // We have group_by1.
1731 $group_by1 = $options['group_by1'];
1732 if ('cf_1' == $group_by1)
1733 $group_by_header .= ' - '.$custom_fields->fields[0]['label'];
1735 $key = 'label.'.$group_by1;
1736 $group_by_header .= ' - '.$i18n->get($key);
1739 if ($options['group_by2'] != null && $options['group_by2'] != 'no_grouping') {
1740 // We have group_by2.
1741 $group_by2 = $options['group_by2'];
1742 if ('cf_1' == $group_by2)
1743 $group_by_header .= ' - '.$custom_fields->fields[0]['label'];
1745 $key = 'label.'.$group_by2;
1746 $group_by_header .= ' - '.$i18n->get($key);
1749 if ($options['group_by3'] != null && $options['group_by3'] != 'no_grouping') {
1750 // We have group_by3.
1751 $group_by3 = $options['group_by3'];
1752 if ('cf_1' == $group_by3)
1753 $group_by_header .= ' - '.$custom_fields->fields[0]['label'];
1755 $key = 'label.'.$group_by3;
1756 $group_by_header .= ' - '.$i18n->get($key);
1759 $group_by_header = ltrim($group_by_header, ' -');
1760 return $group_by_header;
1763 // makeGroupByXmlTag creates an xml tag for a totals only report using group_by1,
1764 // group_by2, and group_by3 values passed in $options.
1765 static function makeGroupByXmlTag($options) {
1766 if ($options['group_by1'] != null && $options['group_by1'] != 'no_grouping') {
1767 // We have group_by1.
1768 $tag .= '_'.$options['group_by1'];
1770 if ($options['group_by2'] != null && $options['group_by2'] != 'no_grouping') {
1771 // We have group_by2.
1772 $tag .= '_'.$options['group_by2'];
1774 if ($options['group_by3'] != null && $options['group_by3'] != 'no_grouping') {
1775 // We have group_by3.
1776 $tag .= '_'.$options['group_by3'];
1778 $tag = ltrim($tag, '_');
1782 // makeGroupByLabel builds a label for one row in a "Totals only" report of grouped by items.
1783 // It does one thing: if we are grouping by date, the date format is converted for user.
1784 static function makeGroupByLabel($key, $options) {
1785 if (!ttReportHelper::groupingBy('date', $options))
1786 return $key; // No need to format.
1789 if ($user->getDateFormat() == DB_DATEFORMAT)
1790 return $key; // No need to format.
1793 if (preg_match('/\d\d\d\d-\d\d-\d\d/', $key, $matches)) {
1794 // Replace the first found match of a date in DB_DATEFORMAT.
1795 // This is not entirely clean but better than nothing for a label in a row.
1796 $userDate = ttDateToUserFormat($matches[0]);
1797 $label = str_replace($matches[0], $userDate, $key);