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 // Class ttReportHelper is used for help with reports.
37 class ttReportHelper {
39 // getWhere prepares a WHERE clause for a report query.
40 static function getWhere($options) {
43 $group_id = $user->getGroup();
44 $org_id = $user->org_id;
46 // Prepare dropdown parts.
48 if ($options['client_id'])
49 $dropdown_parts .= ' and l.client_id = '.$options['client_id'];
50 elseif ($user->isClient() && $user->client_id)
51 $dropdown_parts .= ' and l.client_id = '.$user->client_id;
52 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'].')';
53 if ($options['project_id']) $dropdown_parts .= ' and l.project_id = '.$options['project_id'];
54 if ($options['task_id']) $dropdown_parts .= ' and l.task_id = '.$options['task_id'];
55 if ($options['billable']=='1') $dropdown_parts .= ' and l.billable = 1';
56 if ($options['billable']=='2') $dropdown_parts .= ' and l.billable = 0';
57 if ($options['invoice']=='1') $dropdown_parts .= ' and l.invoice_id is not NULL';
58 if ($options['invoice']=='2') $dropdown_parts .= ' and l.invoice_id is NULL';
59 if ($options['paid_status']=='1') $dropdown_parts .= ' and l.paid = 1';
60 if ($options['paid_status']=='2') $dropdown_parts .= ' and l.paid = 0';
62 // Prepare sql query part for user list.
63 $userlist = $options['users'] ? $options['users'] : '-1';
64 if ($user->can('view_reports') || $user->can('view_all_reports') || $user->isClient())
65 $user_list_part = " and l.user_id in ($userlist)";
67 $user_list_part = " and l.user_id = ".$user->getUser();
68 $user_list_part .= " and l.group_id = $group_id and l.org_id = $org_id";
70 // Prepare sql query part for where.
71 $dateFormat = $user->getDateFormat();
72 if ($options['period'])
73 $period = new Period($options['period'], new DateAndTime($dateFormat));
75 $period = new Period();
77 new DateAndTime($dateFormat, $options['period_start']),
78 new DateAndTime($dateFormat, $options['period_end']));
80 $where = " where l.status = 1 and l.date >= '".$period->getStartDate(DB_DATEFORMAT)."' and l.date <= '".$period->getEndDate(DB_DATEFORMAT)."'".
81 " $user_list_part $dropdown_parts";
85 // getExpenseWhere prepares WHERE clause for expenses query in a report.
86 static function getExpenseWhere($options) {
89 $group_id = $user->getGroup();
90 $org_id = $user->org_id;
92 // Prepare dropdown parts.
94 if ($options['client_id'])
95 $dropdown_parts .= ' and ei.client_id = '.$options['client_id'];
96 elseif ($user->isClient() && $user->client_id)
97 $dropdown_parts .= ' and ei.client_id = '.$user->client_id;
98 if ($options['project_id']) $dropdown_parts .= ' and ei.project_id = '.$options['project_id'];
99 if ($options['invoice']=='1') $dropdown_parts .= ' and ei.invoice_id is not NULL';
100 if ($options['invoice']=='2') $dropdown_parts .= ' and ei.invoice_id is NULL';
101 if ($options['paid_status']=='1') $dropdown_parts .= ' and ei.paid = 1';
102 if ($options['paid_status']=='2') $dropdown_parts .= ' and ei.paid = 0';
104 // Prepare sql query part for user list.
105 $userlist = $options['users'] ? $options['users'] : '-1';
106 if ($user->can('view_reports') || $user->can('view_all_reports') || $user->isClient())
107 $user_list_part = " and ei.user_id in ($userlist)";
109 $user_list_part = " and ei.user_id = ".$user->getUser();
110 $user_list_part .= " and ei.group_id = $group_id and ei.org_id = $org_id";
112 // Prepare sql query part for where.
113 $dateFormat = $user->getDateFormat();
114 if ($options['period'])
115 $period = new Period($options['period'], new DateAndTime($dateFormat));
117 $period = new Period();
119 new DateAndTime($dateFormat, $options['period_start']),
120 new DateAndTime($dateFormat, $options['period_end']));
122 $where = " where ei.status = 1 and ei.date >= '".$period->getStartDate(DB_DATEFORMAT)."' and ei.date <= '".$period->getEndDate(DB_DATEFORMAT)."'".
123 " $user_list_part $dropdown_parts";
127 // getItems retrieves all items associated with a report.
128 // It combines tt_log and tt_expense_items in one array for presentation in one table using mysql union all.
129 // Expense items use the "note" field for item name.
130 static function getItems($options) {
132 $mdb2 = getConnection();
134 // Determine these once as they are used in multiple places in this function.
135 $canViewReports = $user->can('view_reports') || $user->can('view_all_reports');
136 $isClient = $user->isClient();
138 $grouping = ttReportHelper::grouping($options);
140 $grouping_by_date = ttReportHelper::groupingBy('date', $options);
141 $grouping_by_client = ttReportHelper::groupingBy('client', $options);
142 $grouping_by_project = ttReportHelper::groupingBy('project', $options);
143 $grouping_by_task = ttReportHelper::groupingBy('task', $options);
144 $grouping_by_user = ttReportHelper::groupingBy('user', $options);
145 $grouping_by_cf_1 = ttReportHelper::groupingBy('cf_1', $options);
147 $convertTo12Hour = ('%I:%M %p' == $user->getTimeFormat()) && ($options['show_start'] || $options['show_end']);
148 $trackingMode = $user->getTrackingMode();
149 $decimalMark = $user->getDecimalMark();
151 // Prepare a query for time items in tt_log table.
152 $fields = array(); // An array of fields for database query.
153 array_push($fields, 'l.id as id');
154 array_push($fields, '1 as type'); // Type 1 is for tt_log entries.
155 array_push($fields, 'l.date as date');
156 if($canViewReports || $isClient)
157 array_push($fields, 'u.name as user');
158 // Add client name if it is selected.
159 if ($options['show_client'] || $grouping_by_client)
160 array_push($fields, 'c.name as client');
161 // Add project name if it is selected.
162 if ($options['show_project'] || $grouping_by_project)
163 array_push($fields, 'p.name as project');
164 // Add task name if it is selected.
165 if ($options['show_task'] || $grouping_by_task)
166 array_push($fields, 't.name as task');
168 $include_cf_1 = $options['show_custom_field_1'] || $grouping_by_cf_1;
170 $custom_fields = new CustomFields();
171 $cf_1_type = $custom_fields->fields[0]['type'];
172 if ($cf_1_type == CustomFields::TYPE_TEXT) {
173 array_push($fields, 'cfl.value as cf_1');
174 } elseif ($cf_1_type == CustomFields::TYPE_DROPDOWN) {
175 array_push($fields, 'cfo.value as cf_1');
179 if ($options['show_start']) {
180 array_push($fields, "l.start as unformatted_start");
181 array_push($fields, "TIME_FORMAT(l.start, '%k:%i') as start");
184 if ($options['show_end'])
185 array_push($fields, "TIME_FORMAT(sec_to_time(time_to_sec(l.start) + time_to_sec(l.duration)), '%k:%i') as finish");
187 if ($options['show_duration'])
188 array_push($fields, "TIME_FORMAT(l.duration, '%k:%i') as duration");
190 if ($options['show_work_units']) {
191 if ($user->getConfigOption('unit_totals_only'))
192 array_push($fields, "null as units");
194 array_push($fields, "if(l.billable = 0 or time_to_sec(l.duration)/60 < $user->first_unit_threshold, 0, ceil(time_to_sec(l.duration)/60/$user->minutes_in_unit)) as units");
197 if ($options['show_note'])
198 array_push($fields, 'l.comment as note');
200 $includeCost = $options['show_cost'];
202 if (MODE_TIME == $trackingMode)
203 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.
205 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.
206 array_push($fields, "null as expense");
209 if ($canViewReports && $options['show_paid'])
210 array_push($fields, 'l.paid as paid');
212 if ($canViewReports && $options['show_ip']) {
213 array_push($fields, 'l.created as created');
214 array_push($fields, 'l.created_ip as created_ip');
215 array_push($fields, 'l.modified as modified');
216 array_push($fields, 'l.modified_ip as modified_ip');
218 // Add invoice name if it is selected.
219 if (($canViewReports || $isClient) && $options['show_invoice'])
220 array_push($fields, 'i.name as invoice');
222 // Prepare sql query part for left joins.
224 if ($options['show_client'] || $grouping_by_client)
225 $left_joins .= " left join tt_clients c on (c.id = l.client_id)";
226 if (($canViewReports || $isClient) && $options['show_invoice'])
227 $left_joins .= " left join tt_invoices i on (i.id = l.invoice_id and i.status = 1)";
228 if ($canViewReports || $isClient || $user->isPluginEnabled('ex'))
229 $left_joins .= " left join tt_users u on (u.id = l.user_id)";
230 if ($options['show_project'] || $grouping_by_project)
231 $left_joins .= " left join tt_projects p on (p.id = l.project_id)";
232 if ($options['show_task'] || $grouping_by_task)
233 $left_joins .= " left join tt_tasks t on (t.id = l.task_id)";
235 if ($cf_1_type == CustomFields::TYPE_TEXT)
236 $left_joins .= " left join tt_custom_field_log cfl on (l.id = cfl.log_id and cfl.status = 1)";
237 elseif ($cf_1_type == CustomFields::TYPE_DROPDOWN) {
238 $left_joins .= " left join tt_custom_field_log cfl on (l.id = cfl.log_id and cfl.status = 1)".
239 " left join tt_custom_field_options cfo on (cfl.option_id = cfo.id)";
242 if ($includeCost && MODE_TIME != $trackingMode)
243 $left_joins .= " left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id)";
245 $where = ttReportHelper::getWhere($options);
247 // Construct sql query for tt_log items.
248 $sql = "select ".join(', ', $fields)." from tt_log l $left_joins $where";
249 // If we don't have expense items (such as when the Expenses plugin is disabled), the above is all sql we need,
250 // with an exception of sorting part, that is added in the end.
252 // However, when we have expenses, we need to do a union with a separate query for expense items from tt_expense_items table.
253 if ($options['show_cost'] && $user->isPluginEnabled('ex')) { // if ex(penses) plugin is enabled
255 $fields = array(); // An array of fields for database query.
256 array_push($fields, 'ei.id');
257 array_push($fields, '2 as type'); // Type 2 is for tt_expense_items entries.
258 array_push($fields, 'ei.date');
259 if($canViewReports || $isClient)
260 array_push($fields, 'u.name as user');
261 // Add client name if it is selected.
262 if ($options['show_client'] || $grouping_by_client)
263 array_push($fields, 'c.name as client');
264 // Add project name if it is selected.
265 if ($options['show_project'] || $grouping_by_project)
266 array_push($fields, 'p.name as project');
267 if ($options['show_task'] || $grouping_by_task)
268 array_push($fields, 'null'); // null for task name. We need to match column count for union.
269 if ($options['show_custom_field_1'] || $grouping_by_cf_1)
270 array_push($fields, 'null'); // null for cf_1.
271 if ($options['show_start']) {
272 array_push($fields, 'null'); // null for unformatted_start.
273 array_push($fields, 'null'); // null for start.
275 if ($options['show_end'])
276 array_push($fields, 'null'); // null for finish.
277 if ($options['show_duration'])
278 array_push($fields, 'null'); // null for duration.
279 if ($options['show_work_units'])
280 array_push($fields, 'null as units'); // null for work units.
281 // Use the note field to print item name.
282 if ($options['show_note'])
283 array_push($fields, 'ei.name as note');
284 array_push($fields, 'ei.cost as cost');
285 array_push($fields, 'ei.cost as expense');
287 if ($canViewReports && $options['show_paid'])
288 array_push($fields, 'ei.paid as paid');
290 if ($canViewReports && $options['show_ip']) {
291 array_push($fields, 'ei.created as created');
292 array_push($fields, 'ei.created_ip as created_ip');
293 array_push($fields, 'ei.modified as modified');
294 array_push($fields, 'ei.modified_ip as modified_ip');
296 // Add invoice name if it is selected.
297 if (($canViewReports || $isClient) && $options['show_invoice'])
298 array_push($fields, 'i.name as invoice');
300 // Prepare sql query part for left joins.
302 if ($canViewReports || $isClient)
303 $left_joins .= " left join tt_users u on (u.id = ei.user_id)";
304 if ($options['show_client'] || $grouping_by_client)
305 $left_joins .= " left join tt_clients c on (c.id = ei.client_id)";
306 if ($options['show_project'] || $grouping_by_project)
307 $left_joins .= " left join tt_projects p on (p.id = ei.project_id)";
308 if (($canViewReports || $isClient) && $options['show_invoice'])
309 $left_joins .= " left join tt_invoices i on (i.id = ei.invoice_id and i.status = 1)";
311 $where = ttReportHelper::getExpenseWhere($options);
313 // Construct sql query for expense items.
314 $sql_for_expense_items = "select ".join(', ', $fields)." from tt_expense_items ei $left_joins $where";
316 // Construct a union.
317 $sql = "($sql) union all ($sql_for_expense_items)";
320 // Determine sort part.
321 $sort_part = ' order by ';
323 $sort_part2 .= ($options['group_by1'] != null && $options['group_by1'] != 'no_grouping') ? ', '.$options['group_by1'] : '';
324 $sort_part2 .= ($options['group_by2'] != null && $options['group_by2'] != 'no_grouping') ? ', '.$options['group_by2'] : '';
325 $sort_part2 .= ($options['group_by3'] != null && $options['group_by3'] != 'no_grouping') ? ', '.$options['group_by3'] : '';
326 if (!$grouping_by_date) $sort_part2 .= ', date';
327 $sort_part .= ltrim($sort_part2, ', '); // Remove leading comma and space.
329 $sort_part .= 'date';
331 if (($canViewReports || $isClient) && $options['users'] && !$grouping_by_user)
332 $sort_part .= ', user, type';
333 if ($options['show_start'])
334 $sort_part .= ', unformatted_start';
335 $sort_part .= ', id';
338 // By now we are ready with sql.
340 // Obtain items for report.
341 $res = $mdb2->query($sql);
342 if (is_a($res, 'PEAR_Error')) die($res->getMessage());
344 while ($val = $res->fetchRow()) {
345 if ($convertTo12Hour) {
346 if($val['start'] != '')
347 $val['start'] = ttTimeHelper::to12HourFormat($val['start']);
348 if($val['finish'] != '')
349 $val['finish'] = ttTimeHelper::to12HourFormat($val['finish']);
351 if (isset($val['cost'])) {
352 if ('.' != $decimalMark)
353 $val['cost'] = str_replace('.', $decimalMark, $val['cost']);
355 if (isset($val['expense'])) {
356 if ('.' != $decimalMark)
357 $val['expense'] = str_replace('.', $decimalMark, $val['expense']);
360 if ($grouping) $val['grouped_by'] = ttReportHelper::makeGroupByKey($options, $val);
361 $val['date'] = ttDateToUserFormat($val['date']);
363 $report_items[] = $val;
366 return $report_items;
369 // putInSession stores tt_log and tt_expense_items ids from a report in user session
370 // as 2 comma-separated lists.
371 static function putInSession($report_items) {
372 unset($_SESSION['report_item_ids']);
373 unset($_SESSION['report_item_expense_ids']);
375 // Iterate through records and build 2 comma-separated lists.
376 foreach($report_items as $item) {
377 if ($item['type'] == 1)
378 $report_item_ids .= ','.$item['id'];
379 else if ($item['type'] == 2)
380 $report_item_expense_ids .= ','.$item['id'];
382 $report_item_ids = trim($report_item_ids, ',');
383 $report_item_expense_ids = trim($report_item_expense_ids, ',');
385 // The lists are reqdy. Put them in session.
386 if ($report_item_ids) $_SESSION['report_item_ids'] = $report_item_ids;
387 if ($report_item_expense_ids) $_SESSION['report_item_expense_ids'] = $report_item_expense_ids;
390 // getFromSession obtains tt_log and tt_expense_items ids stored in user session.
391 static function getFromSession() {
393 $report_item_ids = $_SESSION['report_item_ids'];
394 if ($report_item_ids)
395 $items['report_item_ids'] = explode(',', $report_item_ids);
396 $report_item_expense_ids = $_SESSION['report_item_expense_ids'];
397 if ($report_item_expense_ids)
398 $items['report_item_expense_ids'] = explode(',', $report_item_expense_ids);
402 // getSubtotals calculates report items subtotals when a report is grouped by.
403 // Without expenses, it's a simple select with group by.
404 // With expenses, it becomes a select with group by from a combined set of records obtained with "union all".
405 static function getSubtotals($options) {
408 $mdb2 = getConnection();
410 $concat_part = ttReportHelper::makeConcatPart($options);
411 $join_part = ttReportHelper::makeJoinPart($options);
412 $where = ttReportHelper::getWhere($options);
413 $group_by_part = ttReportHelper::makeGroupByPart($options);
414 if ($options['show_cost']) {
415 if (MODE_TIME == $user->tracking_mode) {
416 if (!ttReportHelper::groupingBy('user', $options))
417 $left_join = 'left join tt_users u on (l.user_id = u.id)';
418 $sql = "select $concat_part, sum(time_to_sec(l.duration)) as time";
419 if ($options['show_work_units']) {
420 if ($user->unit_totals_only)
421 $sql .= ", if (sum(l.billable * time_to_sec(l.duration)/60) < $user->first_unit_threshold, 0, ceil(sum(l.billable * time_to_sec(l.duration)/60/$user->minutes_in_unit))) as units";
423 $sql .= ", sum(if(l.billable = 0 or time_to_sec(l.duration)/60 < $user->first_unit_threshold, 0, ceil(time_to_sec(l.duration)/60/$user->minutes_in_unit))) as units";
425 $sql .= ", sum(cast(l.billable * coalesce(u.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10, 2))) as cost,
426 null as expenses from tt_log l
427 $join_part $left_join $where $group_by_part";
429 // If we are including cost and tracking projects, our query (the same as above) needs to join the tt_user_project_binds table.
430 $sql = "select $concat_part, sum(time_to_sec(l.duration)) as time";
431 if ($options['show_work_units']) {
432 if ($user->unit_totals_only)
433 $sql .= ", if (sum(l.billable * time_to_sec(l.duration)/60) < $user->first_unit_threshold, 0, ceil(sum(l.billable * time_to_sec(l.duration)/60/$user->minutes_in_unit))) as units";
435 $sql .= ", sum(if(l.billable = 0 or time_to_sec(l.duration)/60 < $user->first_unit_threshold, 0, ceil(time_to_sec(l.duration)/60/$user->minutes_in_unit))) as units";
437 $sql .= ", sum(cast(l.billable * coalesce(upb.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10,2))) as cost,
438 null as expenses from tt_log l
440 left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id) $where $group_by_part";
443 // $sql = "select $group_field as group_field, sum(time_to_sec(l.duration)) as time";
444 $sql = "select $concat_part, sum(time_to_sec(l.duration)) as time";
445 if ($options['show_work_units']) {
446 if ($user->unit_totals_only)
447 $sql .= ", if (sum(l.billable * time_to_sec(l.duration)/60) < $user->first_unit_threshold, 0, ceil(sum(l.billable * time_to_sec(l.duration)/60/$user->minutes_in_unit))) as units";
449 $sql .= ", sum(if(l.billable = 0 or time_to_sec(l.duration)/60 < $user->first_unit_threshold, 0, ceil(time_to_sec(l.duration)/60/$user->minutes_in_unit))) as units";
451 $sql .= ", null as expenses from tt_log l
452 $join_part $where $group_by_part";
454 // By now we have sql for time items.
456 // However, when we have expenses, we need to do a union with a separate query for expense items from tt_expense_items table.
457 if ($options['show_cost'] && $user->isPluginEnabled('ex')) { // if ex(penses) plugin is enabled
459 $concat_part = ttReportHelper::makeConcatExpensesPart($options);
460 $join_part = ttReportHelper::makeJoinExpensesPart($options);
461 $where = ttReportHelper::getExpenseWhere($options);
462 $group_by_expenses_part = ttReportHelper::makeGroupByExpensesPart($options);
463 $sql_for_expenses = "select $concat_part, null as time";
464 if ($options['show_work_units']) $sql_for_expenses .= ", null as units";
465 $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";
467 // Create a combined query.
468 $fields = ttReportHelper::makeCombinedSelectPart($options);
469 $combined = "select $fields, sum(time) as time";
470 if ($options['show_work_units']) $combined .= ", sum(units) as units";
471 $combined .= ", sum(cost) as cost, sum(expenses) as expenses from (($sql) union all ($sql_for_expenses)) t group by $fields";
476 $res = $mdb2->query($sql);
477 if (is_a($res, 'PEAR_Error')) die($res->getMessage());
478 while ($val = $res->fetchRow()) {
479 $time = $val['time'] ? sec_to_time_fmt_hm($val['time']) : null;
480 $rowLabel = ttReportHelper::makeGroupByLabel($val['group_field'], $options);
481 if ($options['show_cost']) {
482 if ('.' != $user->decimal_mark) {
483 $val['cost'] = str_replace('.', $user->decimal_mark, $val['cost']);
484 $val['expenses'] = str_replace('.', $user->decimal_mark, $val['expenses']);
486 $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']);
488 $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']);
494 // getTotals calculates total hours and cost for all report items.
495 static function getTotals($options)
499 $mdb2 = getConnection();
501 $where = ttReportHelper::getWhere($options);
504 $time_part = "sum(time_to_sec(l.duration)) as time";
505 if ($options['show_work_units']) {
506 $units_part = $user->unit_totals_only ? ", null as units" : ", sum(if(l.billable = 0 or time_to_sec(l.duration)/60 < $user->first_unit_threshold, 0, ceil(time_to_sec(l.duration)/60/$user->minutes_in_unit))) as units";
508 if ($options['show_cost']) {
509 if (MODE_TIME == $user->tracking_mode)
510 $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";
512 $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";
514 $cost_part = ", null as cost, null as expenses";
516 if ($options['show_cost']) {
517 if (MODE_TIME == $user->tracking_mode) {
518 $left_joins = "left join tt_users u on (l.user_id = u.id)";
520 $left_joins = "left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id)";
523 // Prepare a query for time items.
524 $sql = "select $time_part $units_part $cost_part from tt_log l $left_joins $where";
526 // If we have expenses, query becomes a bit more complex.
527 if ($options['show_cost'] && $user->isPluginEnabled('ex')) {
528 $where = ttReportHelper::getExpenseWhere($options);
529 $sql_for_expenses = "select null as time";
530 if ($options['show_work_units']) $sql_for_expenses .= ", null as units";
531 $sql_for_expenses .= ", sum(cost) as cost, sum(cost) as expenses from tt_expense_items ei $where";
533 // Create a combined query.
534 $combined = "select sum(time) as time";
535 if ($options['show_work_units']) $combined .= ", sum(units) as units";
536 $combined .= ", sum(cost) as cost, sum(expenses) as expenses from (($sql) union all ($sql_for_expenses)) t";
541 $res = $mdb2->query($sql);
542 if (is_a($res, 'PEAR_Error')) die($res->getMessage());
544 $val = $res->fetchRow();
545 $total_time = $val['time'] ? sec_to_time_fmt_hm($val['time']) : null;
546 if ($options['show_cost']) {
547 $total_cost = $val['cost'];
548 if (!$total_cost) $total_cost = '0.00';
549 if ('.' != $user->decimal_mark)
550 $total_cost = str_replace('.', $user->decimal_mark, $total_cost);
551 $total_expenses = $val['expenses'];
552 if (!$total_expenses) $total_expenses = '0.00';
553 if ('.' != $user->decimal_mark)
554 $total_expenses = str_replace('.', $user->decimal_mark, $total_expenses);
557 if ($options['period'])
558 $period = new Period($options['period'], new DateAndTime($user->date_format));
560 $period = new Period();
562 new DateAndTime($user->date_format, $options['period_start']),
563 new DateAndTime($user->date_format, $options['period_end']));
566 $totals['start_date'] = $period->getStartDate();
567 $totals['end_date'] = $period->getEndDate();
568 $totals['time'] = $total_time;
569 $totals['units'] = $val['units'];
570 $totals['cost'] = $total_cost;
571 $totals['expenses'] = $total_expenses;
576 // The assignToInvoice assigns a set of records to a specific invoice.
577 static function assignToInvoice($invoice_id, $time_log_ids, $expense_item_ids) {
579 $mdb2 = getConnection();
581 $group_id = $user->getGroup();
582 $org_id = $user->org_id;
585 $sql = "update tt_log set invoice_id = ".$mdb2->quote($invoice_id).
586 " where id in(".join(', ', $time_log_ids).") and group_id = $group_id and org_id = $org_id";
587 $affected = $mdb2->exec($sql);
588 if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
590 if ($expense_item_ids) {
591 $sql = "update tt_expense_items set invoice_id = ".$mdb2->quote($invoice_id).
592 " where id in(".join(', ', $expense_item_ids).") and group_id = $group_id and org_id = $org_id";
593 $affected = $mdb2->exec($sql);
594 if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
598 // The markPaid marks a set of records as either paid or unpaid.
599 static function markPaid($time_log_ids, $expense_item_ids, $paid = true) {
601 $mdb2 = getConnection();
603 $group_id = $user->getGroup();
604 $org_id = $user->org_id;
606 $paid_val = (int) $paid;
608 $sql = "update tt_log set paid = $paid_val".
609 " where id in(".join(', ', $time_log_ids).") and group_id = $group_id and org_id = $org_id";
610 $affected = $mdb2->exec($sql);
611 if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
613 if ($expense_item_ids) {
614 $sql = "update tt_expense_items set paid = $paid_val".
615 " where id in(".join(', ', $expense_item_ids).") and group_id = $group_id and org_id = $org_id";
616 $affected = $mdb2->exec($sql);
617 if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
621 // prepareReportBody - prepares an email body for report.
622 static function prepareReportBody($options, $comment = null)
627 // Determine these once as they are used in multiple places in this function.
628 $canViewReports = $user->can('view_reports') || $user->can('view_all_reports');
629 $isClient = $user->isClient();
631 $items = ttReportHelper::getItems($options);
632 $grouping = ttReportHelper::grouping($options);
634 $subtotals = ttReportHelper::getSubtotals($options);
635 $totals = ttReportHelper::getTotals($options);
637 // Use custom fields plugin if it is enabled.
638 if ($user->isPluginEnabled('cf'))
639 $custom_fields = new CustomFields();
641 // Define some styles to use in email.
642 $style_title = 'text-align: center; font-size: 15pt; font-family: Arial, Helvetica, sans-serif;';
643 $tableHeader = 'font-weight: bold; background-color: #a6ccf7; text-align: left;';
644 $tableHeaderCentered = 'font-weight: bold; background-color: #a6ccf7; text-align: center;';
645 $rowItem = 'background-color: #ffffff;';
646 $rowItemAlt = 'background-color: #f5f5f5;';
647 $rowSubtotal = 'background-color: #e0e0e0;';
648 $cellLeftAligned = 'text-align: left; vertical-align: top;';
649 $cellRightAligned = 'text-align: right; vertical-align: top;';
650 $cellLeftAlignedSubtotal = 'font-weight: bold; text-align: left; vertical-align: top;';
651 $cellRightAlignedSubtotal = 'font-weight: bold; text-align: right; vertical-align: top;';
653 // Start creating email body.
655 $body .= '<head><meta http-equiv="content-type" content="text/html; charset='.CHARSET.'"></head>';
659 $body .= '<p style="'.$style_title.'">'.$i18n->get('form.mail.report_subject').': '.$totals['start_date'].' - '.$totals['end_date'].'</p>';
662 if ($comment) $body .= '<p>'.htmlspecialchars($comment).'</p>';
664 if ($options['show_totals_only']) {
665 // Totals only report. Output subtotals.
666 $group_by_header = ttReportHelper::makeGroupByHeader($options);
668 $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
670 $body .= '<td style="'.$tableHeader.'">'.$group_by_header.'</td>';
671 if ($options['show_duration'])
672 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.duration').'</td>';
673 if ($options['show_work_units'])
674 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.work_units_short').'</td>';
675 if ($options['show_cost'])
676 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.cost').'</td>';
678 foreach($subtotals as $subtotal) {
679 $body .= '<tr style="'.$rowSubtotal.'">';
680 $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($subtotal['name'] ? htmlspecialchars($subtotal['name']) : ' ').'</td>';
681 if ($options['show_duration']) {
682 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
683 if ($subtotal['time'] <> '0:00') $body .= $subtotal['time'];
686 if ($options['show_work_units']) {
687 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
688 $body .= $subtotal['units'];
691 if ($options['show_cost']) {
692 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
693 $body .= ($canViewReports || $isClient) ? $subtotal['cost'] : $subtotal['expenses'];
700 $body .= '<tr><td> </td></tr>';
701 $body .= '<tr style="'.$rowSubtotal.'">';
702 $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.total').'</td>';
703 if ($options['show_duration']) {
704 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
705 if ($totals['time'] <> '0:00') $body .= $totals['time'];
708 if ($options['show_work_units']) {
709 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
710 $body .= $totals['units'];
713 if ($options['show_cost']) {
714 $body .= '<td nowrap style="'.$cellRightAlignedSubtotal.'">'.htmlspecialchars($user->currency).' ';
715 $body .= ($canViewReports || $isClient) ? $totals['cost'] : $totals['expenses'];
724 // Print table header.
725 $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
727 $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.date').'</td>';
728 if ($canViewReports || $isClient)
729 $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.user').'</td>';
730 if ($options['show_client'])
731 $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.client').'</td>';
732 if ($options['show_project'])
733 $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.project').'</td>';
734 if ($options['show_task'])
735 $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.task').'</td>';
736 if ($options['show_custom_field_1'])
737 $body .= '<td style="'.$tableHeader.'">'.htmlspecialchars($custom_fields->fields[0]['label']).'</td>';
738 if ($options['show_start'])
739 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.start').'</td>';
740 if ($options['show_end'])
741 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.finish').'</td>';
742 if ($options['show_duration'])
743 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.duration').'</td>';
744 if ($options['show_work_units'])
745 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.work_units_short').'</td>';
746 if ($options['show_note'])
747 $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.note').'</td>';
748 if ($options['show_cost'])
749 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.cost').'</td>';
750 if ($options['show_paid'])
751 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.paid').'</td>';
752 if ($options['show_ip'])
753 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.ip').'</td>';
754 if ($options['show_invoice'])
755 $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.invoice').'</td>';
758 // Initialize variables to print subtotals.
759 if ($items && $grouping) {
760 $print_subtotals = true;
762 $prev_grouped_by = '';
763 $cur_grouped_by = '';
765 // Initialize variables to alternate color of rows for different dates.
768 $row_style = $rowItem;
770 // Print report items.
771 if (is_array($items)) {
772 foreach ($items as $record) {
773 $cur_date = $record['date'];
774 // Print a subtotal row after a block of grouped items.
775 if ($print_subtotals) {
776 $cur_grouped_by = $record['grouped_by'];
777 if ($cur_grouped_by != $prev_grouped_by && !$first_pass) {
778 $body .= '<tr style="'.$rowSubtotal.'">';
779 $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.subtotal').'</td>';
780 $subtotal_name = htmlspecialchars($subtotals[$prev_grouped_by]['name']);
781 if ($canViewReports || $isClient) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['user'].'</td>';
782 if ($options['show_client']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['client'].'</td>';
783 if ($options['show_project']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['project'].'</td>';
784 if ($options['show_task']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['task'].'</td>';
785 if ($options['show_custom_field_1']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['cf_1'].'</td>';
786 if ($options['show_start']) $body .= '<td></td>';
787 if ($options['show_end']) $body .= '<td></td>';
788 if ($options['show_duration']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['time'].'</td>';
789 if ($options['show_work_units']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['units'].'</td>';
790 if ($options['show_note']) $body .= '<td></td>';
791 if ($options['show_cost']) {
792 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
793 $body .= ($canViewReports || $isClient) ? $subtotals[$prev_grouped_by]['cost'] : $subtotals[$prev_grouped_by]['expenses'];
796 if ($options['show_paid']) $body .= '<td></td>';
797 if ($options['show_ip']) $body .= '<td></td>';
798 if ($options['show_invoice']) $body .= '<td></td>';
800 $body .= '<tr><td> </td></tr>';
805 // Print a regular row.
806 if ($cur_date != $prev_date)
807 $row_style = ($row_style == $rowItem) ? $rowItemAlt : $rowItem;
808 $body .= '<tr style="'.$row_style.'">';
809 $body .= '<td style="'.$cellLeftAligned.'">'.$record['date'].'</td>';
810 if ($canViewReports || $isClient)
811 $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['user']).'</td>';
812 if ($options['show_client'])
813 $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['client']).'</td>';
814 if ($options['show_project'])
815 $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['project']).'</td>';
816 if ($options['show_task'])
817 $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['task']).'</td>';
818 if ($options['show_custom_field_1'])
819 $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['cf_1']).'</td>';
820 if ($options['show_start'])
821 $body .= '<td nowrap style="'.$cellRightAligned.'">'.$record['start'].'</td>';
822 if ($options['show_end'])
823 $body .= '<td nowrap style="'.$cellRightAligned.'">'.$record['finish'].'</td>';
824 if ($options['show_duration'])
825 $body .= '<td style="'.$cellRightAligned.'">'.$record['duration'].'</td>';
826 if ($options['show_work_units'])
827 $body .= '<td style="'.$cellRightAligned.'">'.$record['units'].'</td>';
828 if ($options['show_note'])
829 $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['note']).'</td>';
830 if ($options['show_cost'])
831 $body .= '<td style="'.$cellRightAligned.'">'.$record['cost'].'</td>';
832 if ($options['show_paid']) {
833 $body .= '<td style="'.$cellRightAligned.'">';
834 $body .= $record['paid'] == 1 ? $i18n->get('label.yes') : $i18n->get('label.no');
837 if ($options['show_ip']) {
838 $body .= '<td style="'.$cellRightAligned.'">';
839 $body .= $record['modified'] ? $record['modified_ip'].' '.$record['modified'] : $record['created_ip'].' '.$record['created'];
842 if ($options['show_invoice'])
843 $body .= '<td style="'.$cellRightAligned.'">'.htmlspecialchars($record['invoice']).'</td>';
846 $prev_date = $record['date'];
847 if ($print_subtotals)
848 $prev_grouped_by = $record['grouped_by'];
852 // Print a terminating subtotal.
853 if ($print_subtotals) {
854 $body .= '<tr style="'.$rowSubtotal.'">';
855 $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.subtotal').'</td>';
856 $subtotal_name = htmlspecialchars($subtotals[$cur_grouped_by]['name']);
857 if ($canViewReports || $isClient) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['user'].'</td>';
858 if ($options['show_client']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['client'].'</td>';
859 if ($options['show_project']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['project'].'</td>';
860 if ($options['show_task']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['task'].'</td>';
861 if ($options['show_custom_field_1']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['cf_1'].'</td>';
862 if ($options['show_start']) $body .= '<td></td>';
863 if ($options['show_end']) $body .= '<td></td>';
864 if ($options['show_duration']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$cur_grouped_by]['time'].'</td>';
865 if ($options['show_work_units']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$cur_grouped_by]['units'].'</td>';
866 if ($options['show_note']) $body .= '<td></td>';
867 if ($options['show_cost']) {
868 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
869 $body .= ($canViewReports || $isClient) ? $subtotals[$cur_grouped_by]['cost'] : $subtotals[$cur_grouped_by]['expenses'];
872 if ($options['show_paid']) $body .= '<td></td>';
873 if ($options['show_ip']) $body .= '<td></td>';
874 if ($options['show_invoice']) $body .= '<td></td>';
879 $body .= '<tr><td> </td></tr>';
880 $body .= '<tr style="'.$rowSubtotal.'">';
881 $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.total').'</td>';
882 if ($canViewReports || $isClient) $body .= '<td></td>';
883 if ($options['show_client']) $body .= '<td></td>';
884 if ($options['show_project']) $body .= '<td></td>';
885 if ($options['show_task']) $body .= '<td></td>';
886 if ($options['show_custom_field_1']) $body .= '<td></td>';
887 if ($options['show_start']) $body .= '<td></td>';
888 if ($options['show_end']) $body .= '<td></td>';
889 if ($options['show_duration']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$totals['time'].'</td>';
890 if ($options['show_work_units']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$totals['units'].'</td>';
891 if ($options['show_note']) $body .= '<td></td>';
892 if ($options['show_cost']) {
893 $body .= '<td nowrap style="'.$cellRightAlignedSubtotal.'">'.htmlspecialchars($user->currency).' ';
894 $body .= ($canViewReports || $isClient) ? $totals['cost'] : $totals['expenses'];
897 if ($options['show_paid']) $body .= '<td></td>';
898 if ($options['show_ip']) $body .= '<td></td>';
899 if ($options['show_invoice']) $body .= '<td></td>';
906 if (!defined('REPORT_FOOTER') || !(REPORT_FOOTER == false))
907 $body .= '<p style="text-align: center;">'.$i18n->get('form.mail.footer').'</p>';
909 // Finish creating email body.
910 $body .= '</body></html>';
915 // checkFavReportCondition - checks whether it is okay to send fav report.
916 static function checkFavReportCondition($options, $condition)
918 $items = ttReportHelper::getItems($options);
920 $condition = trim(str_replace('count', '', $condition));
922 $greater_or_equal = ttStartsWith($condition, '>=');
923 if ($greater_or_equal) $condition = trim(str_replace('>=', '', $condition));
925 $less_or_equal = ttStartsWith($condition, '<=');
926 if ($less_or_equal) $condition = trim(str_replace('<=', '', $condition));
928 $not_equal = ttStartsWith($condition, '<>');
929 if ($not_equal) $condition = trim(str_replace('<>', '', $condition));
931 $greater = ttStartsWith($condition, '>');
932 if ($greater) $condition = trim(str_replace('>', '', $condition));
934 $less = ttStartsWith($condition, '<');
935 if ($less) $condition = trim(str_replace('<', '', $condition));
937 $equal = ttStartsWith($condition, '=');
938 if ($equal) $condition = trim(str_replace('=', '', $condition));
940 $count_required = (int) $condition;
942 if ($greater && count($items) > $count_required) return true;
943 if ($greater_or_equal && count($items) >= $count_required) return true;
944 if ($less && count($items) < $count_required) return true;
945 if ($less_or_equal && count($items) <= $count_required) return true;
946 if ($equal && count($items) == $count_required) return true;
947 if ($not_equal && count($items) <> $count_required) return true;
952 // sendFavReport - sends a favorite report to a specified email, called from cron.php
953 static function sendFavReport($options, $subject, $email, $cc) {
954 // We are called from cron.php, we have no $bean in session.
955 // cron.php sets global $user and $i18n objects to match our favorite report user.
959 // Prepare report body.
960 $body = ttReportHelper::prepareReportBody($options);
962 import('mail.Mailer');
963 $mailer = new Mailer();
964 $mailer->setCharSet(CHARSET);
965 $mailer->setContentType('text/html');
966 $mailer->setSender(SENDER);
968 $mailer->setReceiverCC($cc);
969 if (!empty($user->bcc_email))
970 $mailer->setReceiverBCC($user->bcc_email);
971 $mailer->setReceiver($email);
972 $mailer->setMailMode(MAIL_MODE);
973 if (empty($subject)) $subject = $options['name'];
974 if (!$mailer->send($subject, $body))
980 // getReportOptions - returns an array of report options constructed from session bean.
982 // Note: similarly to ttFavReportHelper::getReportOptions, this function is a part of
983 // refactoring to simplify maintenance of report generating functions, as we currently
984 // have 2 sets: normal reporting (from bean), and fav report emailing (from db fields).
985 // Using options obtained from either db or bean shall allow us to use only one set of functions.
986 static function getReportOptions($bean) {
989 // Prepare an array of report options.
992 // Construct one by one.
993 $options['name'] = null; // No name required.
994 $options['user_id'] = $user->id; // Not sure if we need user_id here. Fav reports use it to recycle $user object in cron.php.
995 $options['client_id'] = $bean->getAttribute('client');
996 $options['cf_1_option_id'] = $bean->getAttribute('option');
997 $options['project_id'] = $bean->getAttribute('project');
998 $options['task_id'] = $bean->getAttribute('task');
999 $options['billable'] = $bean->getAttribute('include_records');
1000 $options['invoice'] = $bean->getAttribute('invoice');
1001 $options['paid_status'] = $bean->getAttribute('paid_status');
1002 if (is_array($bean->getAttribute('users'))) $options['users'] = join(',', $bean->getAttribute('users'));
1003 $options['period'] = $bean->getAttribute('period');
1004 $options['period_start'] = $bean->getAttribute('start_date');
1005 $options['period_end'] = $bean->getAttribute('end_date');
1006 $options['show_client'] = $bean->getAttribute('chclient');
1007 $options['show_invoice'] = $bean->getAttribute('chinvoice');
1008 $options['show_paid'] = $bean->getAttribute('chpaid');
1009 $options['show_ip'] = $bean->getAttribute('chip');
1010 $options['show_project'] = $bean->getAttribute('chproject');
1011 $options['show_start'] = $bean->getAttribute('chstart');
1012 $options['show_duration'] = $bean->getAttribute('chduration');
1013 $options['show_cost'] = $bean->getAttribute('chcost');
1014 $options['show_task'] = $bean->getAttribute('chtask');
1015 $options['show_end'] = $bean->getAttribute('chfinish');
1016 $options['show_note'] = $bean->getAttribute('chnote');
1017 $options['show_custom_field_1'] = $bean->getAttribute('chcf_1');
1018 $options['show_work_units'] = $bean->getAttribute('chunits');
1019 $options['show_totals_only'] = $bean->getAttribute('chtotalsonly');
1020 $options['group_by1'] = $bean->getAttribute('group_by1');
1021 $options['group_by2'] = $bean->getAttribute('group_by2');
1022 $options['group_by3'] = $bean->getAttribute('group_by3');
1026 // verifyBean is a security function to make sure data in bean makes sense for a group.
1027 static function verifyBean($bean) {
1031 $users_in_bean = $bean->getAttribute('users');
1032 if (is_array($users_in_bean)) {
1033 $users_in_group = ttGroupHelper::getUsers();
1034 foreach ($users_in_group as $user_in_group) {
1035 $valid_ids[] = $user_in_group['id'];
1037 foreach ($users_in_bean as $user_in_bean) {
1038 if (!in_array($user_in_bean, $valid_ids)) {
1044 // TODO: add additional checks here. Perhaps do it before saving the bean for consistency.
1048 // makeGroupByKey builds a combined group by key from group_by1, group_by2 and group_by3 values
1049 // (passed in $options) and a row of data ($row obtained from a db query).
1050 static function makeGroupByKey($options, $row) {
1051 if ($options['group_by1'] != null && $options['group_by1'] != 'no_grouping') {
1052 // We have group_by1.
1053 $group_by1 = $options['group_by1'];
1054 $group_by1_value = $row[$group_by1];
1055 //if ($group_by1 == 'date') $group_by1_value = ttDateToUserFormat($group_by1_value);
1056 if (empty($group_by1_value)) $group_by1_value = 'Null'; // To match what comes out of makeConcatPart.
1057 $group_by_key .= ' - '.$group_by1_value;
1059 if ($options['group_by2'] != null && $options['group_by2'] != 'no_grouping') {
1060 // We have group_by2.
1061 $group_by2 = $options['group_by2'];
1062 $group_by2_value = $row[$group_by2];
1063 //if ($group_by2 == 'date') $group_by2_value = ttDateToUserFormat($group_by2_value);
1064 if (empty($group_by2_value)) $group_by2_value = 'Null'; // To match what comes out of makeConcatPart.
1065 $group_by_key .= ' - '.$group_by2_value;
1067 if ($options['group_by3'] != null && $options['group_by3'] != 'no_grouping') {
1068 // We have group_by3.
1069 $group_by3 = $options['group_by3'];
1070 $group_by3_value = $row[$group_by3];
1071 //if ($group_by3 == 'date') $group_by3_value = ttDateToUserFormat($group_by3_value);
1072 if (empty($group_by3_value)) $group_by3_value = 'Null'; // To match what comes out of makeConcatPart.
1073 $group_by_key .= ' - '.$group_by3_value;
1075 $group_by_key = trim($group_by_key, ' -');
1076 return $group_by_key;
1079 // makeGroupByPart builds a combined group by part for sql query for time items using group_by1,
1080 // group_by2, and group_by3 values passed in $options.
1081 static function makeGroupByPart($options) {
1082 if (!ttReportHelper::grouping($options)) return null;
1084 $group_by1 = $options['group_by1'];
1085 $group_by2 = $options['group_by2'];
1086 $group_by3 = $options['group_by3'];
1088 switch ($group_by1) {
1090 $group_by_parts .= ', l.date';
1093 $group_by_parts .= ', u.name';
1096 $group_by_parts .= ', c.name';
1099 $group_by_parts .= ', p.name';
1102 $group_by_parts .= ', t.name';
1105 $group_by_parts .= ', cfo.value';
1108 switch ($group_by2) {
1110 $group_by_parts .= ', l.date';
1113 $group_by_parts .= ', u.name';
1116 $group_by_parts .= ', c.name';
1119 $group_by_parts .= ', p.name';
1122 $group_by_parts .= ', t.name';
1125 $group_by_parts .= ', cfo.value';
1128 switch ($group_by3) {
1130 $group_by_parts .= ', l.date';
1133 $group_by_parts .= ', u.name';
1136 $group_by_parts .= ', c.name';
1139 $group_by_parts .= ', p.name';
1142 $group_by_parts .= ', t.name';
1145 $group_by_parts .= ', cfo.value';
1148 // Remove garbage from the beginning.
1149 $group_by_parts = ltrim($group_by_parts, ', ');
1150 $group_by_part = "group by $group_by_parts";
1151 return $group_by_part;
1154 // makeGroupByExpensesPart builds a combined group by part for sql query for expense items using
1155 // group_by1, group_by2, and group_by3 values passed in $options.
1156 static function makeGroupByExpensesPart($options) {
1157 $no_grouping = ($options['group_by1'] == null || $options['group_by1'] == 'no_grouping') &&
1158 ($options['group_by2'] == null || $options['group_by2'] == 'no_grouping') &&
1159 ($options['group_by3'] == null || $options['group_by3'] == 'no_grouping');
1160 if ($no_grouping) return null;
1162 $group_by1 = $options['group_by1'];
1163 $group_by2 = $options['group_by2'];
1164 $group_by3 = $options['group_by3'];
1166 switch ($group_by1) {
1168 $group_by_parts .= ', ei.date';
1171 $group_by_parts .= ', u.name';
1174 $group_by_parts .= ', c.name';
1177 $group_by_parts .= ', p.name';
1180 switch ($group_by2) {
1182 $group_by_parts .= ', ei.date';
1185 $group_by_parts .= ', u.name';
1188 $group_by_parts .= ', c.name';
1191 $group_by_parts .= ', p.name';
1194 switch ($group_by3) {
1196 $group_by_parts .= ', ei.date';
1199 $group_by_parts .= ', u.name';
1202 $group_by_parts .= ', c.name';
1205 $group_by_parts .= ', p.name';
1208 // Remove garbage from the beginning.
1209 $group_by_parts = ltrim($group_by_parts, ', ');
1210 if ($group_by_parts)
1211 $group_by_part = "group by $group_by_parts";
1212 return $group_by_part;
1215 // makeConcatPart builds a concatenation part for getSubtotals query (for time items).
1216 static function makeConcatPart($options) {
1217 $group_by1 = $options['group_by1'];
1218 $group_by2 = $options['group_by2'];
1219 $group_by3 = $options['group_by3'];
1221 switch ($group_by1) {
1223 $what_to_concat .= ", ' - ', l.date";
1226 $what_to_concat .= ", ' - ', u.name";
1227 $fields_part .= ', u.name as user';
1230 $what_to_concat .= ", ' - ', coalesce(c.name, 'Null')";
1231 $fields_part .= ', c.name as client';
1234 $what_to_concat .= ", ' - ', coalesce(p.name, 'Null')";
1235 $fields_part .= ', p.name as project';
1238 $what_to_concat .= ", ' - ', coalesce(t.name, 'Null')";
1239 $fields_part .= ', t.name as task';
1242 $what_to_concat .= ", ' - ', coalesce(cfo.value, 'Null')";
1243 $fields_part .= ', cfo.value as cf_1';
1246 switch ($group_by2) {
1248 $what_to_concat .= ", ' - ', l.date";
1251 $what_to_concat .= ", ' - ', u.name";
1252 $fields_part .= ', u.name as user';
1255 $what_to_concat .= ", ' - ', coalesce(c.name, 'Null')";
1256 $fields_part .= ', c.name as client';
1259 $what_to_concat .= ", ' - ', coalesce(p.name, 'Null')";
1260 $fields_part .= ', p.name as project';
1263 $what_to_concat .= ", ' - ', coalesce(t.name, 'Null')";
1264 $fields_part .= ', t.name as task';
1267 $what_to_concat .= ", ' - ', coalesce(cfo.value, 'Null')";
1268 $fields_part .= ', cfo.value as cf_1';
1271 switch ($group_by3) {
1273 $what_to_concat .= ", ' - ', l.date";
1276 $what_to_concat .= ", ' - ', u.name";
1277 $fields_part .= ', u.name as user';
1280 $what_to_concat .= ", ' - ', coalesce(c.name, 'Null')";
1281 $fields_part .= ', c.name as client';
1284 $what_to_concat .= ", ' - ', coalesce(p.name, 'Null')";
1285 $fields_part .= ', p.name as project';
1288 $what_to_concat .= ", ' - ', coalesce(t.name, 'Null')";
1289 $fields_part .= ', t.name as task';
1292 $what_to_concat .= ", ' - ', coalesce(cfo.value, 'Null')";
1293 $fields_part .= ', cfo.value as cf_1';
1296 // Remove garbage from both ends.
1297 $what_to_concat = trim($what_to_concat, "', -");
1298 $concat_part = "concat($what_to_concat) as group_field";
1299 $concat_part = trim($concat_part, ' -');
1300 return "$concat_part $fields_part";
1303 // makeConcatPart builds a concatenation part for getSubtotals query (for expense items).
1304 static function makeConcatExpensesPart($options) {
1305 $group_by1 = $options['group_by1'];
1306 $group_by2 = $options['group_by2'];
1307 $group_by3 = $options['group_by3'];
1309 switch ($group_by1) {
1311 $what_to_concat .= ", ' - ', ei.date";
1314 $what_to_concat .= ", ' - ', u.name";
1315 $fields_part .= ', u.name as user';
1318 $what_to_concat .= ", ' - ', coalesce(c.name, 'Null')";
1319 $fields_part .= ', c.name as client';
1322 $what_to_concat .= ", ' - ', coalesce(p.name, 'Null')";
1323 $fields_part .= ', p.name as project';
1327 $what_to_concat .= ", ' - ', 'Null'";
1328 $fields_part .= ', null as task';
1332 $what_to_concat .= ", ' - ', 'Null'";
1333 $fields_part .= ', null as cf_1';
1336 switch ($group_by2) {
1338 $what_to_concat .= ", ' - ', ei.date";
1341 $what_to_concat .= ", ' - ', u.name";
1342 $fields_part .= ', u.name as user';
1345 $what_to_concat .= ", ' - ', coalesce(c.name, 'Null')";
1346 $fields_part .= ', c.name as client';
1349 $what_to_concat .= ", ' - ', coalesce(p.name, 'Null')";
1350 $fields_part .= ', p.name as project';
1354 $what_to_concat .= ", ' - ', 'Null'";
1355 $fields_part .= ', null as task';
1359 $what_to_concat .= ", ' - ', 'Null'";
1360 $fields_part .= ', null as cf_1';
1363 switch ($group_by3) {
1365 $what_to_concat .= ", ' - ', ei.date";
1368 $what_to_concat .= ", ' - ', u.name";
1369 $fields_part .= ', u.name as user';
1372 $what_to_concat .= ", ' - ', coalesce(c.name, 'Null')";
1373 $fields_part .= ', c.name as client';
1376 $what_to_concat .= ", ' - ', coalesce(p.name, 'Null')";
1377 $fields_part .= ', p.name as project';
1381 $what_to_concat .= ", ' - ', 'Null'";
1382 $fields_part .= ', null as task';
1386 $what_to_concat .= ", ' - ', 'Null'";
1387 $fields_part .= ', null as cf_1';
1390 // Remove garbage from the beginning.
1391 if ($what_to_concat)
1392 $what_to_concat = substr($what_to_concat, 8);
1393 $concat_part = "concat($what_to_concat) as group_field";
1394 return "$concat_part $fields_part";
1397 // makeCombinedSelectPart builds a list of fields for a combined select on a union for getSubtotals.
1398 // This is used when we include expenses.
1399 static function makeCombinedSelectPart($options) {
1400 $group_by1 = $options['group_by1'];
1401 $group_by2 = $options['group_by2'];
1402 $group_by3 = $options['group_by3'];
1404 $fields = "group_field";
1406 switch ($group_by1) {
1408 $fields .= ', user';
1411 $fields_part .= ', client';
1414 $fields .= ', project';
1418 $fields .= ', task';
1422 $fields .= ', cf_1';
1425 switch ($group_by2) {
1427 $fields .= ', user';
1430 $fields_part .= ', client';
1433 $fields .= ', project';
1437 $fields .= ', task';
1441 $fields .= ', cf_1';
1444 switch ($group_by3) {
1446 $fields .= ', user';
1449 $fields_part .= ', client';
1452 $fields .= ', project';
1456 $fields .= ', task';
1460 $fields .= ', cf_1';
1466 // makeJoinPart builds a left join part for getSubtotals query (for time items).
1467 static function makeJoinPart($options) {
1470 if (ttReportHelper::groupingBy('user', $options)) {
1471 $join .= ' left join tt_users u on (l.user_id = u.id)';
1473 if (ttReportHelper::groupingBy('client', $options)) {
1474 $join .= ' left join tt_clients c on (l.client_id = c.id)';
1476 if (ttReportHelper::groupingBy('project', $options)) {
1477 $join .= ' left join tt_projects p on (l.project_id = p.id)';
1479 if (ttReportHelper::groupingBy('task', $options)) {
1480 $join .= ' left join tt_tasks t on (l.task_id = t.id)';
1482 if (ttReportHelper::groupingBy('cf_1', $options)) {
1483 $custom_fields = new CustomFields();
1484 if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_TEXT)
1485 $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)';
1486 elseif ($custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN)
1487 $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)';
1492 // makeJoinExpensesPart builds a left join part for getSubtotals query for expense items.
1493 static function makeJoinExpensesPart($options) {
1494 if (ttReportHelper::groupingBy('user', $options)) {
1495 $join .= ' left join tt_users u on (ei.user_id = u.id)';
1497 if (ttReportHelper::groupingBy('client', $options)) {
1498 $join .= ' left join tt_clients c on (ei.client_id = c.id)';
1500 if (ttReportHelper::groupingBy('project', $options)) {
1501 $join .= ' left join tt_projects p on (ei.project_id = p.id)';
1506 // grouping determines if we are grouping the report by either group_by1,
1507 // group_by2, or group_by3 values passed in $options.
1508 static function grouping($options) {
1509 $grouping = ($options['group_by1'] != null && $options['group_by1'] != 'no_grouping') ||
1510 ($options['group_by2'] != null && $options['group_by2'] != 'no_grouping') ||
1511 ($options['group_by3'] != null && $options['group_by3'] != 'no_grouping');
1515 // groupingBy determines if we are grouping a report by a value of $what
1516 // ('date', 'user', 'project', etc.) by checking group_by1, group_by2,
1517 // and group_by3 values passed in $options.
1518 static function groupingBy($what, $options) {
1519 $grouping = ($options['group_by1'] == $what) || ($options['group_by2'] == $what) || ($options['group_by3'] == $what);
1523 // makeGroupByHeader builds a column header for a totals-only report using group_by1,
1524 // group_by2, and group_by3 values passed in $options.
1525 static function makeGroupByHeader($options) {
1527 global $custom_fields;
1529 $no_grouping = ($options['group_by1'] == null || $options['group_by1'] == 'no_grouping') &&
1530 ($options['group_by2'] == null || $options['group_by2'] == 'no_grouping') &&
1531 ($options['group_by3'] == null || $options['group_by3'] == 'no_grouping');
1532 if ($no_grouping) return null;
1534 if ($options['group_by1'] != null && $options['group_by1'] != 'no_grouping') {
1535 // We have group_by1.
1536 $group_by1 = $options['group_by1'];
1537 if ('cf_1' == $group_by1)
1538 $group_by_header .= ' - '.$custom_fields->fields[0]['label'];
1540 $key = 'label.'.$group_by1;
1541 $group_by_header .= ' - '.$i18n->get($key);
1544 if ($options['group_by2'] != null && $options['group_by2'] != 'no_grouping') {
1545 // We have group_by2.
1546 $group_by2 = $options['group_by2'];
1547 if ('cf_1' == $group_by2)
1548 $group_by_header .= ' - '.$custom_fields->fields[0]['label'];
1550 $key = 'label.'.$group_by2;
1551 $group_by_header .= ' - '.$i18n->get($key);
1554 if ($options['group_by3'] != null && $options['group_by3'] != 'no_grouping') {
1555 // We have group_by3.
1556 $group_by3 = $options['group_by3'];
1557 if ('cf_1' == $group_by3)
1558 $group_by_header .= ' - '.$custom_fields->fields[0]['label'];
1560 $key = 'label.'.$group_by3;
1561 $group_by_header .= ' - '.$i18n->get($key);
1564 $group_by_header = ltrim($group_by_header, ' -');
1565 return $group_by_header;
1568 // makeGroupByXmlTag creates an xml tag for a totals only report using group_by1,
1569 // group_by2, and group_by3 values passed in $options.
1570 static function makeGroupByXmlTag($options) {
1571 if ($options['group_by1'] != null && $options['group_by1'] != 'no_grouping') {
1572 // We have group_by1.
1573 $tag .= '_'.$options['group_by1'];
1575 if ($options['group_by2'] != null && $options['group_by2'] != 'no_grouping') {
1576 // We have group_by2.
1577 $tag .= '_'.$options['group_by2'];
1579 if ($options['group_by3'] != null && $options['group_by3'] != 'no_grouping') {
1580 // We have group_by3.
1581 $tag .= '_'.$options['group_by3'];
1583 $tag = ltrim($tag, '_');
1587 // makeGroupByLabel builds a label for one row in a "Totals only" report of grouped by items.
1588 // It does one thing: if we are grouping by date, the date format is converted for user.
1589 static function makeGroupByLabel($key, $options) {
1590 if (!ttReportHelper::groupingBy('date', $options))
1591 return $key; // No need to format.
1594 if ($user->date_format == DB_DATEFORMAT)
1595 return $key; // No need to format.
1598 if (preg_match('/\d\d\d\d-\d\d-\d\d/', $key, $matches)) {
1599 // Replace the first found match of a date in DB_DATEFORMAT.
1600 // This is not entirely clean but better than nothing for a label in a row.
1601 $userDate = ttDateToUserFormat($matches[0]);
1602 $label = str_replace($matches[0], $userDate, $key);