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 // Prepare dropdown parts.
91 if ($options['client_id'])
92 $dropdown_parts .= ' and ei.client_id = '.$options['client_id'];
93 elseif ($user->isClient() && $user->client_id)
94 $dropdown_parts .= ' and ei.client_id = '.$user->client_id;
95 if ($options['project_id']) $dropdown_parts .= ' and ei.project_id = '.$options['project_id'];
96 if ($options['invoice']=='1') $dropdown_parts .= ' and ei.invoice_id is not NULL';
97 if ($options['invoice']=='2') $dropdown_parts .= ' and ei.invoice_id is NULL';
98 if ($options['paid_status']=='1') $dropdown_parts .= ' and ei.paid = 1';
99 if ($options['paid_status']=='2') $dropdown_parts .= ' and ei.paid = 0';
101 // Prepare sql query part for user list.
102 $userlist = $options['users'] ? $options['users'] : '-1';
103 if ($user->can('view_reports') || $user->can('view_all_reports') || $user->isClient())
104 $user_list_part = " and ei.user_id in ($userlist)";
106 $user_list_part = " and ei.user_id = ".$user->id;
107 $user_list_part .= " and ei.group_id = ".$user->getGroup();
109 // Prepare sql query part for where.
110 if ($options['period'])
111 $period = new Period($options['period'], new DateAndTime($user->date_format));
113 $period = new Period();
115 new DateAndTime($user->date_format, $options['period_start']),
116 new DateAndTime($user->date_format, $options['period_end']));
118 $where = " where ei.status = 1 and ei.date >= '".$period->getStartDate(DB_DATEFORMAT)."' and ei.date <= '".$period->getEndDate(DB_DATEFORMAT)."'".
119 " $user_list_part $dropdown_parts";
123 // getItems retrieves all items associated with a report.
124 // It combines tt_log and tt_expense_items in one array for presentation in one table using mysql union all.
125 // Expense items use the "note" field for item name.
126 static function getItems($options) {
128 $mdb2 = getConnection();
130 // Determine these once as they are used in multiple places in this function.
131 $canViewReports = $user->can('view_reports') || $user->can('view_all_reports');
132 $isClient = $user->isClient();
134 $grouping = ttReportHelper::grouping($options);
136 $grouping_by_date = ttReportHelper::groupingBy('date', $options);
137 $grouping_by_client = ttReportHelper::groupingBy('client', $options);
138 $grouping_by_project = ttReportHelper::groupingBy('project', $options);
139 $grouping_by_task = ttReportHelper::groupingBy('task', $options);
140 $grouping_by_user = ttReportHelper::groupingBy('user', $options);
141 $grouping_by_cf_1 = ttReportHelper::groupingBy('cf_1', $options);
143 $convertTo12Hour = ('%I:%M %p' == $user->time_format) && ($options['show_start'] || $options['show_end']);
145 // Prepare a query for time items in tt_log table.
146 $fields = array(); // An array of fields for database query.
147 array_push($fields, 'l.id as id');
148 array_push($fields, '1 as type'); // Type 1 is for tt_log entries.
149 array_push($fields, 'l.date as date');
150 if($canViewReports || $isClient)
151 array_push($fields, 'u.name as user');
152 // Add client name if it is selected.
153 if ($options['show_client'] || $grouping_by_client)
154 array_push($fields, 'c.name as client');
155 // Add project name if it is selected.
156 if ($options['show_project'] || $grouping_by_project)
157 array_push($fields, 'p.name as project');
158 // Add task name if it is selected.
159 if ($options['show_task'] || $grouping_by_task)
160 array_push($fields, 't.name as task');
162 $include_cf_1 = $options['show_custom_field_1'] || $grouping_by_cf_1;
164 $custom_fields = new CustomFields();
165 $cf_1_type = $custom_fields->fields[0]['type'];
166 if ($cf_1_type == CustomFields::TYPE_TEXT) {
167 array_push($fields, 'cfl.value as cf_1');
168 } elseif ($cf_1_type == CustomFields::TYPE_DROPDOWN) {
169 array_push($fields, 'cfo.value as cf_1');
173 if ($options['show_start']) {
174 array_push($fields, "l.start as unformatted_start");
175 array_push($fields, "TIME_FORMAT(l.start, '%k:%i') as start");
178 if ($options['show_end'])
179 array_push($fields, "TIME_FORMAT(sec_to_time(time_to_sec(l.start) + time_to_sec(l.duration)), '%k:%i') as finish");
181 if ($options['show_duration'])
182 array_push($fields, "TIME_FORMAT(l.duration, '%k:%i') as duration");
184 if ($options['show_work_units']) {
185 if ($user->unit_totals_only)
186 array_push($fields, "null as units");
188 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");
191 if ($options['show_note'])
192 array_push($fields, 'l.comment as note');
194 $includeCost = $options['show_cost'];
196 if (MODE_TIME == $user->tracking_mode)
197 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.
199 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.
200 array_push($fields, "null as expense");
203 if ($canViewReports && $options['show_paid'])
204 array_push($fields, 'l.paid as paid');
206 if ($canViewReports && $options['show_ip']) {
207 array_push($fields, 'l.created as created');
208 array_push($fields, 'l.created_ip as created_ip');
209 array_push($fields, 'l.modified as modified');
210 array_push($fields, 'l.modified_ip as modified_ip');
212 // Add invoice name if it is selected.
213 if (($canViewReports || $isClient) && $options['show_invoice'])
214 array_push($fields, 'i.name as invoice');
216 // Prepare sql query part for left joins.
218 if ($options['show_client'] || $grouping_by_client)
219 $left_joins .= " left join tt_clients c on (c.id = l.client_id)";
220 if (($canViewReports || $isClient) && $options['show_invoice'])
221 $left_joins .= " left join tt_invoices i on (i.id = l.invoice_id and i.status = 1)";
222 if ($canViewReports || $isClient || $user->isPluginEnabled('ex'))
223 $left_joins .= " left join tt_users u on (u.id = l.user_id)";
224 if ($options['show_project'] || $grouping_by_project)
225 $left_joins .= " left join tt_projects p on (p.id = l.project_id)";
226 if ($options['show_task'] || $grouping_by_task)
227 $left_joins .= " left join tt_tasks t on (t.id = l.task_id)";
229 if ($cf_1_type == CustomFields::TYPE_TEXT)
230 $left_joins .= " left join tt_custom_field_log cfl on (l.id = cfl.log_id and cfl.status = 1)";
231 elseif ($cf_1_type == CustomFields::TYPE_DROPDOWN) {
232 $left_joins .= " left join tt_custom_field_log cfl on (l.id = cfl.log_id and cfl.status = 1)".
233 " left join tt_custom_field_options cfo on (cfl.option_id = cfo.id)";
236 if ($includeCost && MODE_TIME != $user->tracking_mode)
237 $left_joins .= " left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id)";
239 $where = ttReportHelper::getWhere($options);
241 // Construct sql query for tt_log items.
242 $sql = "select ".join(', ', $fields)." from tt_log l $left_joins $where";
243 // If we don't have expense items (such as when the Expenses plugin is disabled), the above is all sql we need,
244 // with an exception of sorting part, that is added in the end.
246 // However, when we have expenses, we need to do a union with a separate query for expense items from tt_expense_items table.
247 if ($options['show_cost'] && $user->isPluginEnabled('ex')) { // if ex(penses) plugin is enabled
249 $fields = array(); // An array of fields for database query.
250 array_push($fields, 'ei.id');
251 array_push($fields, '2 as type'); // Type 2 is for tt_expense_items entries.
252 array_push($fields, 'ei.date');
253 if($canViewReports || $isClient)
254 array_push($fields, 'u.name as user');
255 // Add client name if it is selected.
256 if ($options['show_client'] || $grouping_by_client)
257 array_push($fields, 'c.name as client');
258 // Add project name if it is selected.
259 if ($options['show_project'] || $grouping_by_project)
260 array_push($fields, 'p.name as project');
261 if ($options['show_task'] || $grouping_by_task)
262 array_push($fields, 'null'); // null for task name. We need to match column count for union.
263 if ($options['show_custom_field_1'] || $grouping_by_cf_1)
264 array_push($fields, 'null'); // null for cf_1.
265 if ($options['show_start']) {
266 array_push($fields, 'null'); // null for unformatted_start.
267 array_push($fields, 'null'); // null for start.
269 if ($options['show_end'])
270 array_push($fields, 'null'); // null for finish.
271 if ($options['show_duration'])
272 array_push($fields, 'null'); // null for duration.
273 if ($options['show_work_units'])
274 array_push($fields, 'null as units'); // null for work units.
275 // Use the note field to print item name.
276 if ($options['show_note'])
277 array_push($fields, 'ei.name as note');
278 array_push($fields, 'ei.cost as cost');
279 array_push($fields, 'ei.cost as expense');
281 if ($canViewReports && $options['show_paid'])
282 array_push($fields, 'ei.paid as paid');
284 if ($canViewReports && $options['show_ip']) {
285 array_push($fields, 'ei.created as created');
286 array_push($fields, 'ei.created_ip as created_ip');
287 array_push($fields, 'ei.modified as modified');
288 array_push($fields, 'ei.modified_ip as modified_ip');
290 // Add invoice name if it is selected.
291 if (($canViewReports || $isClient) && $options['show_invoice'])
292 array_push($fields, 'i.name as invoice');
294 // Prepare sql query part for left joins.
296 if ($canViewReports || $isClient)
297 $left_joins .= " left join tt_users u on (u.id = ei.user_id)";
298 if ($options['show_client'] || $grouping_by_client)
299 $left_joins .= " left join tt_clients c on (c.id = ei.client_id)";
300 if ($options['show_project'] || $grouping_by_project)
301 $left_joins .= " left join tt_projects p on (p.id = ei.project_id)";
302 if (($canViewReports || $isClient) && $options['show_invoice'])
303 $left_joins .= " left join tt_invoices i on (i.id = ei.invoice_id and i.status = 1)";
305 $where = ttReportHelper::getExpenseWhere($options);
307 // Construct sql query for expense items.
308 $sql_for_expense_items = "select ".join(', ', $fields)." from tt_expense_items ei $left_joins $where";
310 // Construct a union.
311 $sql = "($sql) union all ($sql_for_expense_items)";
314 // Determine sort part.
315 $sort_part = ' order by ';
317 $sort_part2 .= ($options['group_by1'] != null && $options['group_by1'] != 'no_grouping') ? ', '.$options['group_by1'] : '';
318 $sort_part2 .= ($options['group_by2'] != null && $options['group_by2'] != 'no_grouping') ? ', '.$options['group_by2'] : '';
319 $sort_part2 .= ($options['group_by3'] != null && $options['group_by3'] != 'no_grouping') ? ', '.$options['group_by3'] : '';
320 if (!$grouping_by_date) $sort_part2 .= ', date';
321 $sort_part .= ltrim($sort_part2, ', '); // Remove leading comma and space.
323 $sort_part .= 'date';
325 if (($canViewReports || $isClient) && $options['users'] && !$grouping_by_user)
326 $sort_part .= ', user, type';
327 if ($options['show_start'])
328 $sort_part .= ', unformatted_start';
329 $sort_part .= ', id';
332 // By now we are ready with sql.
334 // Obtain items for report.
335 $res = $mdb2->query($sql);
336 if (is_a($res, 'PEAR_Error')) die($res->getMessage());
338 while ($val = $res->fetchRow()) {
339 if ($convertTo12Hour) {
340 if($val['start'] != '')
341 $val['start'] = ttTimeHelper::to12HourFormat($val['start']);
342 if($val['finish'] != '')
343 $val['finish'] = ttTimeHelper::to12HourFormat($val['finish']);
345 if (isset($val['cost'])) {
346 if ('.' != $user->decimal_mark)
347 $val['cost'] = str_replace('.', $user->decimal_mark, $val['cost']);
349 if (isset($val['expense'])) {
350 if ('.' != $user->decimal_mark)
351 $val['expense'] = str_replace('.', $user->decimal_mark, $val['expense']);
354 if ($grouping) $val['grouped_by'] = ttReportHelper::makeGroupByKey($options, $val);
355 $val['date'] = ttDateToUserFormat($val['date']);
357 $report_items[] = $val;
360 return $report_items;
363 // putInSession stores tt_log and tt_expense_items ids from a report in user session
364 // as 2 comma-separated lists.
365 static function putInSession($report_items) {
366 unset($_SESSION['report_item_ids']);
367 unset($_SESSION['report_item_expense_ids']);
369 // Iterate through records and build 2 comma-separated lists.
370 foreach($report_items as $item) {
371 if ($item['type'] == 1)
372 $report_item_ids .= ','.$item['id'];
373 else if ($item['type'] == 2)
374 $report_item_expense_ids .= ','.$item['id'];
376 $report_item_ids = trim($report_item_ids, ',');
377 $report_item_expense_ids = trim($report_item_expense_ids, ',');
379 // The lists are reqdy. Put them in session.
380 if ($report_item_ids) $_SESSION['report_item_ids'] = $report_item_ids;
381 if ($report_item_expense_ids) $_SESSION['report_item_expense_ids'] = $report_item_expense_ids;
384 // getFromSession obtains tt_log and tt_expense_items ids stored in user session.
385 static function getFromSession() {
387 $report_item_ids = $_SESSION['report_item_ids'];
388 if ($report_item_ids)
389 $items['report_item_ids'] = explode(',', $report_item_ids);
390 $report_item_expense_ids = $_SESSION['report_item_expense_ids'];
391 if ($report_item_expense_ids)
392 $items['report_item_expense_ids'] = explode(',', $report_item_expense_ids);
396 // getSubtotals calculates report items subtotals when a report is grouped by.
397 // Without expenses, it's a simple select with group by.
398 // With expenses, it becomes a select with group by from a combined set of records obtained with "union all".
399 static function getSubtotals($options) {
402 $mdb2 = getConnection();
404 $concat_part = ttReportHelper::makeConcatPart($options);
405 $join_part = ttReportHelper::makeJoinPart($options);
406 $where = ttReportHelper::getWhere($options);
407 $group_by_part = ttReportHelper::makeGroupByPart($options);
408 if ($options['show_cost']) {
409 if (MODE_TIME == $user->tracking_mode) {
410 if (!ttReportHelper::groupingBy('user', $options))
411 $left_join = 'left join tt_users u on (l.user_id = u.id)';
412 $sql = "select $concat_part, sum(time_to_sec(l.duration)) as time";
413 if ($options['show_work_units']) {
414 if ($user->unit_totals_only)
415 $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";
417 $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";
419 $sql .= ", sum(cast(l.billable * coalesce(u.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10, 2))) as cost,
420 null as expenses from tt_log l
421 $join_part $left_join $where $group_by_part";
423 // If we are including cost and tracking projects, our query (the same as above) needs to join the tt_user_project_binds table.
424 $sql = "select $concat_part, sum(time_to_sec(l.duration)) as time";
425 if ($options['show_work_units']) {
426 if ($user->unit_totals_only)
427 $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";
429 $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";
431 $sql .= ", sum(cast(l.billable * coalesce(upb.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10,2))) as cost,
432 null as expenses from tt_log l
434 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";
437 // $sql = "select $group_field as group_field, sum(time_to_sec(l.duration)) as time";
438 $sql = "select $concat_part, sum(time_to_sec(l.duration)) as time";
439 if ($options['show_work_units']) {
440 if ($user->unit_totals_only)
441 $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";
443 $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";
445 $sql .= ", null as expenses from tt_log l
446 $join_part $where $group_by_part";
448 // By now we have sql for time items.
450 // However, when we have expenses, we need to do a union with a separate query for expense items from tt_expense_items table.
451 if ($options['show_cost'] && $user->isPluginEnabled('ex')) { // if ex(penses) plugin is enabled
453 $concat_part = ttReportHelper::makeConcatExpensesPart($options);
454 $join_part = ttReportHelper::makeJoinExpensesPart($options);
455 $where = ttReportHelper::getExpenseWhere($options);
456 $group_by_expenses_part = ttReportHelper::makeGroupByExpensesPart($options);
457 $sql_for_expenses = "select $concat_part, null as time";
458 if ($options['show_work_units']) $sql_for_expenses .= ", null as units";
459 $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";
461 // Create a combined query.
462 $fields = ttReportHelper::makeCombinedSelectPart($options);
463 $combined = "select $fields, sum(time) as time";
464 if ($options['show_work_units']) $combined .= ", sum(units) as units";
465 $combined .= ", sum(cost) as cost, sum(expenses) as expenses from (($sql) union all ($sql_for_expenses)) t group by $fields";
470 $res = $mdb2->query($sql);
471 if (is_a($res, 'PEAR_Error')) die($res->getMessage());
472 while ($val = $res->fetchRow()) {
473 $time = $val['time'] ? sec_to_time_fmt_hm($val['time']) : null;
474 $rowLabel = ttReportHelper::makeGroupByLabel($val['group_field'], $options);
475 if ($options['show_cost']) {
476 if ('.' != $user->decimal_mark) {
477 $val['cost'] = str_replace('.', $user->decimal_mark, $val['cost']);
478 $val['expenses'] = str_replace('.', $user->decimal_mark, $val['expenses']);
480 $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']);
482 $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']);
488 // getTotals calculates total hours and cost for all report items.
489 static function getTotals($options)
493 $mdb2 = getConnection();
495 $where = ttReportHelper::getWhere($options);
498 $time_part = "sum(time_to_sec(l.duration)) as time";
499 if ($options['show_work_units']) {
500 $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";
502 if ($options['show_cost']) {
503 if (MODE_TIME == $user->tracking_mode)
504 $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";
506 $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";
508 $cost_part = ", null as cost, null as expenses";
510 if ($options['show_cost']) {
511 if (MODE_TIME == $user->tracking_mode) {
512 $left_joins = "left join tt_users u on (l.user_id = u.id)";
514 $left_joins = "left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id)";
517 // Prepare a query for time items.
518 $sql = "select $time_part $units_part $cost_part from tt_log l $left_joins $where";
520 // If we have expenses, query becomes a bit more complex.
521 if ($options['show_cost'] && $user->isPluginEnabled('ex')) {
522 $where = ttReportHelper::getExpenseWhere($options);
523 $sql_for_expenses = "select null as time";
524 if ($options['show_work_units']) $sql_for_expenses .= ", null as units";
525 $sql_for_expenses .= ", sum(cost) as cost, sum(cost) as expenses from tt_expense_items ei $where";
527 // Create a combined query.
528 $combined = "select sum(time) as time";
529 if ($options['show_work_units']) $combined .= ", sum(units) as units";
530 $combined .= ", sum(cost) as cost, sum(expenses) as expenses from (($sql) union all ($sql_for_expenses)) t";
535 $res = $mdb2->query($sql);
536 if (is_a($res, 'PEAR_Error')) die($res->getMessage());
538 $val = $res->fetchRow();
539 $total_time = $val['time'] ? sec_to_time_fmt_hm($val['time']) : null;
540 if ($options['show_cost']) {
541 $total_cost = $val['cost'];
542 if (!$total_cost) $total_cost = '0.00';
543 if ('.' != $user->decimal_mark)
544 $total_cost = str_replace('.', $user->decimal_mark, $total_cost);
545 $total_expenses = $val['expenses'];
546 if (!$total_expenses) $total_expenses = '0.00';
547 if ('.' != $user->decimal_mark)
548 $total_expenses = str_replace('.', $user->decimal_mark, $total_expenses);
551 if ($options['period'])
552 $period = new Period($options['period'], new DateAndTime($user->date_format));
554 $period = new Period();
556 new DateAndTime($user->date_format, $options['period_start']),
557 new DateAndTime($user->date_format, $options['period_end']));
560 $totals['start_date'] = $period->getStartDate();
561 $totals['end_date'] = $period->getEndDate();
562 $totals['time'] = $total_time;
563 $totals['units'] = $val['units'];
564 $totals['cost'] = $total_cost;
565 $totals['expenses'] = $total_expenses;
570 // The assignToInvoice assigns a set of records to a specific invoice.
571 static function assignToInvoice($invoice_id, $time_log_ids, $expense_item_ids) {
573 $mdb2 = getConnection();
575 $group_id = $user->getGroup();
576 $org_id = $user->org_id;
579 $sql = "update tt_log set invoice_id = ".$mdb2->quote($invoice_id).
580 " where id in(".join(', ', $time_log_ids).") and group_id = $group_id and org_id = $org_id";
581 $affected = $mdb2->exec($sql);
582 if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
584 if ($expense_item_ids) {
585 $sql = "update tt_expense_items set invoice_id = ".$mdb2->quote($invoice_id).
586 " where id in(".join(', ', $expense_item_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());
592 // The markPaid marks a set of records as either paid or unpaid.
593 static function markPaid($time_log_ids, $expense_item_ids, $paid = true) {
595 $mdb2 = getConnection();
597 $group_id = $user->getGroup();
598 $org_id = $user->org_id;
600 $paid_val = (int) $paid;
602 $sql = "update tt_log set paid = $paid_val".
603 " where id in(".join(', ', $time_log_ids).") and group_id = $group_id and org_id = $org_id";
604 $affected = $mdb2->exec($sql);
605 if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
607 if ($expense_item_ids) {
608 $sql = "update tt_expense_items set paid = $paid_val".
609 " where id in(".join(', ', $expense_item_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());
615 // prepareReportBody - prepares an email body for report.
616 static function prepareReportBody($options, $comment = null)
621 // Determine these once as they are used in multiple places in this function.
622 $canViewReports = $user->can('view_reports') || $user->can('view_all_reports');
623 $isClient = $user->isClient();
625 $items = ttReportHelper::getItems($options);
626 $grouping = ttReportHelper::grouping($options);
628 $subtotals = ttReportHelper::getSubtotals($options);
629 $totals = ttReportHelper::getTotals($options);
631 // Use custom fields plugin if it is enabled.
632 if ($user->isPluginEnabled('cf'))
633 $custom_fields = new CustomFields();
635 // Define some styles to use in email.
636 $style_title = 'text-align: center; font-size: 15pt; font-family: Arial, Helvetica, sans-serif;';
637 $tableHeader = 'font-weight: bold; background-color: #a6ccf7; text-align: left;';
638 $tableHeaderCentered = 'font-weight: bold; background-color: #a6ccf7; text-align: center;';
639 $rowItem = 'background-color: #ffffff;';
640 $rowItemAlt = 'background-color: #f5f5f5;';
641 $rowSubtotal = 'background-color: #e0e0e0;';
642 $cellLeftAligned = 'text-align: left; vertical-align: top;';
643 $cellRightAligned = 'text-align: right; vertical-align: top;';
644 $cellLeftAlignedSubtotal = 'font-weight: bold; text-align: left; vertical-align: top;';
645 $cellRightAlignedSubtotal = 'font-weight: bold; text-align: right; vertical-align: top;';
647 // Start creating email body.
649 $body .= '<head><meta http-equiv="content-type" content="text/html; charset='.CHARSET.'"></head>';
653 $body .= '<p style="'.$style_title.'">'.$i18n->get('form.mail.report_subject').': '.$totals['start_date'].' - '.$totals['end_date'].'</p>';
656 if ($comment) $body .= '<p>'.htmlspecialchars($comment).'</p>';
658 if ($options['show_totals_only']) {
659 // Totals only report. Output subtotals.
660 $group_by_header = ttReportHelper::makeGroupByHeader($options);
662 $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
664 $body .= '<td style="'.$tableHeader.'">'.$group_by_header.'</td>';
665 if ($options['show_duration'])
666 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.duration').'</td>';
667 if ($options['show_work_units'])
668 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.work_units_short').'</td>';
669 if ($options['show_cost'])
670 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.cost').'</td>';
672 foreach($subtotals as $subtotal) {
673 $body .= '<tr style="'.$rowSubtotal.'">';
674 $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($subtotal['name'] ? htmlspecialchars($subtotal['name']) : ' ').'</td>';
675 if ($options['show_duration']) {
676 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
677 if ($subtotal['time'] <> '0:00') $body .= $subtotal['time'];
680 if ($options['show_work_units']) {
681 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
682 $body .= $subtotal['units'];
685 if ($options['show_cost']) {
686 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
687 $body .= ($canViewReports || $isClient) ? $subtotal['cost'] : $subtotal['expenses'];
694 $body .= '<tr><td> </td></tr>';
695 $body .= '<tr style="'.$rowSubtotal.'">';
696 $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.total').'</td>';
697 if ($options['show_duration']) {
698 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
699 if ($totals['time'] <> '0:00') $body .= $totals['time'];
702 if ($options['show_work_units']) {
703 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
704 $body .= $totals['units'];
707 if ($options['show_cost']) {
708 $body .= '<td nowrap style="'.$cellRightAlignedSubtotal.'">'.htmlspecialchars($user->currency).' ';
709 $body .= ($canViewReports || $isClient) ? $totals['cost'] : $totals['expenses'];
718 // Print table header.
719 $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
721 $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.date').'</td>';
722 if ($canViewReports || $isClient)
723 $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.user').'</td>';
724 if ($options['show_client'])
725 $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.client').'</td>';
726 if ($options['show_project'])
727 $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.project').'</td>';
728 if ($options['show_task'])
729 $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.task').'</td>';
730 if ($options['show_custom_field_1'])
731 $body .= '<td style="'.$tableHeader.'">'.htmlspecialchars($custom_fields->fields[0]['label']).'</td>';
732 if ($options['show_start'])
733 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.start').'</td>';
734 if ($options['show_end'])
735 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.finish').'</td>';
736 if ($options['show_duration'])
737 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.duration').'</td>';
738 if ($options['show_work_units'])
739 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.work_units_short').'</td>';
740 if ($options['show_note'])
741 $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.note').'</td>';
742 if ($options['show_cost'])
743 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.cost').'</td>';
744 if ($options['show_paid'])
745 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.paid').'</td>';
746 if ($options['show_ip'])
747 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.ip').'</td>';
748 if ($options['show_invoice'])
749 $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.invoice').'</td>';
752 // Initialize variables to print subtotals.
753 if ($items && $grouping) {
754 $print_subtotals = true;
756 $prev_grouped_by = '';
757 $cur_grouped_by = '';
759 // Initialize variables to alternate color of rows for different dates.
762 $row_style = $rowItem;
764 // Print report items.
765 if (is_array($items)) {
766 foreach ($items as $record) {
767 $cur_date = $record['date'];
768 // Print a subtotal row after a block of grouped items.
769 if ($print_subtotals) {
770 $cur_grouped_by = $record['grouped_by'];
771 if ($cur_grouped_by != $prev_grouped_by && !$first_pass) {
772 $body .= '<tr style="'.$rowSubtotal.'">';
773 $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.subtotal').'</td>';
774 $subtotal_name = htmlspecialchars($subtotals[$prev_grouped_by]['name']);
775 if ($canViewReports || $isClient) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['user'].'</td>';
776 if ($options['show_client']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['client'].'</td>';
777 if ($options['show_project']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['project'].'</td>';
778 if ($options['show_task']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['task'].'</td>';
779 if ($options['show_custom_field_1']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['cf_1'].'</td>';
780 if ($options['show_start']) $body .= '<td></td>';
781 if ($options['show_end']) $body .= '<td></td>';
782 if ($options['show_duration']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['time'].'</td>';
783 if ($options['show_work_units']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['units'].'</td>';
784 if ($options['show_note']) $body .= '<td></td>';
785 if ($options['show_cost']) {
786 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
787 $body .= ($canViewReports || $isClient) ? $subtotals[$prev_grouped_by]['cost'] : $subtotals[$prev_grouped_by]['expenses'];
790 if ($options['show_paid']) $body .= '<td></td>';
791 if ($options['show_ip']) $body .= '<td></td>';
792 if ($options['show_invoice']) $body .= '<td></td>';
794 $body .= '<tr><td> </td></tr>';
799 // Print a regular row.
800 if ($cur_date != $prev_date)
801 $row_style = ($row_style == $rowItem) ? $rowItemAlt : $rowItem;
802 $body .= '<tr style="'.$row_style.'">';
803 $body .= '<td style="'.$cellLeftAligned.'">'.$record['date'].'</td>';
804 if ($canViewReports || $isClient)
805 $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['user']).'</td>';
806 if ($options['show_client'])
807 $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['client']).'</td>';
808 if ($options['show_project'])
809 $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['project']).'</td>';
810 if ($options['show_task'])
811 $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['task']).'</td>';
812 if ($options['show_custom_field_1'])
813 $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['cf_1']).'</td>';
814 if ($options['show_start'])
815 $body .= '<td nowrap style="'.$cellRightAligned.'">'.$record['start'].'</td>';
816 if ($options['show_end'])
817 $body .= '<td nowrap style="'.$cellRightAligned.'">'.$record['finish'].'</td>';
818 if ($options['show_duration'])
819 $body .= '<td style="'.$cellRightAligned.'">'.$record['duration'].'</td>';
820 if ($options['show_work_units'])
821 $body .= '<td style="'.$cellRightAligned.'">'.$record['units'].'</td>';
822 if ($options['show_note'])
823 $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['note']).'</td>';
824 if ($options['show_cost'])
825 $body .= '<td style="'.$cellRightAligned.'">'.$record['cost'].'</td>';
826 if ($options['show_paid']) {
827 $body .= '<td style="'.$cellRightAligned.'">';
828 $body .= $record['paid'] == 1 ? $i18n->get('label.yes') : $i18n->get('label.no');
831 if ($options['show_ip']) {
832 $body .= '<td style="'.$cellRightAligned.'">';
833 $body .= $record['modified'] ? $record['modified_ip'].' '.$record['modified'] : $record['created_ip'].' '.$record['created'];
836 if ($options['show_invoice'])
837 $body .= '<td style="'.$cellRightAligned.'">'.htmlspecialchars($record['invoice']).'</td>';
840 $prev_date = $record['date'];
841 if ($print_subtotals)
842 $prev_grouped_by = $record['grouped_by'];
846 // Print a terminating subtotal.
847 if ($print_subtotals) {
848 $body .= '<tr style="'.$rowSubtotal.'">';
849 $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.subtotal').'</td>';
850 $subtotal_name = htmlspecialchars($subtotals[$cur_grouped_by]['name']);
851 if ($canViewReports || $isClient) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['user'].'</td>';
852 if ($options['show_client']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['client'].'</td>';
853 if ($options['show_project']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['project'].'</td>';
854 if ($options['show_task']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['task'].'</td>';
855 if ($options['show_custom_field_1']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['cf_1'].'</td>';
856 if ($options['show_start']) $body .= '<td></td>';
857 if ($options['show_end']) $body .= '<td></td>';
858 if ($options['show_duration']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$cur_grouped_by]['time'].'</td>';
859 if ($options['show_work_units']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$cur_grouped_by]['units'].'</td>';
860 if ($options['show_note']) $body .= '<td></td>';
861 if ($options['show_cost']) {
862 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
863 $body .= ($canViewReports || $isClient) ? $subtotals[$cur_grouped_by]['cost'] : $subtotals[$cur_grouped_by]['expenses'];
866 if ($options['show_paid']) $body .= '<td></td>';
867 if ($options['show_ip']) $body .= '<td></td>';
868 if ($options['show_invoice']) $body .= '<td></td>';
873 $body .= '<tr><td> </td></tr>';
874 $body .= '<tr style="'.$rowSubtotal.'">';
875 $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.total').'</td>';
876 if ($canViewReports || $isClient) $body .= '<td></td>';
877 if ($options['show_client']) $body .= '<td></td>';
878 if ($options['show_project']) $body .= '<td></td>';
879 if ($options['show_task']) $body .= '<td></td>';
880 if ($options['show_custom_field_1']) $body .= '<td></td>';
881 if ($options['show_start']) $body .= '<td></td>';
882 if ($options['show_end']) $body .= '<td></td>';
883 if ($options['show_duration']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$totals['time'].'</td>';
884 if ($options['show_work_units']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$totals['units'].'</td>';
885 if ($options['show_note']) $body .= '<td></td>';
886 if ($options['show_cost']) {
887 $body .= '<td nowrap style="'.$cellRightAlignedSubtotal.'">'.htmlspecialchars($user->currency).' ';
888 $body .= ($canViewReports || $isClient) ? $totals['cost'] : $totals['expenses'];
891 if ($options['show_paid']) $body .= '<td></td>';
892 if ($options['show_ip']) $body .= '<td></td>';
893 if ($options['show_invoice']) $body .= '<td></td>';
900 if (!defined('REPORT_FOOTER') || !(REPORT_FOOTER == false))
901 $body .= '<p style="text-align: center;">'.$i18n->get('form.mail.footer').'</p>';
903 // Finish creating email body.
904 $body .= '</body></html>';
909 // checkFavReportCondition - checks whether it is okay to send fav report.
910 static function checkFavReportCondition($options, $condition)
912 $items = ttReportHelper::getItems($options);
914 $condition = trim(str_replace('count', '', $condition));
916 $greater_or_equal = ttStartsWith($condition, '>=');
917 if ($greater_or_equal) $condition = trim(str_replace('>=', '', $condition));
919 $less_or_equal = ttStartsWith($condition, '<=');
920 if ($less_or_equal) $condition = trim(str_replace('<=', '', $condition));
922 $not_equal = ttStartsWith($condition, '<>');
923 if ($not_equal) $condition = trim(str_replace('<>', '', $condition));
925 $greater = ttStartsWith($condition, '>');
926 if ($greater) $condition = trim(str_replace('>', '', $condition));
928 $less = ttStartsWith($condition, '<');
929 if ($less) $condition = trim(str_replace('<', '', $condition));
931 $equal = ttStartsWith($condition, '=');
932 if ($equal) $condition = trim(str_replace('=', '', $condition));
934 $count_required = (int) $condition;
936 if ($greater && count($items) > $count_required) return true;
937 if ($greater_or_equal && count($items) >= $count_required) return true;
938 if ($less && count($items) < $count_required) return true;
939 if ($less_or_equal && count($items) <= $count_required) return true;
940 if ($equal && count($items) == $count_required) return true;
941 if ($not_equal && count($items) <> $count_required) return true;
946 // sendFavReport - sends a favorite report to a specified email, called from cron.php
947 static function sendFavReport($options, $subject, $email, $cc) {
948 // We are called from cron.php, we have no $bean in session.
949 // cron.php sets global $user and $i18n objects to match our favorite report user.
953 // Prepare report body.
954 $body = ttReportHelper::prepareReportBody($options);
956 import('mail.Mailer');
957 $mailer = new Mailer();
958 $mailer->setCharSet(CHARSET);
959 $mailer->setContentType('text/html');
960 $mailer->setSender(SENDER);
962 $mailer->setReceiverCC($cc);
963 if (!empty($user->bcc_email))
964 $mailer->setReceiverBCC($user->bcc_email);
965 $mailer->setReceiver($email);
966 $mailer->setMailMode(MAIL_MODE);
967 if (empty($subject)) $subject = $options['name'];
968 if (!$mailer->send($subject, $body))
974 // getReportOptions - returns an array of report options constructed from session bean.
976 // Note: similarly to ttFavReportHelper::getReportOptions, this function is a part of
977 // refactoring to simplify maintenance of report generating functions, as we currently
978 // have 2 sets: normal reporting (from bean), and fav report emailing (from db fields).
979 // Using options obtained from either db or bean shall allow us to use only one set of functions.
980 static function getReportOptions($bean) {
983 // Prepare an array of report options.
986 // Construct one by one.
987 $options['name'] = null; // No name required.
988 $options['user_id'] = $user->id; // Not sure if we need user_id here. Fav reports use it to recycle $user object in cron.php.
989 $options['client_id'] = $bean->getAttribute('client');
990 $options['cf_1_option_id'] = $bean->getAttribute('option');
991 $options['project_id'] = $bean->getAttribute('project');
992 $options['task_id'] = $bean->getAttribute('task');
993 $options['billable'] = $bean->getAttribute('include_records');
994 $options['invoice'] = $bean->getAttribute('invoice');
995 $options['paid_status'] = $bean->getAttribute('paid_status');
996 if (is_array($bean->getAttribute('users'))) $options['users'] = join(',', $bean->getAttribute('users'));
997 $options['period'] = $bean->getAttribute('period');
998 $options['period_start'] = $bean->getAttribute('start_date');
999 $options['period_end'] = $bean->getAttribute('end_date');
1000 $options['show_client'] = $bean->getAttribute('chclient');
1001 $options['show_invoice'] = $bean->getAttribute('chinvoice');
1002 $options['show_paid'] = $bean->getAttribute('chpaid');
1003 $options['show_ip'] = $bean->getAttribute('chip');
1004 $options['show_project'] = $bean->getAttribute('chproject');
1005 $options['show_start'] = $bean->getAttribute('chstart');
1006 $options['show_duration'] = $bean->getAttribute('chduration');
1007 $options['show_cost'] = $bean->getAttribute('chcost');
1008 $options['show_task'] = $bean->getAttribute('chtask');
1009 $options['show_end'] = $bean->getAttribute('chfinish');
1010 $options['show_note'] = $bean->getAttribute('chnote');
1011 $options['show_custom_field_1'] = $bean->getAttribute('chcf_1');
1012 $options['show_work_units'] = $bean->getAttribute('chunits');
1013 $options['show_totals_only'] = $bean->getAttribute('chtotalsonly');
1014 $options['group_by1'] = $bean->getAttribute('group_by1');
1015 $options['group_by2'] = $bean->getAttribute('group_by2');
1016 $options['group_by3'] = $bean->getAttribute('group_by3');
1020 // verifyBean is a security function to make sure data in bean makes sense for a group.
1021 static function verifyBean($bean) {
1025 $users_in_bean = $bean->getAttribute('users');
1026 if (is_array($users_in_bean)) {
1027 $users_in_group = ttGroupHelper::getUsers();
1028 foreach ($users_in_group as $user_in_group) {
1029 $valid_ids[] = $user_in_group['id'];
1031 foreach ($users_in_bean as $user_in_bean) {
1032 if (!in_array($user_in_bean, $valid_ids)) {
1038 // TODO: add additional checks here. Perhaps do it before saving the bean for consistency.
1042 // makeGroupByKey builds a combined group by key from group_by1, group_by2 and group_by3 values
1043 // (passed in $options) and a row of data ($row obtained from a db query).
1044 static function makeGroupByKey($options, $row) {
1045 if ($options['group_by1'] != null && $options['group_by1'] != 'no_grouping') {
1046 // We have group_by1.
1047 $group_by1 = $options['group_by1'];
1048 $group_by1_value = $row[$group_by1];
1049 //if ($group_by1 == 'date') $group_by1_value = ttDateToUserFormat($group_by1_value);
1050 if (empty($group_by1_value)) $group_by1_value = 'Null'; // To match what comes out of makeConcatPart.
1051 $group_by_key .= ' - '.$group_by1_value;
1053 if ($options['group_by2'] != null && $options['group_by2'] != 'no_grouping') {
1054 // We have group_by2.
1055 $group_by2 = $options['group_by2'];
1056 $group_by2_value = $row[$group_by2];
1057 //if ($group_by2 == 'date') $group_by2_value = ttDateToUserFormat($group_by2_value);
1058 if (empty($group_by2_value)) $group_by2_value = 'Null'; // To match what comes out of makeConcatPart.
1059 $group_by_key .= ' - '.$group_by2_value;
1061 if ($options['group_by3'] != null && $options['group_by3'] != 'no_grouping') {
1062 // We have group_by3.
1063 $group_by3 = $options['group_by3'];
1064 $group_by3_value = $row[$group_by3];
1065 //if ($group_by3 == 'date') $group_by3_value = ttDateToUserFormat($group_by3_value);
1066 if (empty($group_by3_value)) $group_by3_value = 'Null'; // To match what comes out of makeConcatPart.
1067 $group_by_key .= ' - '.$group_by3_value;
1069 $group_by_key = trim($group_by_key, ' -');
1070 return $group_by_key;
1073 // makeGroupByPart builds a combined group by part for sql query for time items using group_by1,
1074 // group_by2, and group_by3 values passed in $options.
1075 static function makeGroupByPart($options) {
1076 if (!ttReportHelper::grouping($options)) return null;
1078 $group_by1 = $options['group_by1'];
1079 $group_by2 = $options['group_by2'];
1080 $group_by3 = $options['group_by3'];
1082 switch ($group_by1) {
1084 $group_by_parts .= ', l.date';
1087 $group_by_parts .= ', u.name';
1090 $group_by_parts .= ', c.name';
1093 $group_by_parts .= ', p.name';
1096 $group_by_parts .= ', t.name';
1099 $group_by_parts .= ', cfo.value';
1102 switch ($group_by2) {
1104 $group_by_parts .= ', l.date';
1107 $group_by_parts .= ', u.name';
1110 $group_by_parts .= ', c.name';
1113 $group_by_parts .= ', p.name';
1116 $group_by_parts .= ', t.name';
1119 $group_by_parts .= ', cfo.value';
1122 switch ($group_by3) {
1124 $group_by_parts .= ', l.date';
1127 $group_by_parts .= ', u.name';
1130 $group_by_parts .= ', c.name';
1133 $group_by_parts .= ', p.name';
1136 $group_by_parts .= ', t.name';
1139 $group_by_parts .= ', cfo.value';
1142 // Remove garbage from the beginning.
1143 $group_by_parts = ltrim($group_by_parts, ', ');
1144 $group_by_part = "group by $group_by_parts";
1145 return $group_by_part;
1148 // makeGroupByExpensesPart builds a combined group by part for sql query for expense items using
1149 // group_by1, group_by2, and group_by3 values passed in $options.
1150 static function makeGroupByExpensesPart($options) {
1151 $no_grouping = ($options['group_by1'] == null || $options['group_by1'] == 'no_grouping') &&
1152 ($options['group_by2'] == null || $options['group_by2'] == 'no_grouping') &&
1153 ($options['group_by3'] == null || $options['group_by3'] == 'no_grouping');
1154 if ($no_grouping) return null;
1156 $group_by1 = $options['group_by1'];
1157 $group_by2 = $options['group_by2'];
1158 $group_by3 = $options['group_by3'];
1160 switch ($group_by1) {
1162 $group_by_parts .= ', ei.date';
1165 $group_by_parts .= ', u.name';
1168 $group_by_parts .= ', c.name';
1171 $group_by_parts .= ', p.name';
1174 switch ($group_by2) {
1176 $group_by_parts .= ', ei.date';
1179 $group_by_parts .= ', u.name';
1182 $group_by_parts .= ', c.name';
1185 $group_by_parts .= ', p.name';
1188 switch ($group_by3) {
1190 $group_by_parts .= ', ei.date';
1193 $group_by_parts .= ', u.name';
1196 $group_by_parts .= ', c.name';
1199 $group_by_parts .= ', p.name';
1202 // Remove garbage from the beginning.
1203 $group_by_parts = ltrim($group_by_parts, ', ');
1204 if ($group_by_parts)
1205 $group_by_part = "group by $group_by_parts";
1206 return $group_by_part;
1209 // makeConcatPart builds a concatenation part for getSubtotals query (for time items).
1210 static function makeConcatPart($options) {
1211 $group_by1 = $options['group_by1'];
1212 $group_by2 = $options['group_by2'];
1213 $group_by3 = $options['group_by3'];
1215 switch ($group_by1) {
1217 $what_to_concat .= ", ' - ', l.date";
1220 $what_to_concat .= ", ' - ', u.name";
1221 $fields_part .= ', u.name as user';
1224 $what_to_concat .= ", ' - ', coalesce(c.name, 'Null')";
1225 $fields_part .= ', c.name as client';
1228 $what_to_concat .= ", ' - ', coalesce(p.name, 'Null')";
1229 $fields_part .= ', p.name as project';
1232 $what_to_concat .= ", ' - ', coalesce(t.name, 'Null')";
1233 $fields_part .= ', t.name as task';
1236 $what_to_concat .= ", ' - ', coalesce(cfo.value, 'Null')";
1237 $fields_part .= ', cfo.value as cf_1';
1240 switch ($group_by2) {
1242 $what_to_concat .= ", ' - ', l.date";
1245 $what_to_concat .= ", ' - ', u.name";
1246 $fields_part .= ', u.name as user';
1249 $what_to_concat .= ", ' - ', coalesce(c.name, 'Null')";
1250 $fields_part .= ', c.name as client';
1253 $what_to_concat .= ", ' - ', coalesce(p.name, 'Null')";
1254 $fields_part .= ', p.name as project';
1257 $what_to_concat .= ", ' - ', coalesce(t.name, 'Null')";
1258 $fields_part .= ', t.name as task';
1261 $what_to_concat .= ", ' - ', coalesce(cfo.value, 'Null')";
1262 $fields_part .= ', cfo.value as cf_1';
1265 switch ($group_by3) {
1267 $what_to_concat .= ", ' - ', l.date";
1270 $what_to_concat .= ", ' - ', u.name";
1271 $fields_part .= ', u.name as user';
1274 $what_to_concat .= ", ' - ', coalesce(c.name, 'Null')";
1275 $fields_part .= ', c.name as client';
1278 $what_to_concat .= ", ' - ', coalesce(p.name, 'Null')";
1279 $fields_part .= ', p.name as project';
1282 $what_to_concat .= ", ' - ', coalesce(t.name, 'Null')";
1283 $fields_part .= ', t.name as task';
1286 $what_to_concat .= ", ' - ', coalesce(cfo.value, 'Null')";
1287 $fields_part .= ', cfo.value as cf_1';
1290 // Remove garbage from both ends.
1291 $what_to_concat = trim($what_to_concat, "', -");
1292 $concat_part = "concat($what_to_concat) as group_field";
1293 $concat_part = trim($concat_part, ' -');
1294 return "$concat_part $fields_part";
1297 // makeConcatPart builds a concatenation part for getSubtotals query (for expense items).
1298 static function makeConcatExpensesPart($options) {
1299 $group_by1 = $options['group_by1'];
1300 $group_by2 = $options['group_by2'];
1301 $group_by3 = $options['group_by3'];
1303 switch ($group_by1) {
1305 $what_to_concat .= ", ' - ', ei.date";
1308 $what_to_concat .= ", ' - ', u.name";
1309 $fields_part .= ', u.name as user';
1312 $what_to_concat .= ", ' - ', coalesce(c.name, 'Null')";
1313 $fields_part .= ', c.name as client';
1316 $what_to_concat .= ", ' - ', coalesce(p.name, 'Null')";
1317 $fields_part .= ', p.name as project';
1321 $what_to_concat .= ", ' - ', 'Null'";
1322 $fields_part .= ', null as task';
1326 $what_to_concat .= ", ' - ', 'Null'";
1327 $fields_part .= ', null as cf_1';
1330 switch ($group_by2) {
1332 $what_to_concat .= ", ' - ', ei.date";
1335 $what_to_concat .= ", ' - ', u.name";
1336 $fields_part .= ', u.name as user';
1339 $what_to_concat .= ", ' - ', coalesce(c.name, 'Null')";
1340 $fields_part .= ', c.name as client';
1343 $what_to_concat .= ", ' - ', coalesce(p.name, 'Null')";
1344 $fields_part .= ', p.name as project';
1348 $what_to_concat .= ", ' - ', 'Null'";
1349 $fields_part .= ', null as task';
1353 $what_to_concat .= ", ' - ', 'Null'";
1354 $fields_part .= ', null as cf_1';
1357 switch ($group_by3) {
1359 $what_to_concat .= ", ' - ', ei.date";
1362 $what_to_concat .= ", ' - ', u.name";
1363 $fields_part .= ', u.name as user';
1366 $what_to_concat .= ", ' - ', coalesce(c.name, 'Null')";
1367 $fields_part .= ', c.name as client';
1370 $what_to_concat .= ", ' - ', coalesce(p.name, 'Null')";
1371 $fields_part .= ', p.name as project';
1375 $what_to_concat .= ", ' - ', 'Null'";
1376 $fields_part .= ', null as task';
1380 $what_to_concat .= ", ' - ', 'Null'";
1381 $fields_part .= ', null as cf_1';
1384 // Remove garbage from the beginning.
1385 if ($what_to_concat)
1386 $what_to_concat = substr($what_to_concat, 8);
1387 $concat_part = "concat($what_to_concat) as group_field";
1388 return "$concat_part $fields_part";
1391 // makeCombinedSelectPart builds a list of fields for a combined select on a union for getSubtotals.
1392 // This is used when we include expenses.
1393 static function makeCombinedSelectPart($options) {
1394 $group_by1 = $options['group_by1'];
1395 $group_by2 = $options['group_by2'];
1396 $group_by3 = $options['group_by3'];
1398 $fields = "group_field";
1400 switch ($group_by1) {
1402 $fields .= ', user';
1405 $fields_part .= ', client';
1408 $fields .= ', project';
1412 $fields .= ', task';
1416 $fields .= ', cf_1';
1419 switch ($group_by2) {
1421 $fields .= ', user';
1424 $fields_part .= ', client';
1427 $fields .= ', project';
1431 $fields .= ', task';
1435 $fields .= ', cf_1';
1438 switch ($group_by3) {
1440 $fields .= ', user';
1443 $fields_part .= ', client';
1446 $fields .= ', project';
1450 $fields .= ', task';
1454 $fields .= ', cf_1';
1460 // makeJoinPart builds a left join part for getSubtotals query (for time items).
1461 static function makeJoinPart($options) {
1464 if (ttReportHelper::groupingBy('user', $options)) {
1465 $join .= ' left join tt_users u on (l.user_id = u.id)';
1467 if (ttReportHelper::groupingBy('client', $options)) {
1468 $join .= ' left join tt_clients c on (l.client_id = c.id)';
1470 if (ttReportHelper::groupingBy('project', $options)) {
1471 $join .= ' left join tt_projects p on (l.project_id = p.id)';
1473 if (ttReportHelper::groupingBy('task', $options)) {
1474 $join .= ' left join tt_tasks t on (l.task_id = t.id)';
1476 if (ttReportHelper::groupingBy('cf_1', $options)) {
1477 $custom_fields = new CustomFields();
1478 if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_TEXT)
1479 $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)';
1480 elseif ($custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN)
1481 $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)';
1486 // makeJoinExpensesPart builds a left join part for getSubtotals query for expense items.
1487 static function makeJoinExpensesPart($options) {
1488 if (ttReportHelper::groupingBy('user', $options)) {
1489 $join .= ' left join tt_users u on (ei.user_id = u.id)';
1491 if (ttReportHelper::groupingBy('client', $options)) {
1492 $join .= ' left join tt_clients c on (ei.client_id = c.id)';
1494 if (ttReportHelper::groupingBy('project', $options)) {
1495 $join .= ' left join tt_projects p on (ei.project_id = p.id)';
1500 // grouping determines if we are grouping the report by either group_by1,
1501 // group_by2, or group_by3 values passed in $options.
1502 static function grouping($options) {
1503 $grouping = ($options['group_by1'] != null && $options['group_by1'] != 'no_grouping') ||
1504 ($options['group_by2'] != null && $options['group_by2'] != 'no_grouping') ||
1505 ($options['group_by3'] != null && $options['group_by3'] != 'no_grouping');
1509 // groupingBy determines if we are grouping a report by a value of $what
1510 // ('date', 'user', 'project', etc.) by checking group_by1, group_by2,
1511 // and group_by3 values passed in $options.
1512 static function groupingBy($what, $options) {
1513 $grouping = ($options['group_by1'] == $what) || ($options['group_by2'] == $what) || ($options['group_by3'] == $what);
1517 // makeGroupByHeader builds a column header for a totals-only report using group_by1,
1518 // group_by2, and group_by3 values passed in $options.
1519 static function makeGroupByHeader($options) {
1521 global $custom_fields;
1523 $no_grouping = ($options['group_by1'] == null || $options['group_by1'] == 'no_grouping') &&
1524 ($options['group_by2'] == null || $options['group_by2'] == 'no_grouping') &&
1525 ($options['group_by3'] == null || $options['group_by3'] == 'no_grouping');
1526 if ($no_grouping) return null;
1528 if ($options['group_by1'] != null && $options['group_by1'] != 'no_grouping') {
1529 // We have group_by1.
1530 $group_by1 = $options['group_by1'];
1531 if ('cf_1' == $group_by1)
1532 $group_by_header .= ' - '.$custom_fields->fields[0]['label'];
1534 $key = 'label.'.$group_by1;
1535 $group_by_header .= ' - '.$i18n->get($key);
1538 if ($options['group_by2'] != null && $options['group_by2'] != 'no_grouping') {
1539 // We have group_by2.
1540 $group_by2 = $options['group_by2'];
1541 if ('cf_1' == $group_by2)
1542 $group_by_header .= ' - '.$custom_fields->fields[0]['label'];
1544 $key = 'label.'.$group_by2;
1545 $group_by_header .= ' - '.$i18n->get($key);
1548 if ($options['group_by3'] != null && $options['group_by3'] != 'no_grouping') {
1549 // We have group_by3.
1550 $group_by3 = $options['group_by3'];
1551 if ('cf_1' == $group_by3)
1552 $group_by_header .= ' - '.$custom_fields->fields[0]['label'];
1554 $key = 'label.'.$group_by3;
1555 $group_by_header .= ' - '.$i18n->get($key);
1558 $group_by_header = ltrim($group_by_header, ' -');
1559 return $group_by_header;
1562 // makeGroupByXmlTag creates an xml tag for a totals only report using group_by1,
1563 // group_by2, and group_by3 values passed in $options.
1564 static function makeGroupByXmlTag($options) {
1565 if ($options['group_by1'] != null && $options['group_by1'] != 'no_grouping') {
1566 // We have group_by1.
1567 $tag .= '_'.$options['group_by1'];
1569 if ($options['group_by2'] != null && $options['group_by2'] != 'no_grouping') {
1570 // We have group_by2.
1571 $tag .= '_'.$options['group_by2'];
1573 if ($options['group_by3'] != null && $options['group_by3'] != 'no_grouping') {
1574 // We have group_by3.
1575 $tag .= '_'.$options['group_by3'];
1577 $tag = ltrim($tag, '_');
1581 // makeGroupByLabel builds a label for one row in a "Totals only" report of grouped by items.
1582 // It does one thing: if we are grouping by date, the date format is converted for user.
1583 static function makeGroupByLabel($key, $options) {
1584 if (!ttReportHelper::groupingBy('date', $options))
1585 return $key; // No need to format.
1588 if ($user->date_format == DB_DATEFORMAT)
1589 return $key; // No need to format.
1592 if (preg_match('/\d\d\d\d-\d\d-\d\d/', $key, $matches)) {
1593 // Replace the first found match of a date in DB_DATEFORMAT.
1594 // This is not entirely clean but better than nothing for a label in a row.
1595 $userDate = ttDateToUserFormat($matches[0]);
1596 $label = str_replace($matches[0], $userDate, $key);