2 // +----------------------------------------------------------------------+
3 // | Anuko Time Tracker
4 // +----------------------------------------------------------------------+
5 // | Copyright (c) Anuko International Ltd. (https://www.anuko.com)
6 // +----------------------------------------------------------------------+
7 // | LIBERAL FREEWARE LICENSE: This source code document may be used
8 // | by anyone for any purpose, and freely redistributed alone or in
9 // | combination with other software, provided that the license is obeyed.
11 // | There are only two ways to violate the license:
13 // | 1. To redistribute this code in source form, with the copyright
14 // | notice or license removed or altered. (Distributing in compiled
15 // | forms without embedded copyright notices is permitted).
17 // | 2. To redistribute modified versions of this code in *any* form
18 // | that bears insufficient indications that the modifications are
19 // | not the work of the original author(s).
21 // | This license applies to this document only, not any other software
22 // | that it may be combined with.
24 // +----------------------------------------------------------------------+
26 // | https://www.anuko.com/time_tracker/credits.htm
27 // +----------------------------------------------------------------------+
29 import('ttClientHelper');
30 import('DateAndTime');
32 import('ttTimeHelper');
34 require_once(dirname(__FILE__).'/../../plugins/CustomFields.class.php');
36 // Definitions of types for timesheet dropdown.
37 define('TIMESHEET_ALL', 0); // Include all records.
38 define('TIMESHEET_NOT_ASSIGNED', 1); // Include records not assigned to timesheets.
39 define('TIMESHEET_ASSIGNED', 2); // Include records assigned to timesheets.
40 define('TIMESHEET_PENDING', 3); // Include records in submitted timesheets that are pending manager approval.
41 define('TIMESHEET_APPROVED', 4); // Include records in approved timesheets.
42 define('TIMESHEET_NOT_APPROVED', 5); // Include records in disapproved timesheets.
44 // Class ttReportHelper is used for help with reports.
45 class ttReportHelper {
47 // getWhere prepares a WHERE clause for a report query.
48 static function getWhere($options) {
51 $group_id = $user->getGroup();
52 $org_id = $user->org_id;
54 // A shortcut for timesheets.
55 if ($options['timesheet_id']) {
56 $where = " where l.timesheet_id = ".$options['timesheet_id']." and l.group_id = $group_id and l.org_id = $org_id";
60 // Prepare dropdown parts.
62 if ($options['client_id'])
63 $dropdown_parts .= ' and l.client_id = '.$options['client_id'];
64 elseif ($user->isClient() && $user->client_id)
65 $dropdown_parts .= ' and l.client_id = '.$user->client_id;
66 if ($options['cf_1_option_id']) $dropdown_parts .= ' and l.id in(select log_id from tt_custom_field_log where status = 1 and option_id = '.$options['cf_1_option_id'].')';
67 if ($options['project_id']) $dropdown_parts .= ' and l.project_id = '.$options['project_id'];
68 if ($options['task_id']) $dropdown_parts .= ' and l.task_id = '.$options['task_id'];
69 if ($options['billable']=='1') $dropdown_parts .= ' and l.billable = 1';
70 if ($options['billable']=='2') $dropdown_parts .= ' and l.billable = 0';
71 if ($options['invoice']=='1') $dropdown_parts .= ' and l.invoice_id is not null';
72 if ($options['invoice']=='2') $dropdown_parts .= ' and l.invoice_id is null';
73 if ($options['timesheet']==TIMESHEET_NOT_ASSIGNED) $dropdown_parts .= ' and l.timesheet_id is null';
74 if ($options['timesheet']==TIMESHEET_ASSIGNED) $dropdown_parts .= ' and l.timesheet_id is not null';
75 if ($options['paid_status']=='1') $dropdown_parts .= ' and l.paid = 1';
76 if ($options['paid_status']=='2') $dropdown_parts .= ' and l.paid = 0';
78 // Prepare sql query part for user list.
79 $userlist = $options['users'] ? $options['users'] : '-1';
80 if ($user->can('view_reports') || $user->can('view_all_reports') || $user->isClient())
81 $user_list_part = " and l.user_id in ($userlist)";
83 $user_list_part = " and l.user_id = ".$user->getUser();
84 $user_list_part .= " and l.group_id = $group_id and l.org_id = $org_id";
86 // Prepare sql query part for where.
87 $dateFormat = $user->getDateFormat();
88 if ($options['period'])
89 $period = new Period($options['period'], new DateAndTime($dateFormat));
91 $period = new Period();
93 new DateAndTime($dateFormat, $options['period_start']),
94 new DateAndTime($dateFormat, $options['period_end']));
96 $where = " where l.status = 1 and l.date >= '".$period->getStartDate(DB_DATEFORMAT)."' and l.date <= '".$period->getEndDate(DB_DATEFORMAT)."'".
97 " $user_list_part $dropdown_parts";
101 // getExpenseWhere prepares WHERE clause for expenses query in a report.
102 static function getExpenseWhere($options) {
105 $group_id = $user->getGroup();
106 $org_id = $user->org_id;
108 // A shortcut for timesheets.
109 if ($options['timesheet_id']) {
110 $where = " where ei.timesheet_id = ".$options['timesheet_id']." and ei.group_id = $group_id and ei.org_id = $org_id";
114 // Prepare dropdown parts.
115 $dropdown_parts = '';
116 if ($options['client_id'])
117 $dropdown_parts .= ' and ei.client_id = '.$options['client_id'];
118 elseif ($user->isClient() && $user->client_id)
119 $dropdown_parts .= ' and ei.client_id = '.$user->client_id;
120 if ($options['project_id']) $dropdown_parts .= ' and ei.project_id = '.$options['project_id'];
121 if ($options['invoice']=='1') $dropdown_parts .= ' and ei.invoice_id is not null';
122 if ($options['invoice']=='2') $dropdown_parts .= ' and ei.invoice_id is null';
123 if ($options['timesheet']==TIMESHEET_NOT_ASSIGNED) $dropdown_parts .= ' and ei.timesheet_id is null';
124 if ($options['timesheet']==TIMESHEET_ASSIGNED) $dropdown_parts .= ' and ei.timesheet_id is not null';
125 if ($options['paid_status']=='1') $dropdown_parts .= ' and ei.paid = 1';
126 if ($options['paid_status']=='2') $dropdown_parts .= ' and ei.paid = 0';
128 // Prepare sql query part for user list.
129 $userlist = $options['users'] ? $options['users'] : '-1';
130 if ($user->can('view_reports') || $user->can('view_all_reports') || $user->isClient())
131 $user_list_part = " and ei.user_id in ($userlist)";
133 $user_list_part = " and ei.user_id = ".$user->getUser();
134 $user_list_part .= " and ei.group_id = $group_id and ei.org_id = $org_id";
136 // Prepare sql query part for where.
137 $dateFormat = $user->getDateFormat();
138 if ($options['period'])
139 $period = new Period($options['period'], new DateAndTime($dateFormat));
141 $period = new Period();
143 new DateAndTime($dateFormat, $options['period_start']),
144 new DateAndTime($dateFormat, $options['period_end']));
146 $where = " where ei.status = 1 and ei.date >= '".$period->getStartDate(DB_DATEFORMAT)."' and ei.date <= '".$period->getEndDate(DB_DATEFORMAT)."'".
147 " $user_list_part $dropdown_parts";
151 // getItems retrieves all items associated with a report.
152 // It combines tt_log and tt_expense_items in one array for presentation in one table using mysql union all.
153 // Expense items use the "note" field for item name.
154 static function getItems($options) {
156 $mdb2 = getConnection();
158 // Determine these once as they are used in multiple places in this function.
159 $canViewReports = $user->can('view_reports') || $user->can('view_all_reports');
160 $isClient = $user->isClient();
162 $grouping = ttReportHelper::grouping($options);
164 $grouping_by_date = ttReportHelper::groupingBy('date', $options);
165 $grouping_by_client = ttReportHelper::groupingBy('client', $options);
166 $grouping_by_project = ttReportHelper::groupingBy('project', $options);
167 $grouping_by_task = ttReportHelper::groupingBy('task', $options);
168 $grouping_by_user = ttReportHelper::groupingBy('user', $options);
169 $grouping_by_cf_1 = ttReportHelper::groupingBy('cf_1', $options);
171 $convertTo12Hour = ('%I:%M %p' == $user->getTimeFormat()) && ($options['show_start'] || $options['show_end']);
172 $trackingMode = $user->getTrackingMode();
173 $decimalMark = $user->getDecimalMark();
175 // Prepare a query for time items in tt_log table.
176 $fields = array(); // An array of fields for database query.
177 array_push($fields, 'l.id');
178 array_push($fields, 'l.user_id');
179 array_push($fields, '1 as type'); // Type 1 is for tt_log entries.
180 array_push($fields, 'l.date');
181 if($canViewReports || $isClient)
182 array_push($fields, 'u.name as user');
183 // Add client name if it is selected.
184 if ($options['show_client'] || $grouping_by_client)
185 array_push($fields, 'c.name as client');
186 // Add project name if it is selected.
187 if ($options['show_project'] || $grouping_by_project)
188 array_push($fields, 'p.name as project');
189 // Add task name if it is selected.
190 if ($options['show_task'] || $grouping_by_task)
191 array_push($fields, 't.name as task');
193 $include_cf_1 = $options['show_custom_field_1'] || $grouping_by_cf_1;
195 $custom_fields = new CustomFields();
196 $cf_1_type = $custom_fields->fields[0]['type'];
197 if ($cf_1_type == CustomFields::TYPE_TEXT) {
198 array_push($fields, 'cfl.value as cf_1');
199 } elseif ($cf_1_type == CustomFields::TYPE_DROPDOWN) {
200 array_push($fields, 'cfo.value as cf_1');
204 if ($options['show_start']) {
205 array_push($fields, "l.start as unformatted_start");
206 array_push($fields, "TIME_FORMAT(l.start, '%k:%i') as start");
209 if ($options['show_end'])
210 array_push($fields, "TIME_FORMAT(sec_to_time(time_to_sec(l.start) + time_to_sec(l.duration)), '%k:%i') as finish");
212 if ($options['show_duration'])
213 array_push($fields, "TIME_FORMAT(l.duration, '%k:%i') as duration");
215 if ($options['show_work_units']) {
216 if ($user->getConfigOption('unit_totals_only'))
217 array_push($fields, "null as units");
219 $firstUnitThreshold = $user->getConfigInt('1st_unit_threshold', 0);
220 $minutesInUnit = $user->getConfigInt('minutes_in_unit', 15);
221 array_push($fields, "if(l.billable = 0 or time_to_sec(l.duration)/60 < $firstUnitThreshold, 0, ceil(time_to_sec(l.duration)/60/$minutesInUnit)) as units");
225 if ($options['show_note'])
226 array_push($fields, 'l.comment as note');
228 $includeCost = $options['show_cost'];
230 if (MODE_TIME == $trackingMode)
231 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.
233 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.
234 array_push($fields, "null as expense");
237 if ($canViewReports && $options['show_paid'])
238 array_push($fields, 'l.paid');
240 if ($canViewReports && $options['show_ip']) {
241 array_push($fields, 'l.created');
242 array_push($fields, 'l.created_ip');
243 array_push($fields, 'l.modified');
244 array_push($fields, 'l.modified_ip');
246 // Add invoice name if it is selected.
247 if (($canViewReports || $isClient) && $options['show_invoice'])
248 array_push($fields, 'i.name as invoice');
249 // Add timesheet name if it is selected.
250 if ($options['show_timesheet'])
251 array_push($fields, 'ts.name as timesheet_name');
253 // Prepare sql query part for left joins.
255 if ($options['show_client'] || $grouping_by_client)
256 $left_joins .= " left join tt_clients c on (c.id = l.client_id)";
257 if (($canViewReports || $isClient) && $options['show_invoice'])
258 $left_joins .= " left join tt_invoices i on (i.id = l.invoice_id and i.status = 1)";
259 if ($canViewReports || $isClient || $user->isPluginEnabled('ex'))
260 $left_joins .= " left join tt_users u on (u.id = l.user_id)";
261 if ($options['show_project'] || $grouping_by_project)
262 $left_joins .= " left join tt_projects p on (p.id = l.project_id)";
263 if ($options['show_task'] || $grouping_by_task)
264 $left_joins .= " left join tt_tasks t on (t.id = l.task_id)";
266 if ($cf_1_type == CustomFields::TYPE_TEXT)
267 $left_joins .= " left join tt_custom_field_log cfl on (l.id = cfl.log_id and cfl.status = 1)";
268 elseif ($cf_1_type == CustomFields::TYPE_DROPDOWN) {
269 $left_joins .= " left join tt_custom_field_log cfl on (l.id = cfl.log_id and cfl.status = 1)".
270 " left join tt_custom_field_options cfo on (cfl.option_id = cfo.id)";
273 if ($includeCost && MODE_TIME != $trackingMode)
274 $left_joins .= " left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id)";
276 // Prepare sql query part for inner joins.
278 if ($user->isPluginEnabled('ts')) {
279 $timesheet_option = $options['timesheet'];
280 if ($timesheet_option == TIMESHEET_PENDING)
281 $inner_joins .= " inner join tt_timesheets ts on (l.timesheet_id = ts.id and ts.submit_status = 1 and ts.approval_status is null)";
282 else if ($timesheet_option == TIMESHEET_APPROVED)
283 $inner_joins .= " inner join tt_timesheets ts on (l.timesheet_id = ts.id and ts.approval_status = 1)";
284 else if ($timesheet_option == TIMESHEET_NOT_APPROVED)
285 $inner_joins .= " inner join tt_timesheets ts on (l.timesheet_id = ts.id and ts.approval_status = 0)";
286 else if ($options['show_timesheet'])
287 $inner_joins .= " left join tt_timesheets ts on (l.timesheet_id = ts.id)"; // Left join for timesheet nme.
290 $where = ttReportHelper::getWhere($options);
292 // Construct sql query for tt_log items.
293 $sql = "select ".join(', ', $fields)." from tt_log l $left_joins $inner_joins $where";
294 // If we don't have expense items (such as when the Expenses plugin is disabled), the above is all sql we need,
295 // with an exception of sorting part, that is added in the end.
297 // However, when we have expenses, we need to do a union with a separate query for expense items from tt_expense_items table.
298 if ($options['show_cost'] && $user->isPluginEnabled('ex')) { // if ex(penses) plugin is enabled
300 $fields = array(); // An array of fields for database query.
301 array_push($fields, 'ei.id');
302 array_push($fields, 'ei.user_id');
303 array_push($fields, '2 as type'); // Type 2 is for tt_expense_items entries.
304 array_push($fields, 'ei.date');
305 if($canViewReports || $isClient)
306 array_push($fields, 'u.name as user');
307 // Add client name if it is selected.
308 if ($options['show_client'] || $grouping_by_client)
309 array_push($fields, 'c.name as client');
310 // Add project name if it is selected.
311 if ($options['show_project'] || $grouping_by_project)
312 array_push($fields, 'p.name as project');
313 if ($options['show_task'] || $grouping_by_task)
314 array_push($fields, 'null'); // null for task name. We need to match column count for union.
315 if ($options['show_custom_field_1'] || $grouping_by_cf_1)
316 array_push($fields, 'null'); // null for cf_1.
317 if ($options['show_start']) {
318 array_push($fields, 'null'); // null for unformatted_start.
319 array_push($fields, 'null'); // null for start.
321 if ($options['show_end'])
322 array_push($fields, 'null'); // null for finish.
323 if ($options['show_duration'])
324 array_push($fields, 'null'); // null for duration.
325 if ($options['show_work_units'])
326 array_push($fields, 'null as units'); // null for work units.
327 // Use the note field to print item name.
328 if ($options['show_note'])
329 array_push($fields, 'ei.name as note');
330 array_push($fields, 'ei.cost as cost');
331 array_push($fields, 'ei.cost as expense');
333 if ($canViewReports && $options['show_paid'])
334 array_push($fields, 'ei.paid');
336 if ($canViewReports && $options['show_ip']) {
337 array_push($fields, 'ei.created');
338 array_push($fields, 'ei.created_ip');
339 array_push($fields, 'ei.modified');
340 array_push($fields, 'ei.modified_ip');
342 // Add invoice name if it is selected.
343 if (($canViewReports || $isClient) && $options['show_invoice'])
344 array_push($fields, 'i.name as invoice');
345 if ($options['show_timesheet'])
346 array_push($fields, 'ts.name as timesheet_name');
348 // Prepare sql query part for left joins.
350 if ($canViewReports || $isClient)
351 $left_joins .= " left join tt_users u on (u.id = ei.user_id)";
352 if ($options['show_client'] || $grouping_by_client)
353 $left_joins .= " left join tt_clients c on (c.id = ei.client_id)";
354 if ($options['show_project'] || $grouping_by_project)
355 $left_joins .= " left join tt_projects p on (p.id = ei.project_id)";
356 if (($canViewReports || $isClient) && $options['show_invoice'])
357 $left_joins .= " left join tt_invoices i on (i.id = ei.invoice_id and i.status = 1)";
359 // Prepare sql query part for inner joins.
361 if ($user->isPluginEnabled('ts')) {
362 $timesheet_option = $options['timesheet'];
363 if ($timesheet_option == TIMESHEET_PENDING)
364 $inner_joins .= " inner join tt_timesheets ts on (ei.timesheet_id = ts.id and ts.submit_status = 1 and ts.approval_status is null)";
365 else if ($timesheet_option == TIMESHEET_APPROVED)
366 $inner_joins .= " inner join tt_timesheets ts on (ei.timesheet_id = ts.id and ts.approval_status = 1)";
367 else if ($timesheet_option == TIMESHEET_NOT_APPROVED)
368 $inner_joins .= " inner join tt_timesheets ts on (ei.timesheet_id = ts.id and ts.approval_status = 0)";
369 else if ($options['show_timesheet'])
370 $inner_joins .= " left join tt_timesheets ts on (ei.timesheet_id = ts.id)"; // Left join for timesheet name.
373 $where = ttReportHelper::getExpenseWhere($options);
375 // Construct sql query for expense items.
376 $sql_for_expense_items = "select ".join(', ', $fields)." from tt_expense_items ei $left_joins $inner_joins $where";
378 // Construct a union.
379 $sql = "($sql) union all ($sql_for_expense_items)";
382 // Determine sort part.
383 $sort_part = ' order by ';
385 $sort_part2 .= ($options['group_by1'] != null && $options['group_by1'] != 'no_grouping') ? ', '.$options['group_by1'] : '';
386 $sort_part2 .= ($options['group_by2'] != null && $options['group_by2'] != 'no_grouping') ? ', '.$options['group_by2'] : '';
387 $sort_part2 .= ($options['group_by3'] != null && $options['group_by3'] != 'no_grouping') ? ', '.$options['group_by3'] : '';
388 if (!$grouping_by_date) $sort_part2 .= ', date';
389 $sort_part .= ltrim($sort_part2, ', '); // Remove leading comma and space.
391 $sort_part .= 'date';
393 if (($canViewReports || $isClient) && $options['users'] && !$grouping_by_user)
394 $sort_part .= ', user, type';
395 if ($options['show_start'])
396 $sort_part .= ', unformatted_start';
397 $sort_part .= ', id';
400 // By now we are ready with sql.
402 // Obtain items for report.
403 $res = $mdb2->query($sql);
404 if (is_a($res, 'PEAR_Error')) die($res->getMessage());
406 while ($val = $res->fetchRow()) {
407 if ($convertTo12Hour) {
408 if($val['start'] != '')
409 $val['start'] = ttTimeHelper::to12HourFormat($val['start']);
410 if($val['finish'] != '')
411 $val['finish'] = ttTimeHelper::to12HourFormat($val['finish']);
413 if (isset($val['cost'])) {
414 if ('.' != $decimalMark)
415 $val['cost'] = str_replace('.', $decimalMark, $val['cost']);
417 if (isset($val['expense'])) {
418 if ('.' != $decimalMark)
419 $val['expense'] = str_replace('.', $decimalMark, $val['expense']);
422 if ($grouping) $val['grouped_by'] = ttReportHelper::makeGroupByKey($options, $val);
423 $val['date'] = ttDateToUserFormat($val['date']);
425 $report_items[] = $val;
428 return $report_items;
431 // putInSession stores tt_log and tt_expense_items ids from a report in user session
432 // as 2 comma-separated lists.
433 static function putInSession($report_items) {
434 unset($_SESSION['report_item_ids']);
435 unset($_SESSION['report_item_expense_ids']);
437 // Iterate through records and build 2 comma-separated lists.
438 foreach($report_items as $item) {
439 if ($item['type'] == 1)
440 $report_item_ids .= ','.$item['id'];
441 else if ($item['type'] == 2)
442 $report_item_expense_ids .= ','.$item['id'];
444 $report_item_ids = trim($report_item_ids, ',');
445 $report_item_expense_ids = trim($report_item_expense_ids, ',');
447 // The lists are reqdy. Put them in session.
448 if ($report_item_ids) $_SESSION['report_item_ids'] = $report_item_ids;
449 if ($report_item_expense_ids) $_SESSION['report_item_expense_ids'] = $report_item_expense_ids;
452 // getFromSession obtains tt_log and tt_expense_items ids stored in user session.
453 static function getFromSession() {
455 $report_item_ids = $_SESSION['report_item_ids'];
456 if ($report_item_ids)
457 $items['report_item_ids'] = explode(',', $report_item_ids);
458 $report_item_expense_ids = $_SESSION['report_item_expense_ids'];
459 if ($report_item_expense_ids)
460 $items['report_item_expense_ids'] = explode(',', $report_item_expense_ids);
464 // getSubtotals calculates report items subtotals when a report is grouped by.
465 // Without expenses, it's a simple select with group by.
466 // With expenses, it becomes a select with group by from a combined set of records obtained with "union all".
467 static function getSubtotals($options) {
469 $mdb2 = getConnection();
471 $concat_part = ttReportHelper::makeConcatPart($options);
472 $work_unit_part = ttReportHelper::makeWorkUnitPart($options);
473 $join_part = ttReportHelper::makeJoinPart($options);
474 $cost_part = ttReportHelper::makeCostPart($options);
475 $where = ttReportHelper::getWhere($options);
476 $group_by_part = ttReportHelper::makeGroupByPart($options);
478 $parts = "$concat_part, sum(time_to_sec(l.duration)) as time, null as expenses".$work_unit_part.$cost_part;
479 $sql = "select $parts from tt_log l $join_part $where $group_by_part";
480 // By now we have sql for time items.
482 // However, when we have expenses, we need to do a union with a separate query for expense items from tt_expense_items table.
483 if ($options['show_cost'] && $user->isPluginEnabled('ex')) { // if ex(penses) plugin is enabled
485 $concat_part = ttReportHelper::makeConcatExpensesPart($options);
486 $join_part = ttReportHelper::makeJoinExpensesPart($options);
487 $where = ttReportHelper::getExpenseWhere($options);
488 $group_by_expenses_part = ttReportHelper::makeGroupByExpensesPart($options);
489 $sql_for_expenses = "select $concat_part, null as time";
490 if ($options['show_work_units']) $sql_for_expenses .= ", null as units";
491 $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";
493 // Create a combined query.
494 $fields = ttReportHelper::makeCombinedSelectPart($options);
495 $combined = "select $fields, sum(time) as time";
496 if ($options['show_work_units']) $combined .= ", sum(units) as units";
497 $combined .= ", sum(cost) as cost, sum(expenses) as expenses from (($sql) union all ($sql_for_expenses)) t group by $fields";
502 $res = $mdb2->query($sql);
503 if (is_a($res, 'PEAR_Error')) die($res->getMessage());
504 while ($val = $res->fetchRow()) {
505 $time = $val['time'] ? sec_to_time_fmt_hm($val['time']) : null;
506 $rowLabel = ttReportHelper::makeGroupByLabel($val['group_field'], $options);
507 if ($options['show_cost']) {
508 $decimalMark = $user->getDecimalMark();
509 if ('.' != $decimalMark) {
510 $val['cost'] = str_replace('.', $decimalMark, $val['cost']);
511 $val['expenses'] = str_replace('.', $decimalMark, $val['expenses']);
513 $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']);
515 $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']);
521 // getTotals calculates total hours and cost for all report items.
522 static function getTotals($options)
525 $mdb2 = getConnection();
527 $trackingMode = $user->getTrackingMode();
528 $decimalMark = $user->getDecimalMark();
529 $where = ttReportHelper::getWhere($options);
532 $time_part = "sum(time_to_sec(l.duration)) as time";
533 if ($options['show_work_units']) {
534 $unitTotalsOnly = $user->getConfigOption('unit_totals_only');
535 $firstUnitThreshold = $user->getConfigInt('1st_unit_threshold', 0);
536 $minutesInUnit = $user->getConfigInt('minutes_in_unit', 15);
537 $units_part = $unitTotalsOnly ? ", null as units" : ", sum(if(l.billable = 0 or time_to_sec(l.duration)/60 < $firstUnitThreshold, 0, ceil(time_to_sec(l.duration)/60/$minutesInUnit))) as units";
539 if ($options['show_cost']) {
540 if (MODE_TIME == $trackingMode)
541 $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";
543 $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";
545 $cost_part = ", null as cost, null as expenses";
547 if ($options['show_cost']) {
548 if (MODE_TIME == $trackingMode) {
549 $left_joins = "left join tt_users u on (l.user_id = u.id)";
551 $left_joins = "left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id)";
554 // Prepare sql query part for inner joins.
556 if ($user->isPluginEnabled('ts') && $options['timesheet']) {
557 $timesheet_option = $options['timesheet'];
558 if ($timesheet_option == TIMESHEET_PENDING)
559 $inner_joins .= " inner join tt_timesheets ts on (l.timesheet_id = ts.id and ts.submit_status = 1 and ts.approval_status is null)";
560 else if ($timesheet_option == TIMESHEET_APPROVED)
561 $inner_joins .= " inner join tt_timesheets ts on (l.timesheet_id = ts.id and ts.approval_status = 1)";
562 else if ($timesheet_option == TIMESHEET_NOT_APPROVED)
563 $inner_joins .= " inner join tt_timesheets ts on (l.timesheet_id = ts.id and ts.approval_status = 0)";
565 // Prepare a query for time items.
566 $sql = "select $time_part $units_part $cost_part from tt_log l $left_joins $inner_joins $where";
568 // If we have expenses, query becomes a bit more complex.
569 if ($options['show_cost'] && $user->isPluginEnabled('ex')) {
570 // Prepare sql query part for inner joins.
572 if ($user->isPluginEnabled('ts') && $options['timesheet']) {
573 $timesheet_option = $options['timesheet'];
574 if ($timesheet_option == TIMESHEET_PENDING)
575 $inner_joins .= " inner join tt_timesheets ts on (ei.timesheet_id = ts.id and ts.submit_status = 1 and ts.approval_status is null)";
576 else if ($timesheet_option == TIMESHEET_APPROVED)
577 $inner_joins .= " inner join tt_timesheets ts on (ei.timesheet_id = ts.id and ts.approval_status = 1)";
578 else if ($timesheet_option == TIMESHEET_NOT_APPROVED)
579 $inner_joins .= " inner join tt_timesheets ts on (ei.timesheet_id = ts.id and ts.approval_status = 0)";
581 $where = ttReportHelper::getExpenseWhere($options);
582 $sql_for_expenses = "select null as time";
583 if ($options['show_work_units']) $sql_for_expenses .= ", null as units";
584 $sql_for_expenses .= ", sum(cost) as cost, sum(cost) as expenses from tt_expense_items ei $inner_joins $where";
586 // Create a combined query.
587 $combined = "select sum(time) as time";
588 if ($options['show_work_units']) $combined .= ", sum(units) as units";
589 $combined .= ", sum(cost) as cost, sum(expenses) as expenses from (($sql) union all ($sql_for_expenses)) t";
594 $res = $mdb2->query($sql);
595 if (is_a($res, 'PEAR_Error')) die($res->getMessage());
597 $val = $res->fetchRow();
598 $total_time = $val['time'] ? sec_to_time_fmt_hm($val['time']) : null;
599 if ($options['show_cost']) {
600 $total_cost = $val['cost'];
601 if (!$total_cost) $total_cost = '0.00';
602 if ('.' != $decimalMark)
603 $total_cost = str_replace('.', $decimalMark, $total_cost);
604 $total_expenses = $val['expenses'];
605 if (!$total_expenses) $total_expenses = '0.00';
606 if ('.' != $decimalMark)
607 $total_expenses = str_replace('.', $decimalMark, $total_expenses);
610 $dateFormat = $user->getDateFormat();
611 if ($options['period'])
612 $period = new Period($options['period'], new DateAndTime($dateFormat));
614 $period = new Period();
616 new DateAndTime($dateFormat, $options['period_start']),
617 new DateAndTime($dateFormat, $options['period_end']));
620 $totals['start_date'] = $period->getStartDate();
621 $totals['end_date'] = $period->getEndDate();
622 $totals['time'] = $total_time;
623 $totals['units'] = $val['units'];
624 $totals['cost'] = $total_cost;
625 $totals['expenses'] = $total_expenses;
630 // The assignToInvoice assigns a set of records to a specific invoice.
631 static function assignToInvoice($invoice_id, $time_log_ids, $expense_item_ids) {
633 $mdb2 = getConnection();
635 $group_id = $user->getGroup();
636 $org_id = $user->org_id;
639 $sql = "update tt_log set invoice_id = ".$mdb2->quote($invoice_id).
640 " where id in(".join(', ', $time_log_ids).") and group_id = $group_id and org_id = $org_id";
641 $affected = $mdb2->exec($sql);
642 if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
644 if ($expense_item_ids) {
645 $sql = "update tt_expense_items set invoice_id = ".$mdb2->quote($invoice_id).
646 " where id in(".join(', ', $expense_item_ids).") and group_id = $group_id and org_id = $org_id";
647 $affected = $mdb2->exec($sql);
648 if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
652 // The markPaid marks a set of records as either paid or unpaid.
653 static function markPaid($time_log_ids, $expense_item_ids, $paid = true) {
655 $mdb2 = getConnection();
657 $group_id = $user->getGroup();
658 $org_id = $user->org_id;
660 $paid_val = (int) $paid;
662 $sql = "update tt_log set paid = $paid_val".
663 " where id in(".join(', ', $time_log_ids).") and group_id = $group_id and org_id = $org_id";
664 $affected = $mdb2->exec($sql);
665 if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
667 if ($expense_item_ids) {
668 $sql = "update tt_expense_items set paid = $paid_val".
669 " where id in(".join(', ', $expense_item_ids).") and group_id = $group_id and org_id = $org_id";
670 $affected = $mdb2->exec($sql);
671 if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
675 // prepareReportBody - prepares an email body for report.
676 static function prepareReportBody($options, $comment = null)
681 // Determine these once as they are used in multiple places in this function.
682 $canViewReports = $user->can('view_reports') || $user->can('view_all_reports');
683 $isClient = $user->isClient();
685 $items = ttReportHelper::getItems($options);
686 $grouping = ttReportHelper::grouping($options);
688 $subtotals = ttReportHelper::getSubtotals($options);
689 $totals = ttReportHelper::getTotals($options);
691 // Use custom fields plugin if it is enabled.
692 if ($user->isPluginEnabled('cf'))
693 $custom_fields = new CustomFields();
695 // Define some styles to use in email.
696 $style_title = 'text-align: center; font-size: 15pt; font-family: Arial, Helvetica, sans-serif;';
697 $tableHeader = 'font-weight: bold; background-color: #a6ccf7; text-align: left;';
698 $tableHeaderCentered = 'font-weight: bold; background-color: #a6ccf7; text-align: center;';
699 $rowItem = 'background-color: #ffffff;';
700 $rowItemAlt = 'background-color: #f5f5f5;';
701 $rowSubtotal = 'background-color: #e0e0e0;';
702 $cellLeftAligned = 'text-align: left; vertical-align: top;';
703 $cellRightAligned = 'text-align: right; vertical-align: top;';
704 $cellLeftAlignedSubtotal = 'font-weight: bold; text-align: left; vertical-align: top;';
705 $cellRightAlignedSubtotal = 'font-weight: bold; text-align: right; vertical-align: top;';
707 // Start creating email body.
709 $body .= '<head><meta http-equiv="content-type" content="text/html; charset='.CHARSET.'"></head>';
713 $body .= '<p style="'.$style_title.'">'.$i18n->get('form.mail.report_subject').': '.$totals['start_date'].' - '.$totals['end_date'].'</p>';
716 if ($comment) $body .= '<p>'.htmlspecialchars($comment).'</p>';
718 if ($options['show_totals_only']) {
719 // Totals only report. Output subtotals.
720 $group_by_header = ttReportHelper::makeGroupByHeader($options);
722 $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
724 $body .= '<td style="'.$tableHeader.'">'.$group_by_header.'</td>';
725 if ($options['show_duration'])
726 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.duration').'</td>';
727 if ($options['show_work_units'])
728 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.work_units_short').'</td>';
729 if ($options['show_cost'])
730 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.cost').'</td>';
732 foreach($subtotals as $subtotal) {
733 $body .= '<tr style="'.$rowSubtotal.'">';
734 $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($subtotal['name'] ? htmlspecialchars($subtotal['name']) : ' ').'</td>';
735 if ($options['show_duration']) {
736 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
737 if ($subtotal['time'] <> '0:00') $body .= $subtotal['time'];
740 if ($options['show_work_units']) {
741 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
742 $body .= $subtotal['units'];
745 if ($options['show_cost']) {
746 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
747 $body .= ($canViewReports || $isClient) ? $subtotal['cost'] : $subtotal['expenses'];
754 $body .= '<tr><td> </td></tr>';
755 $body .= '<tr style="'.$rowSubtotal.'">';
756 $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.total').'</td>';
757 if ($options['show_duration']) {
758 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
759 if ($totals['time'] <> '0:00') $body .= $totals['time'];
762 if ($options['show_work_units']) {
763 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
764 $body .= $totals['units'];
767 if ($options['show_cost']) {
768 $body .= '<td nowrap style="'.$cellRightAlignedSubtotal.'">'.htmlspecialchars($user->currency).' ';
769 $body .= ($canViewReports || $isClient) ? $totals['cost'] : $totals['expenses'];
778 // Print table header.
779 $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
781 $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.date').'</td>';
782 if ($canViewReports || $isClient)
783 $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.user').'</td>';
784 if ($options['show_client'])
785 $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.client').'</td>';
786 if ($options['show_project'])
787 $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.project').'</td>';
788 if ($options['show_task'])
789 $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.task').'</td>';
790 if ($options['show_custom_field_1'])
791 $body .= '<td style="'.$tableHeader.'">'.htmlspecialchars($custom_fields->fields[0]['label']).'</td>';
792 if ($options['show_start'])
793 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.start').'</td>';
794 if ($options['show_end'])
795 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.finish').'</td>';
796 if ($options['show_duration'])
797 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.duration').'</td>';
798 if ($options['show_work_units'])
799 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.work_units_short').'</td>';
800 if ($options['show_note'])
801 $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.note').'</td>';
802 if ($options['show_cost'])
803 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.cost').'</td>';
804 if ($options['show_paid'])
805 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.paid').'</td>';
806 if ($options['show_ip'])
807 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.ip').'</td>';
808 if ($options['show_invoice'])
809 $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.invoice').'</td>';
812 // Initialize variables to print subtotals.
813 if ($items && $grouping) {
814 $print_subtotals = true;
816 $prev_grouped_by = '';
817 $cur_grouped_by = '';
819 // Initialize variables to alternate color of rows for different dates.
822 $row_style = $rowItem;
824 // Print report items.
825 if (is_array($items)) {
826 foreach ($items as $record) {
827 $cur_date = $record['date'];
828 // Print a subtotal row after a block of grouped items.
829 if ($print_subtotals) {
830 $cur_grouped_by = $record['grouped_by'];
831 if ($cur_grouped_by != $prev_grouped_by && !$first_pass) {
832 $body .= '<tr style="'.$rowSubtotal.'">';
833 $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.subtotal').'</td>';
834 $subtotal_name = htmlspecialchars($subtotals[$prev_grouped_by]['name']);
835 if ($canViewReports || $isClient) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['user'].'</td>';
836 if ($options['show_client']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['client'].'</td>';
837 if ($options['show_project']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['project'].'</td>';
838 if ($options['show_task']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['task'].'</td>';
839 if ($options['show_custom_field_1']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['cf_1'].'</td>';
840 if ($options['show_start']) $body .= '<td></td>';
841 if ($options['show_end']) $body .= '<td></td>';
842 if ($options['show_duration']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['time'].'</td>';
843 if ($options['show_work_units']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['units'].'</td>';
844 if ($options['show_note']) $body .= '<td></td>';
845 if ($options['show_cost']) {
846 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
847 $body .= ($canViewReports || $isClient) ? $subtotals[$prev_grouped_by]['cost'] : $subtotals[$prev_grouped_by]['expenses'];
850 if ($options['show_paid']) $body .= '<td></td>';
851 if ($options['show_ip']) $body .= '<td></td>';
852 if ($options['show_invoice']) $body .= '<td></td>';
854 $body .= '<tr><td> </td></tr>';
859 // Print a regular row.
860 if ($cur_date != $prev_date)
861 $row_style = ($row_style == $rowItem) ? $rowItemAlt : $rowItem;
862 $body .= '<tr style="'.$row_style.'">';
863 $body .= '<td style="'.$cellLeftAligned.'">'.$record['date'].'</td>';
864 if ($canViewReports || $isClient)
865 $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['user']).'</td>';
866 if ($options['show_client'])
867 $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['client']).'</td>';
868 if ($options['show_project'])
869 $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['project']).'</td>';
870 if ($options['show_task'])
871 $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['task']).'</td>';
872 if ($options['show_custom_field_1'])
873 $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['cf_1']).'</td>';
874 if ($options['show_start'])
875 $body .= '<td nowrap style="'.$cellRightAligned.'">'.$record['start'].'</td>';
876 if ($options['show_end'])
877 $body .= '<td nowrap style="'.$cellRightAligned.'">'.$record['finish'].'</td>';
878 if ($options['show_duration'])
879 $body .= '<td style="'.$cellRightAligned.'">'.$record['duration'].'</td>';
880 if ($options['show_work_units'])
881 $body .= '<td style="'.$cellRightAligned.'">'.$record['units'].'</td>';
882 if ($options['show_note'])
883 $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['note']).'</td>';
884 if ($options['show_cost'])
885 $body .= '<td style="'.$cellRightAligned.'">'.$record['cost'].'</td>';
886 if ($options['show_paid']) {
887 $body .= '<td style="'.$cellRightAligned.'">';
888 $body .= $record['paid'] == 1 ? $i18n->get('label.yes') : $i18n->get('label.no');
891 if ($options['show_ip']) {
892 $body .= '<td style="'.$cellRightAligned.'">';
893 $body .= $record['modified'] ? $record['modified_ip'].' '.$record['modified'] : $record['created_ip'].' '.$record['created'];
896 if ($options['show_invoice'])
897 $body .= '<td style="'.$cellRightAligned.'">'.htmlspecialchars($record['invoice']).'</td>';
900 $prev_date = $record['date'];
901 if ($print_subtotals)
902 $prev_grouped_by = $record['grouped_by'];
906 // Print a terminating subtotal.
907 if ($print_subtotals) {
908 $body .= '<tr style="'.$rowSubtotal.'">';
909 $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.subtotal').'</td>';
910 $subtotal_name = htmlspecialchars($subtotals[$cur_grouped_by]['name']);
911 if ($canViewReports || $isClient) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['user'].'</td>';
912 if ($options['show_client']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['client'].'</td>';
913 if ($options['show_project']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['project'].'</td>';
914 if ($options['show_task']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['task'].'</td>';
915 if ($options['show_custom_field_1']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['cf_1'].'</td>';
916 if ($options['show_start']) $body .= '<td></td>';
917 if ($options['show_end']) $body .= '<td></td>';
918 if ($options['show_duration']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$cur_grouped_by]['time'].'</td>';
919 if ($options['show_work_units']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$cur_grouped_by]['units'].'</td>';
920 if ($options['show_note']) $body .= '<td></td>';
921 if ($options['show_cost']) {
922 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
923 $body .= ($canViewReports || $isClient) ? $subtotals[$cur_grouped_by]['cost'] : $subtotals[$cur_grouped_by]['expenses'];
926 if ($options['show_paid']) $body .= '<td></td>';
927 if ($options['show_ip']) $body .= '<td></td>';
928 if ($options['show_invoice']) $body .= '<td></td>';
933 $body .= '<tr><td> </td></tr>';
934 $body .= '<tr style="'.$rowSubtotal.'">';
935 $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.total').'</td>';
936 if ($canViewReports || $isClient) $body .= '<td></td>';
937 if ($options['show_client']) $body .= '<td></td>';
938 if ($options['show_project']) $body .= '<td></td>';
939 if ($options['show_task']) $body .= '<td></td>';
940 if ($options['show_custom_field_1']) $body .= '<td></td>';
941 if ($options['show_start']) $body .= '<td></td>';
942 if ($options['show_end']) $body .= '<td></td>';
943 if ($options['show_duration']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$totals['time'].'</td>';
944 if ($options['show_work_units']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$totals['units'].'</td>';
945 if ($options['show_note']) $body .= '<td></td>';
946 if ($options['show_cost']) {
947 $body .= '<td nowrap style="'.$cellRightAlignedSubtotal.'">'.htmlspecialchars($user->currency).' ';
948 $body .= ($canViewReports || $isClient) ? $totals['cost'] : $totals['expenses'];
951 if ($options['show_paid']) $body .= '<td></td>';
952 if ($options['show_ip']) $body .= '<td></td>';
953 if ($options['show_invoice']) $body .= '<td></td>';
960 if (!defined('REPORT_FOOTER') || !(REPORT_FOOTER == false))
961 $body .= '<p style="text-align: center;">'.$i18n->get('form.mail.footer').'</p>';
963 // Finish creating email body.
964 $body .= '</body></html>';
969 // checkFavReportCondition - checks whether it is okay to send fav report.
970 static function checkFavReportCondition($options, $condition)
972 $items = ttReportHelper::getItems($options);
974 $condition = trim(str_replace('count', '', $condition));
976 $greater_or_equal = ttStartsWith($condition, '>=');
977 if ($greater_or_equal) $condition = trim(str_replace('>=', '', $condition));
979 $less_or_equal = ttStartsWith($condition, '<=');
980 if ($less_or_equal) $condition = trim(str_replace('<=', '', $condition));
982 $not_equal = ttStartsWith($condition, '<>');
983 if ($not_equal) $condition = trim(str_replace('<>', '', $condition));
985 $greater = ttStartsWith($condition, '>');
986 if ($greater) $condition = trim(str_replace('>', '', $condition));
988 $less = ttStartsWith($condition, '<');
989 if ($less) $condition = trim(str_replace('<', '', $condition));
991 $equal = ttStartsWith($condition, '=');
992 if ($equal) $condition = trim(str_replace('=', '', $condition));
994 $count_required = (int) $condition;
996 if ($greater && count($items) > $count_required) return true;
997 if ($greater_or_equal && count($items) >= $count_required) return true;
998 if ($less && count($items) < $count_required) return true;
999 if ($less_or_equal && count($items) <= $count_required) return true;
1000 if ($equal && count($items) == $count_required) return true;
1001 if ($not_equal && count($items) <> $count_required) return true;
1006 // sendFavReport - sends a favorite report to a specified email, called from cron.php
1007 static function sendFavReport($options, $subject, $email, $cc) {
1008 // We are called from cron.php, we have no $bean in session.
1009 // cron.php sets global $user and $i18n objects to match our favorite report user.
1013 // Prepare report body.
1014 $body = ttReportHelper::prepareReportBody($options);
1016 import('mail.Mailer');
1017 $mailer = new Mailer();
1018 $mailer->setCharSet(CHARSET);
1019 $mailer->setContentType('text/html');
1020 $mailer->setSender(SENDER);
1022 $mailer->setReceiverCC($cc);
1023 if (!empty($user->bcc_email))
1024 $mailer->setReceiverBCC($user->bcc_email);
1025 $mailer->setReceiver($email);
1026 $mailer->setMailMode(MAIL_MODE);
1027 if (empty($subject)) $subject = $options['name'];
1028 if (!$mailer->send($subject, $body))
1034 // getReportOptions - returns an array of report options constructed from session bean.
1036 // Note: similarly to ttFavReportHelper::getReportOptions, this function is a part of
1037 // refactoring to simplify maintenance of report generating functions, as we currently
1038 // have 2 sets: normal reporting (from bean), and fav report emailing (from db fields).
1039 // Using options obtained from either db or bean shall allow us to use only one set of functions.
1040 static function getReportOptions($bean) {
1043 // Prepare an array of report options.
1046 // Construct one by one.
1047 $options['name'] = null; // No name required.
1048 $options['user_id'] = $user->id; // Not sure if we need user_id here. Fav reports use it to recycle $user object in cron.php.
1049 $options['client_id'] = $bean->getAttribute('client');
1050 $options['cf_1_option_id'] = $bean->getAttribute('option');
1051 $options['project_id'] = $bean->getAttribute('project');
1052 $options['task_id'] = $bean->getAttribute('task');
1053 $options['billable'] = $bean->getAttribute('include_records');
1054 $options['invoice'] = $bean->getAttribute('invoice');
1055 $options['paid_status'] = $bean->getAttribute('paid_status');
1056 $options['timesheet'] = $bean->getAttribute('timesheet');
1057 if (is_array($bean->getAttribute('users'))) $options['users'] = join(',', $bean->getAttribute('users'));
1058 $options['period'] = $bean->getAttribute('period');
1059 $options['period_start'] = $bean->getAttribute('start_date');
1060 $options['period_end'] = $bean->getAttribute('end_date');
1061 $options['show_client'] = $bean->getAttribute('chclient');
1062 $options['show_invoice'] = $bean->getAttribute('chinvoice');
1063 $options['show_paid'] = $bean->getAttribute('chpaid');
1064 $options['show_ip'] = $bean->getAttribute('chip');
1065 $options['show_project'] = $bean->getAttribute('chproject');
1066 $options['show_start'] = $bean->getAttribute('chstart');
1067 $options['show_duration'] = $bean->getAttribute('chduration');
1068 $options['show_cost'] = $bean->getAttribute('chcost');
1069 $options['show_task'] = $bean->getAttribute('chtask');
1070 $options['show_end'] = $bean->getAttribute('chfinish');
1071 $options['show_note'] = $bean->getAttribute('chnote');
1072 $options['show_custom_field_1'] = $bean->getAttribute('chcf_1');
1073 $options['show_work_units'] = $bean->getAttribute('chunits');
1074 $options['show_timesheet'] = $bean->getAttribute('chtimesheet');
1075 $options['show_totals_only'] = $bean->getAttribute('chtotalsonly');
1076 $options['group_by1'] = $bean->getAttribute('group_by1');
1077 $options['group_by2'] = $bean->getAttribute('group_by2');
1078 $options['group_by3'] = $bean->getAttribute('group_by3');
1082 // verifyBean is a security function to make sure data in bean makes sense for a group.
1083 static function verifyBean($bean) {
1087 $users_in_bean = $bean->getAttribute('users');
1088 if (is_array($users_in_bean)) {
1089 $users_in_group = ttGroupHelper::getUsers();
1090 foreach ($users_in_group as $user_in_group) {
1091 $valid_ids[] = $user_in_group['id'];
1093 foreach ($users_in_bean as $user_in_bean) {
1094 if (!in_array($user_in_bean, $valid_ids)) {
1100 // TODO: add additional checks here. Perhaps do it before saving the bean for consistency.
1104 // makeGroupByKey builds a combined group by key from group_by1, group_by2 and group_by3 values
1105 // (passed in $options) and a row of data ($row obtained from a db query).
1106 static function makeGroupByKey($options, $row) {
1107 if ($options['group_by1'] != null && $options['group_by1'] != 'no_grouping') {
1108 // We have group_by1.
1109 $group_by1 = $options['group_by1'];
1110 $group_by1_value = $row[$group_by1];
1111 //if ($group_by1 == 'date') $group_by1_value = ttDateToUserFormat($group_by1_value);
1112 if (empty($group_by1_value)) $group_by1_value = 'Null'; // To match what comes out of makeConcatPart.
1113 $group_by_key .= ' - '.$group_by1_value;
1115 if ($options['group_by2'] != null && $options['group_by2'] != 'no_grouping') {
1116 // We have group_by2.
1117 $group_by2 = $options['group_by2'];
1118 $group_by2_value = $row[$group_by2];
1119 //if ($group_by2 == 'date') $group_by2_value = ttDateToUserFormat($group_by2_value);
1120 if (empty($group_by2_value)) $group_by2_value = 'Null'; // To match what comes out of makeConcatPart.
1121 $group_by_key .= ' - '.$group_by2_value;
1123 if ($options['group_by3'] != null && $options['group_by3'] != 'no_grouping') {
1124 // We have group_by3.
1125 $group_by3 = $options['group_by3'];
1126 $group_by3_value = $row[$group_by3];
1127 //if ($group_by3 == 'date') $group_by3_value = ttDateToUserFormat($group_by3_value);
1128 if (empty($group_by3_value)) $group_by3_value = 'Null'; // To match what comes out of makeConcatPart.
1129 $group_by_key .= ' - '.$group_by3_value;
1131 $group_by_key = trim($group_by_key, ' -');
1132 return $group_by_key;
1135 // makeGroupByPart builds a combined group by part for sql query for time items using group_by1,
1136 // group_by2, and group_by3 values passed in $options.
1137 static function makeGroupByPart($options) {
1138 if (!ttReportHelper::grouping($options)) return null;
1140 $group_by1 = $options['group_by1'];
1141 $group_by2 = $options['group_by2'];
1142 $group_by3 = $options['group_by3'];
1144 switch ($group_by1) {
1146 $group_by_parts .= ', l.date';
1149 $group_by_parts .= ', u.name';
1152 $group_by_parts .= ', c.name';
1155 $group_by_parts .= ', p.name';
1158 $group_by_parts .= ', t.name';
1161 $group_by_parts .= ', cfo.value';
1164 switch ($group_by2) {
1166 $group_by_parts .= ', l.date';
1169 $group_by_parts .= ', u.name';
1172 $group_by_parts .= ', c.name';
1175 $group_by_parts .= ', p.name';
1178 $group_by_parts .= ', t.name';
1181 $group_by_parts .= ', cfo.value';
1184 switch ($group_by3) {
1186 $group_by_parts .= ', l.date';
1189 $group_by_parts .= ', u.name';
1192 $group_by_parts .= ', c.name';
1195 $group_by_parts .= ', p.name';
1198 $group_by_parts .= ', t.name';
1201 $group_by_parts .= ', cfo.value';
1204 // Remove garbage from the beginning.
1205 $group_by_parts = ltrim($group_by_parts, ', ');
1206 $group_by_part = "group by $group_by_parts";
1207 return $group_by_part;
1210 // makeGroupByExpensesPart builds a combined group by part for sql query for expense items using
1211 // group_by1, group_by2, and group_by3 values passed in $options.
1212 static function makeGroupByExpensesPart($options) {
1213 $no_grouping = ($options['group_by1'] == null || $options['group_by1'] == 'no_grouping') &&
1214 ($options['group_by2'] == null || $options['group_by2'] == 'no_grouping') &&
1215 ($options['group_by3'] == null || $options['group_by3'] == 'no_grouping');
1216 if ($no_grouping) return null;
1218 $group_by1 = $options['group_by1'];
1219 $group_by2 = $options['group_by2'];
1220 $group_by3 = $options['group_by3'];
1222 switch ($group_by1) {
1224 $group_by_parts .= ', ei.date';
1227 $group_by_parts .= ', u.name';
1230 $group_by_parts .= ', c.name';
1233 $group_by_parts .= ', p.name';
1236 switch ($group_by2) {
1238 $group_by_parts .= ', ei.date';
1241 $group_by_parts .= ', u.name';
1244 $group_by_parts .= ', c.name';
1247 $group_by_parts .= ', p.name';
1250 switch ($group_by3) {
1252 $group_by_parts .= ', ei.date';
1255 $group_by_parts .= ', u.name';
1258 $group_by_parts .= ', c.name';
1261 $group_by_parts .= ', p.name';
1264 // Remove garbage from the beginning.
1265 $group_by_parts = ltrim($group_by_parts, ', ');
1266 if ($group_by_parts)
1267 $group_by_part = "group by $group_by_parts";
1268 return $group_by_part;
1271 // makeConcatPart builds a concatenation part for getSubtotals query (for time items).
1272 static function makeConcatPart($options) {
1273 $group_by1 = $options['group_by1'];
1274 $group_by2 = $options['group_by2'];
1275 $group_by3 = $options['group_by3'];
1277 switch ($group_by1) {
1279 $what_to_concat .= ", ' - ', l.date";
1282 $what_to_concat .= ", ' - ', u.name";
1283 $fields_part .= ', u.name as user';
1286 $what_to_concat .= ", ' - ', coalesce(c.name, 'Null')";
1287 $fields_part .= ', c.name as client';
1290 $what_to_concat .= ", ' - ', coalesce(p.name, 'Null')";
1291 $fields_part .= ', p.name as project';
1294 $what_to_concat .= ", ' - ', coalesce(t.name, 'Null')";
1295 $fields_part .= ', t.name as task';
1298 $what_to_concat .= ", ' - ', coalesce(cfo.value, 'Null')";
1299 $fields_part .= ', cfo.value as cf_1';
1302 switch ($group_by2) {
1304 $what_to_concat .= ", ' - ', l.date";
1307 $what_to_concat .= ", ' - ', u.name";
1308 $fields_part .= ', u.name as user';
1311 $what_to_concat .= ", ' - ', coalesce(c.name, 'Null')";
1312 $fields_part .= ', c.name as client';
1315 $what_to_concat .= ", ' - ', coalesce(p.name, 'Null')";
1316 $fields_part .= ', p.name as project';
1319 $what_to_concat .= ", ' - ', coalesce(t.name, 'Null')";
1320 $fields_part .= ', t.name as task';
1323 $what_to_concat .= ", ' - ', coalesce(cfo.value, 'Null')";
1324 $fields_part .= ', cfo.value as cf_1';
1327 switch ($group_by3) {
1329 $what_to_concat .= ", ' - ', l.date";
1332 $what_to_concat .= ", ' - ', u.name";
1333 $fields_part .= ', u.name as user';
1336 $what_to_concat .= ", ' - ', coalesce(c.name, 'Null')";
1337 $fields_part .= ', c.name as client';
1340 $what_to_concat .= ", ' - ', coalesce(p.name, 'Null')";
1341 $fields_part .= ', p.name as project';
1344 $what_to_concat .= ", ' - ', coalesce(t.name, 'Null')";
1345 $fields_part .= ', t.name as task';
1348 $what_to_concat .= ", ' - ', coalesce(cfo.value, 'Null')";
1349 $fields_part .= ', cfo.value as cf_1';
1352 // Remove garbage from both ends.
1353 $what_to_concat = trim($what_to_concat, "', -");
1354 $concat_part = "concat($what_to_concat) as group_field";
1355 $concat_part = trim($concat_part, ' -');
1356 return "$concat_part $fields_part";
1359 // makeConcatPart builds a concatenation part for getSubtotals query (for expense items).
1360 static function makeConcatExpensesPart($options) {
1361 $group_by1 = $options['group_by1'];
1362 $group_by2 = $options['group_by2'];
1363 $group_by3 = $options['group_by3'];
1365 switch ($group_by1) {
1367 $what_to_concat .= ", ' - ', ei.date";
1370 $what_to_concat .= ", ' - ', u.name";
1371 $fields_part .= ', u.name as user';
1374 $what_to_concat .= ", ' - ', coalesce(c.name, 'Null')";
1375 $fields_part .= ', c.name as client';
1378 $what_to_concat .= ", ' - ', coalesce(p.name, 'Null')";
1379 $fields_part .= ', p.name as project';
1383 $what_to_concat .= ", ' - ', 'Null'";
1384 $fields_part .= ', null as task';
1388 $what_to_concat .= ", ' - ', 'Null'";
1389 $fields_part .= ', null as cf_1';
1392 switch ($group_by2) {
1394 $what_to_concat .= ", ' - ', ei.date";
1397 $what_to_concat .= ", ' - ', u.name";
1398 $fields_part .= ', u.name as user';
1401 $what_to_concat .= ", ' - ', coalesce(c.name, 'Null')";
1402 $fields_part .= ', c.name as client';
1405 $what_to_concat .= ", ' - ', coalesce(p.name, 'Null')";
1406 $fields_part .= ', p.name as project';
1410 $what_to_concat .= ", ' - ', 'Null'";
1411 $fields_part .= ', null as task';
1415 $what_to_concat .= ", ' - ', 'Null'";
1416 $fields_part .= ', null as cf_1';
1419 switch ($group_by3) {
1421 $what_to_concat .= ", ' - ', ei.date";
1424 $what_to_concat .= ", ' - ', u.name";
1425 $fields_part .= ', u.name as user';
1428 $what_to_concat .= ", ' - ', coalesce(c.name, 'Null')";
1429 $fields_part .= ', c.name as client';
1432 $what_to_concat .= ", ' - ', coalesce(p.name, 'Null')";
1433 $fields_part .= ', p.name as project';
1437 $what_to_concat .= ", ' - ', 'Null'";
1438 $fields_part .= ', null as task';
1442 $what_to_concat .= ", ' - ', 'Null'";
1443 $fields_part .= ', null as cf_1';
1446 // Remove garbage from the beginning.
1447 if ($what_to_concat)
1448 $what_to_concat = substr($what_to_concat, 8);
1449 $concat_part = "concat($what_to_concat) as group_field";
1450 return "$concat_part $fields_part";
1453 // makeCombinedSelectPart builds a list of fields for a combined select on a union for getSubtotals.
1454 // This is used when we include expenses.
1455 static function makeCombinedSelectPart($options) {
1456 $group_by1 = $options['group_by1'];
1457 $group_by2 = $options['group_by2'];
1458 $group_by3 = $options['group_by3'];
1460 $fields = "group_field";
1462 switch ($group_by1) {
1464 $fields .= ', user';
1467 $fields_part .= ', client';
1470 $fields .= ', project';
1474 $fields .= ', task';
1478 $fields .= ', cf_1';
1481 switch ($group_by2) {
1483 $fields .= ', user';
1486 $fields_part .= ', client';
1489 $fields .= ', project';
1493 $fields .= ', task';
1497 $fields .= ', cf_1';
1500 switch ($group_by3) {
1502 $fields .= ', user';
1505 $fields_part .= ', client';
1508 $fields .= ', project';
1512 $fields .= ', task';
1516 $fields .= ', cf_1';
1522 // makeJoinPart builds a left join part for getSubtotals query (for time items).
1523 static function makeJoinPart($options) {
1526 $trackingMode = $user->getTrackingMode();
1527 if (ttReportHelper::groupingBy('user', $options) || MODE_TIME == $trackingMode) {
1528 $join .= ' left join tt_users u on (l.user_id = u.id)';
1530 if (ttReportHelper::groupingBy('client', $options)) {
1531 $join .= ' left join tt_clients c on (l.client_id = c.id)';
1533 if (ttReportHelper::groupingBy('project', $options)) {
1534 $join .= ' left join tt_projects p on (l.project_id = p.id)';
1536 if (ttReportHelper::groupingBy('task', $options)) {
1537 $join .= ' left join tt_tasks t on (l.task_id = t.id)';
1539 if (ttReportHelper::groupingBy('cf_1', $options)) {
1540 $custom_fields = new CustomFields();
1541 if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_TEXT)
1542 $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)';
1543 elseif ($custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN)
1544 $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)';
1546 if ($options['show_cost'] && $trackingMode != MODE_TIME) {
1547 $join .= ' left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id)';
1552 // makeWorkUnitPart builds an sql part for work units for time items.
1553 static function makeWorkUnitPart($options) {
1556 $workUnits = $options['show_work_units'];
1558 $unitTotalsOnly = $user->getConfigOption('unit_totals_only');
1559 $firstUnitThreshold = $user->getConfigInt('1st_unit_threshold', 0);
1560 $minutesInUnit = $user->getConfigInt('minutes_in_unit', 15);
1561 if ($unitTotalsOnly)
1562 $work_unit_part = ", if (sum(l.billable * time_to_sec(l.duration)/60) < $firstUnitThreshold, 0, ceil(sum(l.billable * time_to_sec(l.duration)/60/$minutesInUnit))) as units";
1564 $work_unit_part = ", sum(if(l.billable = 0 or time_to_sec(l.duration)/60 < $firstUnitThreshold, 0, ceil(time_to_sec(l.duration)/60/$minutesInUnit))) as units";
1566 return $work_unit_part;
1569 // makeCostPart builds a cost part for time items.
1570 static function makeCostPart($options) {
1573 if ($options['show_cost']) {
1574 if (MODE_TIME == $user->getTrackingMode())
1575 $cost_part = ", sum(cast(l.billable * coalesce(u.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10, 2))) as cost";
1577 $cost_part .= ", sum(cast(l.billable * coalesce(upb.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10,2))) as cost";
1582 // makeJoinExpensesPart builds a left join part for getSubtotals query for expense items.
1583 static function makeJoinExpensesPart($options) {
1584 if (ttReportHelper::groupingBy('user', $options)) {
1585 $join .= ' left join tt_users u on (ei.user_id = u.id)';
1587 if (ttReportHelper::groupingBy('client', $options)) {
1588 $join .= ' left join tt_clients c on (ei.client_id = c.id)';
1590 if (ttReportHelper::groupingBy('project', $options)) {
1591 $join .= ' left join tt_projects p on (ei.project_id = p.id)';
1596 // grouping determines if we are grouping the report by either group_by1,
1597 // group_by2, or group_by3 values passed in $options.
1598 static function grouping($options) {
1599 $grouping = ($options['group_by1'] != null && $options['group_by1'] != 'no_grouping') ||
1600 ($options['group_by2'] != null && $options['group_by2'] != 'no_grouping') ||
1601 ($options['group_by3'] != null && $options['group_by3'] != 'no_grouping');
1605 // groupingBy determines if we are grouping a report by a value of $what
1606 // ('date', 'user', 'project', etc.) by checking group_by1, group_by2,
1607 // and group_by3 values passed in $options.
1608 static function groupingBy($what, $options) {
1609 $grouping = ($options['group_by1'] == $what) || ($options['group_by2'] == $what) || ($options['group_by3'] == $what);
1613 // makeGroupByHeader builds a column header for a totals-only report using group_by1,
1614 // group_by2, and group_by3 values passed in $options.
1615 static function makeGroupByHeader($options) {
1617 global $custom_fields;
1619 $no_grouping = ($options['group_by1'] == null || $options['group_by1'] == 'no_grouping') &&
1620 ($options['group_by2'] == null || $options['group_by2'] == 'no_grouping') &&
1621 ($options['group_by3'] == null || $options['group_by3'] == 'no_grouping');
1622 if ($no_grouping) return null;
1624 if ($options['group_by1'] != null && $options['group_by1'] != 'no_grouping') {
1625 // We have group_by1.
1626 $group_by1 = $options['group_by1'];
1627 if ('cf_1' == $group_by1)
1628 $group_by_header .= ' - '.$custom_fields->fields[0]['label'];
1630 $key = 'label.'.$group_by1;
1631 $group_by_header .= ' - '.$i18n->get($key);
1634 if ($options['group_by2'] != null && $options['group_by2'] != 'no_grouping') {
1635 // We have group_by2.
1636 $group_by2 = $options['group_by2'];
1637 if ('cf_1' == $group_by2)
1638 $group_by_header .= ' - '.$custom_fields->fields[0]['label'];
1640 $key = 'label.'.$group_by2;
1641 $group_by_header .= ' - '.$i18n->get($key);
1644 if ($options['group_by3'] != null && $options['group_by3'] != 'no_grouping') {
1645 // We have group_by3.
1646 $group_by3 = $options['group_by3'];
1647 if ('cf_1' == $group_by3)
1648 $group_by_header .= ' - '.$custom_fields->fields[0]['label'];
1650 $key = 'label.'.$group_by3;
1651 $group_by_header .= ' - '.$i18n->get($key);
1654 $group_by_header = ltrim($group_by_header, ' -');
1655 return $group_by_header;
1658 // makeGroupByXmlTag creates an xml tag for a totals only report using group_by1,
1659 // group_by2, and group_by3 values passed in $options.
1660 static function makeGroupByXmlTag($options) {
1661 if ($options['group_by1'] != null && $options['group_by1'] != 'no_grouping') {
1662 // We have group_by1.
1663 $tag .= '_'.$options['group_by1'];
1665 if ($options['group_by2'] != null && $options['group_by2'] != 'no_grouping') {
1666 // We have group_by2.
1667 $tag .= '_'.$options['group_by2'];
1669 if ($options['group_by3'] != null && $options['group_by3'] != 'no_grouping') {
1670 // We have group_by3.
1671 $tag .= '_'.$options['group_by3'];
1673 $tag = ltrim($tag, '_');
1677 // makeGroupByLabel builds a label for one row in a "Totals only" report of grouped by items.
1678 // It does one thing: if we are grouping by date, the date format is converted for user.
1679 static function makeGroupByLabel($key, $options) {
1680 if (!ttReportHelper::groupingBy('date', $options))
1681 return $key; // No need to format.
1684 if ($user->getDateFormat() == DB_DATEFORMAT)
1685 return $key; // No need to format.
1688 if (preg_match('/\d\d\d\d-\d\d-\d\d/', $key, $matches)) {
1689 // Replace the first found match of a date in DB_DATEFORMAT.
1690 // This is not entirely clean but better than nothing for a label in a row.
1691 $userDate = ttDateToUserFormat($matches[0]);
1692 $label = str_replace($matches[0], $userDate, $key);