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 // Note: $options is a future replacement of $bean, which is work in progress.
41 static function getWhere($bean, $options) {
44 // Prepare dropdown parts.
46 if ($options['client_id'])
47 $dropdown_parts .= ' and l.client_id = '.$options['client_id'];
48 elseif ($user->isClient() && $user->client_id)
49 $dropdown_parts .= ' and l.client_id = '.$user->client_id;
50 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'].')';
51 if ($options['project_id']) $dropdown_parts .= ' and l.project_id = '.$options['project_id'];
52 if ($options['task_id']) $dropdown_parts .= ' and l.task_id = '.$options['task_id'];
53 if ($options['billable']=='1') $dropdown_parts .= ' and l.billable = 1';
54 if ($options['billable']=='2') $dropdown_parts .= ' and l.billable = 0';
55 if ($options['invoice']=='1') $dropdown_parts .= ' and l.invoice_id is not NULL';
56 if ($options['invoice']=='2') $dropdown_parts .= ' and l.invoice_id is NULL';
57 if ($options['paid_status']=='1') $dropdown_parts .= ' and l.paid = 1';
58 if ($options['paid_status']=='2') $dropdown_parts .= ' and l.paid = 0';
60 // Prepare user list part.
62 if (($user->can('view_reports') || $user->isClient()) && is_array($bean->getAttribute('users')))
63 $userlist = join(',', $bean->getAttribute('users'));
64 // Prepare sql query part for user list.
65 $user_list_part = null;
66 if ($user->can('view_reports') || $user->isClient())
67 $user_list_part = " and l.user_id in ($userlist)";
69 $user_list_part = " and l.user_id = ".$user->id;
71 // Prepare sql query part for where.
72 if ($bean->getAttribute('period'))
73 $period = new Period($bean->getAttribute('period'), new DateAndTime($user->date_format));
75 $period = new Period();
77 new DateAndTime($user->date_format, $bean->getAttribute('start_date')),
78 new DateAndTime($user->date_format, $bean->getAttribute('end_date')));
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 // getFavWhere prepares a WHERE clause for a favorite report query.
86 static function getFavWhere($options) {
89 // Prepare dropdown parts.
91 if ($options['client_id'])
92 $dropdown_parts .= ' and l.client_id = '.$options['client_id'];
93 elseif ($user->isClient() && $user->client_id)
94 $dropdown_parts .= ' and l.client_id = '.$user->client_id;
95 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'].')';
96 if ($options['project_id']) $dropdown_parts .= ' and l.project_id = '.$options['project_id'];
97 if ($options['task_id']) $dropdown_parts .= ' and l.task_id = '.$options['task_id'];
98 if ($options['billable']=='1') $dropdown_parts .= ' and l.billable = 1';
99 if ($options['billable']=='2') $dropdown_parts .= ' and l.billable = 0';
100 if ($options['invoice']=='1') $dropdown_parts .= ' and l.invoice_id is not NULL';
101 if ($options['invoice']=='2') $dropdown_parts .= ' and l.invoice_id is NULL';
102 if ($options['paid_status']=='1') $dropdown_parts .= ' and l.paid = 1';
103 if ($options['paid_status']=='2') $dropdown_parts .= ' and l.paid = 0';
105 // Prepare user list part.
107 if (($user->can('view_reports') || $user->isClient())) {
108 if ($options['users'])
109 $userlist = $options['users'];
111 $active_users = ttTeamHelper::getActiveUsers();
112 foreach ($active_users as $single_user)
113 $users[] = $single_user['id'];
114 $userlist = join(',', $users);
117 // Prepare sql query part for user list.
118 $user_list_part = null;
119 if ($user->can('view_reports') || $user->isClient())
120 $user_list_part = " and l.user_id in ($userlist)";
122 $user_list_part = " and l.user_id = ".$user->id;
124 // Prepare sql query part for where.
125 if ($options['period'])
126 $period = new Period($options['period'], new DateAndTime($user->date_format));
128 $period = new Period();
130 new DateAndTime($user->date_format, $options['period_start']),
131 new DateAndTime($user->date_format, $options['period_end']));
133 $where = " where l.status = 1 and l.date >= '".$period->getStartDate(DB_DATEFORMAT)."' and l.date <= '".$period->getEndDate(DB_DATEFORMAT)."'".
134 " $user_list_part $dropdown_parts";
138 // getExpenseWhere prepares WHERE clause for expenses query in a report.
139 static function getExpenseWhere($bean, $options) {
142 // Prepare dropdown parts.
143 $dropdown_parts = '';
144 if ($options['client_id'])
145 $dropdown_parts .= ' and l.client_id = '.$options['client_id'];
146 elseif ($user->isClient() && $user->client_id)
147 $dropdown_parts .= ' and ei.client_id = '.$user->client_id;
148 if ($options['project_id']) $dropdown_parts .= ' and ei.project_id = '.$options['project_id'];
149 if ($options['invoice']=='1') $dropdown_parts .= ' and ei.invoice_id is not NULL';
150 if ($options['invoice']=='2') $dropdown_parts .= ' and ei.invoice_id is NULL';
151 if ($options['paid_status']=='1') $dropdown_parts .= ' and ei.paid = 1';
152 if ($options['paid_status']=='2') $dropdown_parts .= ' and ei.paid = 0';
154 // Prepare user list part.
156 if (($user->can('view_reports') || $user->isClient()) && is_array($bean->getAttribute('users')))
157 $userlist = join(',', $bean->getAttribute('users'));
158 // Prepare sql query part for user list.
159 $user_list_part = null;
160 if ($user->can('view_reports') || $user->isClient())
161 $user_list_part = " and ei.user_id in ($userlist)";
163 $user_list_part = " and ei.user_id = ".$user->id;
165 // Prepare sql query part for where.
166 if ($bean->getAttribute('period'))
167 $period = new Period($bean->getAttribute('period'), new DateAndTime($user->date_format));
169 $period = new Period();
171 new DateAndTime($user->date_format, $bean->getAttribute('start_date')),
172 new DateAndTime($user->date_format, $bean->getAttribute('end_date')));
174 $where = " where ei.status = 1 and ei.date >= '".$period->getStartDate(DB_DATEFORMAT)."' and ei.date <= '".$period->getEndDate(DB_DATEFORMAT)."'".
175 " $user_list_part $dropdown_parts";
179 // getFavExpenseWhere prepares a WHERE clause for expenses query in a favorite report.
180 static function getFavExpenseWhere($options) {
183 // Prepare dropdown parts.
184 $dropdown_parts = '';
185 if ($options['client_id'])
186 $dropdown_parts .= ' and ei.client_id = '.$options['client_id'];
187 elseif ($user->isClient() && $user->client_id)
188 $dropdown_parts .= ' and ei.client_id = '.$user->client_id;
189 if ($options['project_id']) $dropdown_parts .= ' and ei.project_id = '.$options['project_id'];
190 if ($options['invoice']=='1') $dropdown_parts .= ' and ei.invoice_id is not NULL';
191 if ($options['invoice']=='2') $dropdown_parts .= ' and ei.invoice_id is NULL';
192 if ($options['paid_status']=='1') $dropdown_parts .= ' and ei.paid = 1';
193 if ($options['paid_status']=='2') $dropdown_parts .= ' and ei.paid = 0';
195 // Prepare user list part.
197 if (($user->can('view_reports') || $user->isClient())) {
198 if ($options['users'])
199 $userlist = $options['users'];
201 $active_users = ttTeamHelper::getActiveUsers();
202 foreach ($active_users as $single_user)
203 $users[] = $single_user['id'];
204 $userlist = join(',', $users);
207 // Prepare sql query part for user list.
208 $user_list_part = null;
209 if ($user->can('view_reports') || $user->isClient())
210 $user_list_part = " and ei.user_id in ($userlist)";
212 $user_list_part = " and ei.user_id = ".$user->id;
214 // Prepare sql query part for where.
215 if ($options['period'])
216 $period = new Period($options['period'], new DateAndTime($user->date_format));
218 $period = new Period();
220 new DateAndTime($user->date_format, $options['period_start']),
221 new DateAndTime($user->date_format, $options['period_end']));
223 $where = " where ei.status = 1 and ei.date >= '".$period->getStartDate(DB_DATEFORMAT)."' and ei.date <= '".$period->getEndDate(DB_DATEFORMAT)."'".
224 " $user_list_part $dropdown_parts";
228 // getItems retrieves all items associated with a report.
229 // It combines tt_log and tt_expense_items in one array for presentation in one table using mysql union all.
230 // Expense items use the "note" field for item name.
231 static function getItems($bean, $options) {
233 $mdb2 = getConnection();
235 // Determine these once as they are used in multiple places in this function.
236 $canViewReports = $user->can('view_reports');
237 $isClient = $user->isClient();
239 $group_by_option = $bean->getAttribute('group_by');
240 $convertTo12Hour = ('%I:%M %p' == $user->time_format) && ($bean->getAttribute('chstart') || $bean->getAttribute('chfinish'));
242 // Prepare a query for time items in tt_log table.
243 $fields = array(); // An array of fields for database query.
244 array_push($fields, 'l.id as id');
245 array_push($fields, '1 as type'); // Type 1 is for tt_log entries.
246 array_push($fields, 'l.date as date');
247 if($canViewReports || $isClient)
248 array_push($fields, 'u.name as user');
249 // Add client name if it is selected.
250 if ($bean->getAttribute('chclient') || 'client' == $group_by_option)
251 array_push($fields, 'c.name as client');
252 // Add project name if it is selected.
253 if ($bean->getAttribute('chproject') || 'project' == $group_by_option)
254 array_push($fields, 'p.name as project');
255 // Add task name if it is selected.
256 if ($bean->getAttribute('chtask') || 'task' == $group_by_option)
257 array_push($fields, 't.name as task');
259 $include_cf_1 = $bean->getAttribute('chcf_1') || 'cf_1' == $group_by_option;
261 $custom_fields = new CustomFields($user->group_id);
262 $cf_1_type = $custom_fields->fields[0]['type'];
263 if ($cf_1_type == CustomFields::TYPE_TEXT) {
264 array_push($fields, 'cfl.value as cf_1');
265 } elseif ($cf_1_type == CustomFields::TYPE_DROPDOWN) {
266 array_push($fields, 'cfo.value as cf_1');
270 if ($bean->getAttribute('chstart')) {
271 array_push($fields, "l.start as unformatted_start");
272 array_push($fields, "TIME_FORMAT(l.start, '%k:%i') as start");
275 if ($bean->getAttribute('chfinish'))
276 array_push($fields, "TIME_FORMAT(sec_to_time(time_to_sec(l.start) + time_to_sec(l.duration)), '%k:%i') as finish");
278 if ($bean->getAttribute('chduration'))
279 array_push($fields, "TIME_FORMAT(l.duration, '%k:%i') as duration");
281 if ($bean->getAttribute('chunits')) {
282 if ($user->unit_totals_only)
283 array_push($fields, "null as units");
285 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");
288 if ($bean->getAttribute('chnote'))
289 array_push($fields, 'l.comment as note');
291 $includeCost = $bean->getAttribute('chcost');
293 if (MODE_TIME == $user->tracking_mode)
294 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.
296 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.
297 array_push($fields, "null as expense");
300 if ($canViewReports && $bean->getAttribute('chpaid'))
301 array_push($fields, 'l.paid as paid');
303 if ($canViewReports && $bean->getAttribute('chip')) {
304 array_push($fields, 'l.created as created');
305 array_push($fields, 'l.created_ip as created_ip');
306 array_push($fields, 'l.modified as modified');
307 array_push($fields, 'l.modified_ip as modified_ip');
310 // Add invoice name if it is selected.
311 if (($canViewReports || $isClient) && $bean->getAttribute('chinvoice'))
312 array_push($fields, 'i.name as invoice');
314 // Prepare sql query part for left joins.
316 if ($bean->getAttribute('chclient') || 'client' == $group_by_option)
317 $left_joins .= " left join tt_clients c on (c.id = l.client_id)";
318 if (($canViewReports || $isClient) && $bean->getAttribute('chinvoice'))
319 $left_joins .= " left join tt_invoices i on (i.id = l.invoice_id and i.status = 1)";
320 if ($canViewReports || $isClient || $user->isPluginEnabled('ex'))
321 $left_joins .= " left join tt_users u on (u.id = l.user_id)";
322 if ($bean->getAttribute('chproject') || 'project' == $group_by_option)
323 $left_joins .= " left join tt_projects p on (p.id = l.project_id)";
324 if ($bean->getAttribute('chtask') || 'task' == $group_by_option)
325 $left_joins .= " left join tt_tasks t on (t.id = l.task_id)";
327 if ($cf_1_type == CustomFields::TYPE_TEXT)
328 $left_joins .= " left join tt_custom_field_log cfl on (l.id = cfl.log_id and cfl.status = 1)";
329 elseif ($cf_1_type == CustomFields::TYPE_DROPDOWN) {
330 $left_joins .= " left join tt_custom_field_log cfl on (l.id = cfl.log_id and cfl.status = 1)".
331 " left join tt_custom_field_options cfo on (cfl.option_id = cfo.id)";
334 if ($includeCost && MODE_TIME != $user->tracking_mode)
335 $left_joins .= " left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id)";
337 $where = ttReportHelper::getWhere($bean, $options);
339 // Construct sql query for tt_log items.
340 $sql = "select ".join(', ', $fields)." from tt_log l $left_joins $where";
341 // If we don't have expense items (such as when the Expenses plugin is desabled), the above is all sql we need,
342 // with an exception of sorting part, that is added in the end.
344 // However, when we have expenses, we need to do a union with a separate query for expense items from tt_expense_items table.
345 if ($bean->getAttribute('chcost') && $user->isPluginEnabled('ex')) { // if ex(penses) plugin is enabled
347 $fields = array(); // An array of fields for database query.
348 array_push($fields, 'ei.id');
349 array_push($fields, '2 as type'); // Type 2 is for tt_expense_items entries.
350 array_push($fields, 'ei.date');
351 if($canViewReports || $isClient)
352 array_push($fields, 'u.name as user');
353 // Add client name if it is selected.
354 if ($bean->getAttribute('chclient') || 'client' == $group_by_option)
355 array_push($fields, 'c.name as client');
356 // Add project name if it is selected.
357 if ($bean->getAttribute('chproject') || 'project' == $group_by_option)
358 array_push($fields, 'p.name as project');
359 if ($bean->getAttribute('chtask') || 'task' == $group_by_option)
360 array_push($fields, 'null'); // null for task name. We need to match column count for union.
361 if ($bean->getAttribute('chcf_1') || 'cf_1' == $group_by_option)
362 array_push($fields, 'null'); // null for cf_1.
363 if ($bean->getAttribute('chstart')) {
364 array_push($fields, 'null'); // null for unformatted_start.
365 array_push($fields, 'null'); // null for start.
367 if ($bean->getAttribute('chfinish'))
368 array_push($fields, 'null'); // null for finish.
369 if ($bean->getAttribute('chduration'))
370 array_push($fields, 'null'); // null for duration.
372 if ($bean->getAttribute('chunits'))
373 array_push($fields, 'null as units'); // null for work units.
374 // Use the note field to print item name.
375 if ($bean->getAttribute('chnote'))
376 array_push($fields, 'ei.name as note');
377 array_push($fields, 'ei.cost as cost');
378 array_push($fields, 'ei.cost as expense');
380 if ($canViewReports && $bean->getAttribute('chpaid'))
381 array_push($fields, 'ei.paid as paid');
383 if ($canViewReports && $bean->getAttribute('chip')) {
384 array_push($fields, 'ei.created as created');
385 array_push($fields, 'ei.created_ip as created_ip');
386 array_push($fields, 'ei.modified as modified');
387 array_push($fields, 'ei.modified_ip as modified_ip');
390 // Add invoice name if it is selected.
391 if (($canViewReports || $isClient) && $bean->getAttribute('chinvoice'))
392 array_push($fields, 'i.name as invoice');
394 // Prepare sql query part for left joins.
396 if ($canViewReports || $isClient)
397 $left_joins .= " left join tt_users u on (u.id = ei.user_id)";
398 if ($bean->getAttribute('chclient') || 'client' == $group_by_option)
399 $left_joins .= " left join tt_clients c on (c.id = ei.client_id)";
400 if ($bean->getAttribute('chproject') || 'project' == $group_by_option)
401 $left_joins .= " left join tt_projects p on (p.id = ei.project_id)";
402 if (($canViewReports || $isClient) && $bean->getAttribute('chinvoice'))
403 $left_joins .= " left join tt_invoices i on (i.id = ei.invoice_id and i.status = 1)";
405 $where = ttReportHelper::getExpenseWhere($bean, $options);
407 // Construct sql query for expense items.
408 $sql_for_expense_items = "select ".join(', ', $fields)." from tt_expense_items ei $left_joins $where";
410 // Construct a union.
411 $sql = "($sql) union all ($sql_for_expense_items)";
414 // Determine sort part.
415 $sort_part = ' order by ';
416 if ('no_grouping' == $group_by_option || 'date' == $group_by_option)
417 $sort_part .= 'date';
419 $sort_part .= $group_by_option.', date';
420 if (($canViewReports || $isClient) && is_array($bean->getAttribute('users')) && 'user' != $group_by_option)
421 $sort_part .= ', user, type';
422 if ($bean->getAttribute('chstart'))
423 $sort_part .= ', unformatted_start';
424 $sort_part .= ', id';
427 // By now we are ready with sql.
429 // Obtain items for report.
430 $res = $mdb2->query($sql);
431 if (is_a($res, 'PEAR_Error')) die($res->getMessage());
433 while ($val = $res->fetchRow()) {
434 if ($convertTo12Hour) {
435 if($val['start'] != '')
436 $val['start'] = ttTimeHelper::to12HourFormat($val['start']);
437 if($val['finish'] != '')
438 $val['finish'] = ttTimeHelper::to12HourFormat($val['finish']);
440 if (isset($val['cost'])) {
441 if ('.' != $user->decimal_mark)
442 $val['cost'] = str_replace('.', $user->decimal_mark, $val['cost']);
444 if (isset($val['expense'])) {
445 if ('.' != $user->decimal_mark)
446 $val['expense'] = str_replace('.', $user->decimal_mark, $val['expense']);
448 if ('no_grouping' != $group_by_option) {
449 $val['grouped_by'] = $val[$group_by_option];
450 if ('date' == $group_by_option) {
451 // This is needed to get the date in user date format.
452 $o_date = new DateAndTime(DB_DATEFORMAT, $val['grouped_by']);
453 $val['grouped_by'] = $o_date->toString($user->date_format);
458 // This is needed to get the date in user date format.
459 $o_date = new DateAndTime(DB_DATEFORMAT, $val['date']);
460 $val['date'] = $o_date->toString($user->date_format);
464 $report_items[] = $row;
467 return $report_items;
470 // putInSession stores tt_log and tt_expense_items ids from a report in user session
471 // as 2 comma-separated lists.
472 static function putInSession($report_items) {
473 unset($_SESSION['report_item_ids']);
474 unset($_SESSION['report_item_expense_ids']);
476 // Iterate through records and build 2 comma-separated lists.
477 foreach($report_items as $item) {
478 if ($item['type'] == 1)
479 $report_item_ids .= ','.$item['id'];
480 else if ($item['type'] == 2)
481 $report_item_expense_ids .= ','.$item['id'];
483 $report_item_ids = trim($report_item_ids, ',');
484 $report_item_expense_ids = trim($report_item_expense_ids, ',');
486 // The lists are reqdy. Put them in session.
487 if ($report_item_ids) $_SESSION['report_item_ids'] = $report_item_ids;
488 if ($report_item_expense_ids) $_SESSION['report_item_expense_ids'] = $report_item_expense_ids;
491 // getFromSession obtains tt_log and tt_expense_items ids stored in user session.
492 static function getFromSession() {
494 $report_item_ids = $_SESSION['report_item_ids'];
495 if ($report_item_ids)
496 $items['report_item_ids'] = explode(',', $report_item_ids);
497 $report_item_expense_ids = $_SESSION['report_item_expense_ids'];
498 if ($report_item_expense_ids)
499 $items['report_item_expense_ids'] = explode(',', $report_item_expense_ids);
503 // getFavItems retrieves all items associated with a favorite report.
504 // It combines tt_log and tt_expense_items in one array for presentation in one table using mysql union all.
505 // Expense items use the "note" field for item name.
506 static function getFavItems($options) {
508 $mdb2 = getConnection();
510 // Determine these once as they are used in multiple places in this function.
511 $canViewReports = $user->can('view_reports');
512 $isClient = $user->isClient();
514 $group_by_option = $options['group_by'];
515 $convertTo12Hour = ('%I:%M %p' == $user->time_format) && ($options['show_start'] || $options['show_end']);
517 // Prepare a query for time items in tt_log table.
518 $fields = array(); // An array of fields for database query.
519 array_push($fields, 'l.id as id');
520 array_push($fields, '1 as type'); // Type 1 is for tt_log entries.
521 array_push($fields, 'l.date as date');
522 if($canViewReports || $isClient)
523 array_push($fields, 'u.name as user');
524 // Add client name if it is selected.
525 if ($options['show_client'] || 'client' == $group_by_option)
526 array_push($fields, 'c.name as client');
527 // Add project name if it is selected.
528 if ($options['show_project'] || 'project' == $group_by_option)
529 array_push($fields, 'p.name as project');
530 // Add task name if it is selected.
531 if ($options['show_task'] || 'task' == $group_by_option)
532 array_push($fields, 't.name as task');
534 $include_cf_1 = $options['show_custom_field_1'] || 'cf_1' == $group_by_option;
536 $custom_fields = new CustomFields($user->group_id);
537 $cf_1_type = $custom_fields->fields[0]['type'];
538 if ($cf_1_type == CustomFields::TYPE_TEXT) {
539 array_push($fields, 'cfl.value as cf_1');
540 } elseif ($cf_1_type == CustomFields::TYPE_DROPDOWN) {
541 array_push($fields, 'cfo.value as cf_1');
545 if ($options['show_start']) {
546 array_push($fields, "l.start as unformatted_start");
547 array_push($fields, "TIME_FORMAT(l.start, '%k:%i') as start");
550 if ($options['show_end'])
551 array_push($fields, "TIME_FORMAT(sec_to_time(time_to_sec(l.start) + time_to_sec(l.duration)), '%k:%i') as finish");
553 if ($options['show_duration'])
554 array_push($fields, "TIME_FORMAT(l.duration, '%k:%i') as duration");
556 if ($options['show_work_units']) {
557 if ($user->unit_totals_only)
558 array_push($fields, "null as units");
560 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");
564 if ($options['show_note'])
565 array_push($fields, 'l.comment as note');
567 $includeCost = $options['show_cost'];
569 if (MODE_TIME == $user->tracking_mode)
570 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.
572 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.
573 array_push($fields, "null as expense");
576 if ($canViewReports && $options['show_paid'])
577 array_push($fields, 'l.paid as paid');
579 if ($canViewReports && $options['show_ip']) {
580 array_push($fields, 'l.created as created');
581 array_push($fields, 'l.created_ip as created_ip');
582 array_push($fields, 'l.modified as modified');
583 array_push($fields, 'l.modified_ip as modified_ip');
585 // Add invoice name if it is selected.
586 if (($canViewReports || $isClient) && $options['show_invoice'])
587 array_push($fields, 'i.name as invoice');
589 // Prepare sql query part for left joins.
591 if ($options['show_client'] || 'client' == $group_by_option)
592 $left_joins .= " left join tt_clients c on (c.id = l.client_id)";
593 if (($canViewReports || $isClient) && $options['show_invoice'])
594 $left_joins .= " left join tt_invoices i on (i.id = l.invoice_id and i.status = 1)";
595 if ($canViewReports || $isClient || $user->isPluginEnabled('ex'))
596 $left_joins .= " left join tt_users u on (u.id = l.user_id)";
597 if ($options['show_project'] || 'project' == $group_by_option)
598 $left_joins .= " left join tt_projects p on (p.id = l.project_id)";
599 if ($options['show_task'] || 'task' == $group_by_option)
600 $left_joins .= " left join tt_tasks t on (t.id = l.task_id)";
602 if ($cf_1_type == CustomFields::TYPE_TEXT)
603 $left_joins .= " left join tt_custom_field_log cfl on (l.id = cfl.log_id and cfl.status = 1)";
604 elseif ($cf_1_type == CustomFields::TYPE_DROPDOWN) {
605 $left_joins .= " left join tt_custom_field_log cfl on (l.id = cfl.log_id and cfl.status = 1)".
606 " left join tt_custom_field_options cfo on (cfl.option_id = cfo.id)";
609 if ($includeCost && MODE_TIME != $user->tracking_mode)
610 $left_joins .= " left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id)";
612 $where = ttReportHelper::getFavWhere($options);
614 // Construct sql query for tt_log items.
615 $sql = "select ".join(', ', $fields)." from tt_log l $left_joins $where";
616 // If we don't have expense items (such as when the Expenses plugin is desabled), the above is all sql we need,
617 // with an exception of sorting part, that is added in the end.
619 // However, when we have expenses, we need to do a union with a separate query for expense items from tt_expense_items table.
620 if ($options['show_cost'] && $user->isPluginEnabled('ex')) { // if ex(penses) plugin is enabled
622 $fields = array(); // An array of fields for database query.
623 array_push($fields, 'ei.id');
624 array_push($fields, '2 as type'); // Type 2 is for tt_expense_items entries.
625 array_push($fields, 'ei.date');
626 if($canViewReports || $isClient)
627 array_push($fields, 'u.name as user');
628 // Add client name if it is selected.
629 if ($options['show_client'] || 'client' == $group_by_option)
630 array_push($fields, 'c.name as client');
631 // Add project name if it is selected.
632 if ($options['show_project'] || 'project' == $group_by_option)
633 array_push($fields, 'p.name as project');
634 if ($options['show_task'] || 'task' == $group_by_option)
635 array_push($fields, 'null'); // null for task name. We need to match column count for union.
636 if ($options['show_custom_field_1'] || 'cf_1' == $group_by_option)
637 array_push($fields, 'null'); // null for cf_1.
638 if ($options['show_start']) {
639 array_push($fields, 'null'); // null for unformatted_start.
640 array_push($fields, 'null'); // null for start.
642 if ($options['show_end'])
643 array_push($fields, 'null'); // null for finish.
644 if ($options['show_duration'])
645 array_push($fields, 'null'); // null for duration.
646 if ($options['show_work_units'])
647 array_push($fields, 'null as units'); // null for work units.
648 // Use the note field to print item name.
649 if ($options['show_note'])
650 array_push($fields, 'ei.name as note');
651 array_push($fields, 'ei.cost as cost');
652 array_push($fields, 'ei.cost as expense');
654 if ($canViewReports && $options['show_paid'])
655 array_push($fields, 'ei.paid as paid');
657 if ($canViewReports && $options['show_ip']) {
658 array_push($fields, 'ei.created as created');
659 array_push($fields, 'ei.created_ip as created_ip');
660 array_push($fields, 'ei.modified as modified');
661 array_push($fields, 'ei.modified_ip as modified_ip');
663 // Add invoice name if it is selected.
664 if (($canViewReports || $isClient) && $options['show_invoice'])
665 array_push($fields, 'i.name as invoice');
667 // Prepare sql query part for left joins.
669 if ($canViewReports || $isClient)
670 $left_joins .= " left join tt_users u on (u.id = ei.user_id)";
671 if ($options['show_client'] || 'client' == $group_by_option)
672 $left_joins .= " left join tt_clients c on (c.id = ei.client_id)";
673 if ($options['show_project'] || 'project' == $group_by_option)
674 $left_joins .= " left join tt_projects p on (p.id = ei.project_id)";
675 if (($canViewReports || $isClient) && $options['show_invoice'])
676 $left_joins .= " left join tt_invoices i on (i.id = ei.invoice_id and i.status = 1)";
678 $where = ttReportHelper::getFavExpenseWhere($options);
680 // Construct sql query for expense items.
681 $sql_for_expense_items = "select ".join(', ', $fields)." from tt_expense_items ei $left_joins $where";
683 // Construct a union.
684 $sql = "($sql) union all ($sql_for_expense_items)";
687 // Determine sort part.
688 $sort_part = ' order by ';
689 if ($group_by_option == null || 'no_grouping' == $group_by_option || 'date' == $group_by_option) // TODO: fix DB for NULL values in group_by field.
690 $sort_part .= 'date';
692 $sort_part .= $group_by_option.', date';
693 if (($canViewReports || $isClient) /*&& is_array($bean->getAttribute('users'))*/ && 'user' != $group_by_option)
694 $sort_part .= ', user, type';
695 if ($options['show_start'])
696 $sort_part .= ', unformatted_start';
697 $sort_part .= ', id';
700 // By now we are ready with sql.
702 // Obtain items for report.
703 $res = $mdb2->query($sql);
704 if (is_a($res, 'PEAR_Error')) die($res->getMessage());
706 while ($val = $res->fetchRow()) {
707 if ($convertTo12Hour) {
708 if($val['start'] != '')
709 $val['start'] = ttTimeHelper::to12HourFormat($val['start']);
710 if($val['finish'] != '')
711 $val['finish'] = ttTimeHelper::to12HourFormat($val['finish']);
713 if (isset($val['cost'])) {
714 if ('.' != $user->decimal_mark)
715 $val['cost'] = str_replace('.', $user->decimal_mark, $val['cost']);
717 if (isset($val['expense'])) {
718 if ('.' != $user->decimal_mark)
719 $val['expense'] = str_replace('.', $user->decimal_mark, $val['expense']);
721 if ('no_grouping' != $group_by_option) {
722 $val['grouped_by'] = $val[$group_by_option];
723 if ('date' == $group_by_option) {
724 // This is needed to get the date in user date format.
725 $o_date = new DateAndTime(DB_DATEFORMAT, $val['grouped_by']);
726 $val['grouped_by'] = $o_date->toString($user->date_format);
731 // This is needed to get the date in user date format.
732 $o_date = new DateAndTime(DB_DATEFORMAT, $val['date']);
733 $val['date'] = $o_date->toString($user->date_format);
737 $report_items[] = $row;
740 return $report_items;
743 // getSubtotals calculates report items subtotals when a report is grouped by.
744 // Without expenses, it's a simple select with group by.
745 // With expenses, it becomes a select with group by from a combined set of records obtained with "union all".
746 static function getSubtotals($bean, $options) {
749 $group_by_option = $bean->getAttribute('group_by');
750 if ('no_grouping' == $group_by_option) return null;
752 $mdb2 = getConnection();
754 // Start with sql to obtain subtotals for time items. This simple sql will be used when we have no expenses.
756 // Determine group by field and a required join.
757 switch ($group_by_option) {
759 $group_field = 'l.date';
763 $group_field = 'u.name';
764 $group_join = 'left join tt_users u on (l.user_id = u.id) ';
767 $group_field = 'c.name';
768 $group_join = 'left join tt_clients c on (l.client_id = c.id) ';
771 $group_field = 'p.name';
772 $group_join = 'left join tt_projects p on (l.project_id = p.id) ';
775 $group_field = 't.name';
776 $group_join = 'left join tt_tasks t on (l.task_id = t.id) ';
779 $group_field = 'cfo.value';
780 $custom_fields = new CustomFields($user->group_id);
781 if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_TEXT)
782 $group_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) ';
783 elseif ($custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN)
784 $group_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) ';
788 $where = ttReportHelper::getWhere($bean, $options);
789 if ($bean->getAttribute('chcost')) {
790 if (MODE_TIME == $user->tracking_mode) {
791 if ($group_by_option != 'user')
792 $left_join = 'left join tt_users u on (l.user_id = u.id)';
793 $sql = "select $group_field as group_field, sum(time_to_sec(l.duration)) as time";
794 if ($bean->getAttribute('chunits')) {
795 if ($user->unit_totals_only)
796 $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";
798 $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";
800 $sql .= ", sum(cast(l.billable * coalesce(u.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10, 2))) as cost,
801 null as expenses from tt_log l
802 $group_join $left_join $where group by $group_field";
804 // If we are including cost and tracking projects, our query (the same as above) needs to join the tt_user_project_binds table.
805 $sql = "select $group_field as group_field, sum(time_to_sec(l.duration)) as time";
806 if ($bean->getAttribute('chunits')) {
807 if ($user->unit_totals_only)
808 $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";
810 $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";
812 $sql .= ", sum(cast(l.billable * coalesce(upb.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10,2))) as cost,
813 null as expenses from tt_log l
815 left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id) $where group by $group_field";
818 $sql = "select $group_field as group_field, sum(time_to_sec(l.duration)) as time";
819 if ($bean->getAttribute('chunits')) {
820 if ($user->unit_totals_only)
821 $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";
823 $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";
825 $sql .= ", null as expenses from tt_log l
826 $group_join $where group by $group_field";
828 // By now we have sql for time items.
830 // However, when we have expenses, we need to do a union with a separate query for expense items from tt_expense_items table.
831 if ($bean->getAttribute('chcost') && $user->isPluginEnabled('ex')) { // if ex(penses) plugin is enabled
833 // Determine group by field and a required join.
835 $group_field = 'null';
836 switch ($group_by_option) {
838 $group_field = 'ei.date';
842 $group_field = 'u.name';
843 $group_join = 'left join tt_users u on (ei.user_id = u.id) ';
846 $group_field = 'c.name';
847 $group_join = 'left join tt_clients c on (ei.client_id = c.id) ';
850 $group_field = 'p.name';
851 $group_join = 'left join tt_projects p on (ei.project_id = p.id) ';
855 $where = ttReportHelper::getExpenseWhere($bean, $options);
856 $sql_for_expenses = "select $group_field as group_field, null as time";
857 if ($bean->getAttribute('chunits')) $sql_for_expenses .= ", null as units";
858 $sql_for_expenses .= ", sum(ei.cost) as cost, sum(ei.cost) as expenses from tt_expense_items ei $group_join $where";
859 // Add a "group by" clause if we are grouping.
860 if ('null' != $group_field) $sql_for_expenses .= " group by $group_field";
862 // Create a combined query.
863 $combined = "select group_field, sum(time) as time";
864 if ($bean->getAttribute('chunits')) $combined .= ", sum(units) as units";
865 $combined .= ", sum(cost) as cost, sum(expenses) as expenses from (($sql) union all ($sql_for_expenses)) t group by group_field";
870 $res = $mdb2->query($sql);
871 if (is_a($res, 'PEAR_Error')) die($res->getMessage());
873 while ($val = $res->fetchRow()) {
874 if ('date' == $group_by_option) {
875 // This is needed to get the date in user date format.
876 $o_date = new DateAndTime(DB_DATEFORMAT, $val['group_field']);
877 $val['group_field'] = $o_date->toString($user->date_format);
880 $time = $val['time'] ? sec_to_time_fmt_hm($val['time']) : null;
881 if ($bean->getAttribute('chcost')) {
882 if ('.' != $user->decimal_mark) {
883 $val['cost'] = str_replace('.', $user->decimal_mark, $val['cost']);
884 $val['expenses'] = str_replace('.', $user->decimal_mark, $val['expenses']);
886 $subtotals[$val['group_field']] = array('name'=>$val['group_field'],'time'=>$time, 'units'=> $val['units'],'cost'=>$val['cost'],'expenses'=>$val['expenses']);
888 $subtotals[$val['group_field']] = array('name'=>$val['group_field'],'time'=>$time, 'units'=> $val['units']);
894 // getFavSubtotals calculates report items subtotals when a favorite report is grouped by.
895 // Without expenses, it's a simple select with group by.
896 // With expenses, it becomes a select with group by from a combined set of records obtained with "union all".
897 static function getFavSubtotals($options) {
900 $group_by_option = $options['group_by'];
901 if ('no_grouping' == $group_by_option) return null;
903 $mdb2 = getConnection();
905 // Start with sql to obtain subtotals for time items. This simple sql will be used when we have no expenses.
907 // Determine group by field and a required join.
908 switch ($group_by_option) {
910 $group_field = 'l.date';
914 $group_field = 'u.name';
915 $group_join = 'left join tt_users u on (l.user_id = u.id) ';
918 $group_field = 'c.name';
919 $group_join = 'left join tt_clients c on (l.client_id = c.id) ';
922 $group_field = 'p.name';
923 $group_join = 'left join tt_projects p on (l.project_id = p.id) ';
926 $group_field = 't.name';
927 $group_join = 'left join tt_tasks t on (l.task_id = t.id) ';
930 $group_field = 'cfo.value';
931 $custom_fields = new CustomFields($user->group_id);
932 if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_TEXT)
933 $group_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) ';
934 elseif ($custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN)
935 $group_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) ';
939 $where = ttReportHelper::getFavWhere($options);
940 if ($options['show_cost']) {
941 if (MODE_TIME == $user->tracking_mode) {
942 if ($group_by_option != 'user')
943 $left_join = 'left join tt_users u on (l.user_id = u.id)';
944 $sql = "select $group_field as group_field, sum(time_to_sec(l.duration)) as time";
945 if ($options['show_work_units']) {
946 if ($user->unit_totals_only)
947 $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";
949 $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";
951 $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";
952 $sql .= ", sum(cast(l.billable * coalesce(u.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10, 2))) as cost,
953 null as expenses from tt_log l
954 $group_join $left_join $where group by $group_field";
956 // If we are including cost and tracking projects, our query (the same as above) needs to join the tt_user_project_binds table.
957 $sql = "select $group_field as group_field, sum(time_to_sec(l.duration)) as time";
958 if ($options['show_work_units']) {
959 if ($user->unit_totals_only)
960 $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";
962 $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";
964 $sql .= ", sum(cast(l.billable * coalesce(upb.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10,2))) as cost,
965 null as expenses from tt_log l
967 left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id) $where group by $group_field";
970 $sql = "select $group_field as group_field, sum(time_to_sec(l.duration)) as time";
971 if ($options['show_work_units']) {
972 if ($user->unit_totals_only)
973 $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";
975 $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";
977 $sql .= ", null as expenses from tt_log l
978 $group_join $where group by $group_field";
980 // By now we have sql for time items.
982 // However, when we have expenses, we need to do a union with a separate query for expense items from tt_expense_items table.
983 if ($options['show_cost'] && $user->isPluginEnabled('ex')) { // if ex(penses) plugin is enabled
985 // Determine group by field and a required join.
987 $group_field = 'null';
988 switch ($group_by_option) {
990 $group_field = 'ei.date';
994 $group_field = 'u.name';
995 $group_join = 'left join tt_users u on (ei.user_id = u.id) ';
998 $group_field = 'c.name';
999 $group_join = 'left join tt_clients c on (ei.client_id = c.id) ';
1002 $group_field = 'p.name';
1003 $group_join = 'left join tt_projects p on (ei.project_id = p.id) ';
1007 $where = ttReportHelper::getFavExpenseWhere($options);
1008 $sql_for_expenses = "select $group_field as group_field, null as time";
1009 if ($options['show_work_units']) $sql_for_expenses .= ", null as units";
1010 $sql_for_expenses .= ", sum(ei.cost) as cost, sum(ei.cost) as expenses from tt_expense_items ei $group_join $where";
1011 // Add a "group by" clause if we are grouping.
1012 if ('null' != $group_field) $sql_for_expenses .= " group by $group_field";
1014 // Create a combined query.
1015 $combined = "select group_field, sum(time) as time";
1016 if ($options['show_work_units']) $combined .= ", sum(units) as units";
1017 $combined .= ", sum(cost) as cost, sum(expenses) as expenses from (($sql) union all ($sql_for_expenses)) t group by group_field";
1022 $res = $mdb2->query($sql);
1023 if (is_a($res, 'PEAR_Error')) die($res->getMessage());
1025 while ($val = $res->fetchRow()) {
1026 if ('date' == $group_by_option) {
1027 // This is needed to get the date in user date format.
1028 $o_date = new DateAndTime(DB_DATEFORMAT, $val['group_field']);
1029 $val['group_field'] = $o_date->toString($user->date_format);
1032 $time = $val['time'] ? sec_to_time_fmt_hm($val['time']) : null;
1033 if ($options['show_cost']) {
1034 if ('.' != $user->decimal_mark) {
1035 $val['cost'] = str_replace('.', $user->decimal_mark, $val['cost']);
1036 $val['expenses'] = str_replace('.', $user->decimal_mark, $val['expenses']);
1038 $subtotals[$val['group_field']] = array('name'=>$val['group_field'],'time'=>$time, 'units'=> $val['units'], 'cost'=>$val['cost'],'expenses'=>$val['expenses']);
1040 $subtotals[$val['group_field']] = array('name'=>$val['group_field'],'time'=>$time, 'units'=> $val['units']);
1046 // getTotals calculates total hours and cost for all report items.
1047 static function getTotals($bean, $options)
1051 $mdb2 = getConnection();
1053 $where = ttReportHelper::getWhere($bean, $options);
1056 $time_part = "sum(time_to_sec(l.duration)) as time";
1057 if ($bean->getAttribute('chunits')) {
1058 $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";
1060 if ($bean->getAttribute('chcost')) {
1061 if (MODE_TIME == $user->tracking_mode)
1062 $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";
1064 $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";
1066 $cost_part = ", null as cost, null as expenses";
1068 if ($bean->getAttribute('chcost')) {
1069 if (MODE_TIME == $user->tracking_mode) {
1070 $left_joins = "left join tt_users u on (l.user_id = u.id)";
1072 $left_joins = "left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id)";
1075 // Prepare a query for time items.
1076 $sql = "select $time_part $units_part $cost_part from tt_log l $left_joins $where";
1078 // If we have expenses, query becomes a bit more complex.
1079 if ($bean->getAttribute('chcost') && $user->isPluginEnabled('ex')) {
1080 $where = ttReportHelper::getExpenseWhere($bean, $options);
1081 $sql_for_expenses = "select null as time";
1082 if ($bean->getAttribute('chunits')) $sql_for_expenses .= ", null as units";
1083 $sql_for_expenses .= ", sum(cost) as cost, sum(cost) as expenses from tt_expense_items ei $where";
1085 // Create a combined query.
1086 $combined = "select sum(time) as time";
1087 if ($bean->getAttribute('chunits')) $combined .= ", sum(units) as units";
1088 $combined .= ", sum(cost) as cost, sum(expenses) as expenses from (($sql) union all ($sql_for_expenses)) t";
1093 $res = $mdb2->query($sql);
1094 if (is_a($res, 'PEAR_Error')) die($res->getMessage());
1096 $val = $res->fetchRow();
1097 $total_time = $val['time'] ? sec_to_time_fmt_hm($val['time']) : null;
1098 if ($bean->getAttribute('chcost')) {
1099 $total_cost = $val['cost'];
1100 if (!$total_cost) $total_cost = '0.00';
1101 if ('.' != $user->decimal_mark)
1102 $total_cost = str_replace('.', $user->decimal_mark, $total_cost);
1103 $total_expenses = $val['expenses'];
1104 if (!$total_expenses) $total_expenses = '0.00';
1105 if ('.' != $user->decimal_mark)
1106 $total_expenses = str_replace('.', $user->decimal_mark, $total_expenses);
1109 if ($bean->getAttribute('period'))
1110 $period = new Period($bean->getAttribute('period'), new DateAndTime($user->date_format));
1112 $period = new Period();
1114 new DateAndTime($user->date_format, $bean->getAttribute('start_date')),
1115 new DateAndTime($user->date_format, $bean->getAttribute('end_date')));
1118 $totals['start_date'] = $period->getStartDate();
1119 $totals['end_date'] = $period->getEndDate();
1120 $totals['time'] = $total_time;
1121 $totals['units'] = $val['units'];
1122 $totals['cost'] = $total_cost;
1123 $totals['expenses'] = $total_expenses;
1128 // getFavTotals calculates total hours and cost for all favorite report items.
1129 static function getFavTotals($options)
1133 $mdb2 = getConnection();
1135 $where = ttReportHelper::getFavWhere($options);
1138 $time_part = "sum(time_to_sec(l.duration)) as time";
1139 if ($options['show_work_units']) {
1140 $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";
1142 if ($options['show_cost']) {
1143 if (MODE_TIME == $user->tracking_mode)
1144 $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";
1146 $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";
1148 $cost_part = ", null as cost, null as expenses";
1150 if ($options['show_cost']) {
1151 if (MODE_TIME == $user->tracking_mode) {
1152 $left_joins = "left join tt_users u on (l.user_id = u.id)";
1154 $left_joins = "left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id)";
1157 // Prepare a query for time items.
1158 $sql = "select $time_part $units_part $cost_part from tt_log l $left_joins $where";
1160 // If we have expenses, query becomes a bit more complex.
1161 if ($options['show_cost'] && $user->isPluginEnabled('ex')) {
1162 $where = ttReportHelper::getFavExpenseWhere($options);
1163 $sql_for_expenses = "select null as time";
1164 if ($options['show_work_units']) $sql_for_expenses .= ", null as units";
1165 $sql_for_expenses .= ", sum(cost) as cost, sum(cost) as expenses from tt_expense_items ei $where";
1167 // Create a combined query.
1168 $combined = "select sum(time) as time";
1169 if ($options['show_work_units']) $combined .= ", sum(units) as units";
1170 $combined .= ", sum(cost) as cost, sum(expenses) as expenses from (($sql) union all ($sql_for_expenses)) t";
1175 $res = $mdb2->query($sql);
1176 if (is_a($res, 'PEAR_Error')) die($res->getMessage());
1178 $val = $res->fetchRow();
1179 $total_time = $val['time'] ? sec_to_time_fmt_hm($val['time']) : null;
1180 if ($options['show_cost']) {
1181 $total_cost = $val['cost'];
1182 if (!$total_cost) $total_cost = '0.00';
1183 if ('.' != $user->decimal_mark)
1184 $total_cost = str_replace('.', $user->decimal_mark, $total_cost);
1185 $total_expenses = $val['expenses'];
1186 if (!$total_expenses) $total_expenses = '0.00';
1187 if ('.' != $user->decimal_mark)
1188 $total_expenses = str_replace('.', $user->decimal_mark, $total_expenses);
1191 if ($options['period'])
1192 $period = new Period($options['period'], new DateAndTime($user->date_format));
1194 $period = new Period();
1196 new DateAndTime($user->date_format, $options['period_start']),
1197 new DateAndTime($user->date_format, $options['period_end']));
1200 $totals['start_date'] = $period->getStartDate();
1201 $totals['end_date'] = $period->getEndDate();
1202 $totals['time'] = $total_time;
1203 $totals['units'] = $val['units'];
1204 $totals['cost'] = $total_cost;
1205 $totals['expenses'] = $total_expenses;
1210 // The assignToInvoice assigns a set of records to a specific invoice.
1211 static function assignToInvoice($invoice_id, $time_log_ids, $expense_item_ids)
1213 $mdb2 = getConnection();
1214 if ($time_log_ids) {
1215 $sql = "update tt_log set invoice_id = ".$mdb2->quote($invoice_id).
1216 " where id in(".join(', ', $time_log_ids).")";
1217 $affected = $mdb2->exec($sql);
1218 if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
1220 if ($expense_item_ids) {
1221 $sql = "update tt_expense_items set invoice_id = ".$mdb2->quote($invoice_id).
1222 " where id in(".join(', ', $expense_item_ids).")";
1223 $affected = $mdb2->exec($sql);
1224 if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
1228 // The markPaid marks a set of records as either paid or unpaid.
1229 static function markPaid($time_log_ids, $expense_item_ids, $paid = true)
1231 $mdb2 = getConnection();
1232 $paid_val = (int) $paid;
1233 if ($time_log_ids) {
1234 $sql = "update tt_log set paid = $paid_val where id in(".join(', ', $time_log_ids).")";
1235 $affected = $mdb2->exec($sql);
1236 if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
1238 if ($expense_item_ids) {
1239 $sql = "update tt_expense_items set paid = $paid_val where id in(".join(', ', $expense_item_ids).")";
1240 $affected = $mdb2->exec($sql);
1241 if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
1245 // prepareReportBody - prepares an email body for report.
1246 static function prepareReportBody($bean, $comment)
1251 // Determine these once as they are used in multiple places in this function.
1252 $canViewReports = $user->can('view_reports');
1253 $isClient = $user->isClient();
1254 $options = ttReportHelper::getReportOptions($bean);
1256 $items = ttReportHelper::getItems($bean, $options);
1257 $group_by = $bean->getAttribute('group_by');
1258 if ($group_by && 'no_grouping' != $group_by)
1259 $subtotals = ttReportHelper::getSubtotals($bean, $options);
1260 $totals = ttReportHelper::getTotals($bean, $options);
1262 // Use custom fields plugin if it is enabled.
1263 if ($user->isPluginEnabled('cf'))
1264 $custom_fields = new CustomFields($user->group_id);
1266 // Define some styles to use in email.
1267 $style_title = 'text-align: center; font-size: 15pt; font-family: Arial, Helvetica, sans-serif;';
1268 $tableHeader = 'font-weight: bold; background-color: #a6ccf7; text-align: left;';
1269 $tableHeaderCentered = 'font-weight: bold; background-color: #a6ccf7; text-align: center;';
1270 $rowItem = 'background-color: #ffffff;';
1271 $rowItemAlt = 'background-color: #f5f5f5;';
1272 $rowSubtotal = 'background-color: #e0e0e0;';
1273 $cellLeftAligned = 'text-align: left; vertical-align: top;';
1274 $cellRightAligned = 'text-align: right; vertical-align: top;';
1275 $cellLeftAlignedSubtotal = 'font-weight: bold; text-align: left; vertical-align: top;';
1276 $cellRightAlignedSubtotal = 'font-weight: bold; text-align: right; vertical-align: top;';
1278 // Start creating email body.
1280 $body .= '<head><meta http-equiv="content-type" content="text/html; charset='.CHARSET.'"></head>';
1284 $body .= '<p style="'.$style_title.'">'.$i18n->get('form.mail.report_subject').': '.$totals['start_date'].' - '.$totals['end_date'].'</p>';
1287 if ($comment) $body .= '<p>'.htmlspecialchars($comment).'</p>';
1289 if ($bean->getAttribute('chtotalsonly')) {
1290 // Totals only report. Output subtotals.
1292 // Determine group_by header.
1293 if ('cf_1' == $group_by)
1294 $group_by_header = htmlspecialchars($custom_fields->fields[0]['label']);
1296 $key = 'label.'.$group_by;
1297 $group_by_header = $i18n->get($key);
1300 $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
1302 $body .= '<td style="'.$tableHeader.'">'.$group_by_header.'</td>';
1303 if ($bean->getAttribute('chduration'))
1304 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.duration').'</td>';
1305 if ($bean->getAttribute('chunits'))
1306 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.work_units_short').'</td>';
1307 if ($bean->getAttribute('chcost'))
1308 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.cost').'</td>';
1310 foreach($subtotals as $subtotal) {
1311 $body .= '<tr style="'.$rowSubtotal.'">';
1312 $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($subtotal['name'] ? htmlspecialchars($subtotal['name']) : ' ').'</td>';
1313 if ($bean->getAttribute('chduration')) {
1314 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1315 if ($subtotal['time'] <> '0:00') $body .= $subtotal['time'];
1318 if ($bean->getAttribute('chunits')) {
1319 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1320 $body .= $subtotal['units'];
1323 if ($bean->getAttribute('chcost')) {
1324 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1325 $body .= ($canViewReports || $isClient) ? $subtotal['cost'] : $subtotal['expenses'];
1332 $body .= '<tr><td> </td></tr>';
1333 $body .= '<tr style="'.$rowSubtotal.'">';
1334 $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.total').'</td>';
1335 if ($bean->getAttribute('chduration')) {
1336 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1337 if ($totals['time'] <> '0:00') $body .= $totals['time'];
1340 if ($bean->getAttribute('chunits')) {
1341 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1342 $body .= $totals['units'];
1345 if ($bean->getAttribute('chcost')) {
1346 $body .= '<td nowrap style="'.$cellRightAlignedSubtotal.'">'.htmlspecialchars($user->currency).' ';
1347 $body .= ($canViewReports || $isClient) ? $totals['cost'] : $totals['expenses'];
1352 $body .= '</table>';
1356 // Print table header.
1357 $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
1359 $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.date').'</td>';
1360 if ($canViewReports || $isClient)
1361 $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.user').'</td>';
1362 if ($bean->getAttribute('chclient'))
1363 $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.client').'</td>';
1364 if ($bean->getAttribute('chproject'))
1365 $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.project').'</td>';
1366 if ($bean->getAttribute('chtask'))
1367 $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.task').'</td>';
1368 if ($bean->getAttribute('chcf_1'))
1369 $body .= '<td style="'.$tableHeader.'">'.htmlspecialchars($custom_fields->fields[0]['label']).'</td>';
1370 if ($bean->getAttribute('chstart'))
1371 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.start').'</td>';
1372 if ($bean->getAttribute('chfinish'))
1373 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.finish').'</td>';
1374 if ($bean->getAttribute('chduration'))
1375 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.duration').'</td>';
1376 if ($bean->getAttribute('chunits'))
1377 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.work_units_short').'</td>';
1378 if ($bean->getAttribute('chnote'))
1379 $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.note').'</td>';
1380 if ($bean->getAttribute('chcost'))
1381 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.cost').'</td>';
1382 if ($bean->getAttribute('chpaid'))
1383 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.paid').'</td>';
1384 if ($bean->getAttribute('chip'))
1385 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.ip').'</td>';
1386 if ($bean->getAttribute('chinvoice'))
1387 $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.invoice').'</td>';
1390 // Initialize variables to print subtotals.
1391 if ($items && 'no_grouping' != $group_by) {
1392 $print_subtotals = true;
1394 $prev_grouped_by = '';
1395 $cur_grouped_by = '';
1397 // Initialize variables to alternate color of rows for different dates.
1400 $row_style = $rowItem;
1402 // Print report items.
1403 if (is_array($items)) {
1404 foreach ($items as $record) {
1405 $cur_date = $record['date'];
1406 // Print a subtotal row after a block of grouped items.
1407 if ($print_subtotals) {
1408 $cur_grouped_by = $record['grouped_by'];
1409 if ($cur_grouped_by != $prev_grouped_by && !$first_pass) {
1410 $body .= '<tr style="'.$rowSubtotal.'">';
1411 $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.subtotal').'</td>';
1412 $subtotal_name = htmlspecialchars($subtotals[$prev_grouped_by]['name']);
1413 if ($canViewReports || $isClient) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'user' ? $subtotal_name : '').'</td>';
1414 if ($bean->getAttribute('chclient')) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'client' ? $subtotal_name : '').'</td>';
1415 if ($bean->getAttribute('chproject')) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'project' ? $subtotal_name : '').'</td>';
1416 if ($bean->getAttribute('chtask')) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'task' ? $subtotal_name : '').'</td>';
1417 if ($bean->getAttribute('chcf_1')) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'cf_1' ? $subtotal_name : '').'</td>';
1418 if ($bean->getAttribute('chstart')) $body .= '<td></td>';
1419 if ($bean->getAttribute('chfinish')) $body .= '<td></td>';
1420 if ($bean->getAttribute('chduration')) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['time'].'</td>';
1421 if ($bean->getAttribute('chunits')) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['units'].'</td>';
1422 if ($bean->getAttribute('chnote')) $body .= '<td></td>';
1423 if ($bean->getAttribute('chcost')) {
1424 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1425 $body .= ($canViewReports || $isClient) ? $subtotals[$prev_grouped_by]['cost'] : $subtotals[$prev_grouped_by]['expenses'];
1428 if ($bean->getAttribute('chpaid')) $body .= '<td></td>';
1429 if ($bean->getAttribute('chip')) $body .= '<td></td>';
1430 if ($bean->getAttribute('chinvoice')) $body .= '<td></td>';
1432 $body .= '<tr><td> </td></tr>';
1434 $first_pass = false;
1437 // Print a regular row.
1438 if ($cur_date != $prev_date)
1439 $row_style = ($row_style == $rowItem) ? $rowItemAlt : $rowItem;
1440 $body .= '<tr style="'.$row_style.'">';
1441 $body .= '<td style="'.$cellLeftAligned.'">'.$record['date'].'</td>';
1442 if ($canViewReports || $isClient)
1443 $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['user']).'</td>';
1444 if ($bean->getAttribute('chclient'))
1445 $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['client']).'</td>';
1446 if ($bean->getAttribute('chproject'))
1447 $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['project']).'</td>';
1448 if ($bean->getAttribute('chtask'))
1449 $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['task']).'</td>';
1450 if ($bean->getAttribute('chcf_1'))
1451 $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['cf_1']).'</td>';
1452 if ($bean->getAttribute('chstart'))
1453 $body .= '<td nowrap style="'.$cellRightAligned.'">'.$record['start'].'</td>';
1454 if ($bean->getAttribute('chfinish'))
1455 $body .= '<td nowrap style="'.$cellRightAligned.'">'.$record['finish'].'</td>';
1456 if ($bean->getAttribute('chduration'))
1457 $body .= '<td style="'.$cellRightAligned.'">'.$record['duration'].'</td>';
1458 if ($bean->getAttribute('chunits'))
1459 $body .= '<td style="'.$cellRightAligned.'">'.$record['units'].'</td>';
1460 if ($bean->getAttribute('chnote'))
1461 $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['note']).'</td>';
1462 if ($bean->getAttribute('chcost'))
1463 $body .= '<td style="'.$cellRightAligned.'">'.$record['cost'].'</td>';
1464 if ($bean->getAttribute('chpaid')) {
1465 $body .= '<td style="'.$cellRightAligned.'">';
1466 $body .= $record['paid'] == 1 ? $i18n->get('label.yes') : $i18n->get('label.no');
1469 if ($bean->getAttribute('chip')) {
1470 $body .= '<td style="'.$cellRightAligned.'">';
1471 $body .= $record['modified'] ? $record['modified_ip'].' '.$record['modified'] : $record['created_ip'].' '.$record['created'];
1474 if ($bean->getAttribute('chinvoice'))
1475 $body .= '<td style="'.$cellRightAligned.'">'.htmlspecialchars($record['invoice']).'</td>';
1478 $prev_date = $record['date'];
1479 if ($print_subtotals)
1480 $prev_grouped_by = $record['grouped_by'];
1484 // Print a terminating subtotal.
1485 if ($print_subtotals) {
1486 $body .= '<tr style="'.$rowSubtotal.'">';
1487 $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.subtotal').'</td>';
1488 $subtotal_name = htmlspecialchars($subtotals[$cur_grouped_by]['name']);
1489 if ($canViewReports || $isClient) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'user' ? $subtotal_name : '').'</td>';
1490 if ($bean->getAttribute('chclient')) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'client' ? $subtotal_name : '').'</td>';
1491 if ($bean->getAttribute('chproject')) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'project' ? $subtotal_name : '').'</td>';
1492 if ($bean->getAttribute('chtask')) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'task' ? $subtotal_name : '').'</td>';
1493 if ($bean->getAttribute('chcf_1')) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'cf_1' ? $subtotal_name : '').'</td>';
1494 if ($bean->getAttribute('chstart')) $body .= '<td></td>';
1495 if ($bean->getAttribute('chfinish')) $body .= '<td></td>';
1496 if ($bean->getAttribute('chduration')) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$cur_grouped_by]['time'].'</td>';
1497 if ($bean->getAttribute('chunits')) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$cur_grouped_by]['units'].'</td>';
1498 if ($bean->getAttribute('chnote')) $body .= '<td></td>';
1499 if ($bean->getAttribute('chcost')) {
1500 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1501 $body .= ($canViewReports || $isClient) ? $subtotals[$cur_grouped_by]['cost'] : $subtotals[$cur_grouped_by]['expenses'];
1504 if ($bean->getAttribute('chpaid')) $body .= '<td></td>';
1505 if ($bean->getAttribute('chip')) $body .= '<td></td>';
1506 if ($bean->getAttribute('chinvoice')) $body .= '<td></td>';
1511 $body .= '<tr><td> </td></tr>';
1512 $body .= '<tr style="'.$rowSubtotal.'">';
1513 $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.total').'</td>';
1514 if ($canViewReports || $isClient) $body .= '<td></td>';
1515 if ($bean->getAttribute('chclient')) $body .= '<td></td>';
1516 if ($bean->getAttribute('chproject')) $body .= '<td></td>';
1517 if ($bean->getAttribute('chtask')) $body .= '<td></td>';
1518 if ($bean->getAttribute('chcf_1')) $body .= '<td></td>';
1519 if ($bean->getAttribute('chstart')) $body .= '<td></td>';
1520 if ($bean->getAttribute('chfinish')) $body .= '<td></td>';
1521 if ($bean->getAttribute('chduration')) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$totals['time'].'</td>';
1522 if ($bean->getAttribute('chunits')) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$totals['units'].'</td>';
1523 if ($bean->getAttribute('chnote')) $body .= '<td></td>';
1524 if ($bean->getAttribute('chcost')) {
1525 $body .= '<td nowrap style="'.$cellRightAlignedSubtotal.'">'.htmlspecialchars($user->currency).' ';
1526 $body .= ($canViewReports || $isClient) ? $totals['cost'] : $totals['expenses'];
1529 if ($bean->getAttribute('chpaid')) $body .= '<td></td>';
1530 if ($bean->getAttribute('chip')) $body .= '<td></td>';
1531 if ($bean->getAttribute('chinvoice')) $body .= '<td></td>';
1534 $body .= '</table>';
1538 if (!defined('REPORT_FOOTER') || !(REPORT_FOOTER == false))
1539 $body .= '<p style="text-align: center;">'.$i18n->get('form.mail.footer').'</p>';
1541 // Finish creating email body.
1542 $body .= '</body></html>';
1547 // checkFavReportCondition - checks whether it is okay to send fav report.
1548 static function checkFavReportCondition($options, $condition)
1550 $items = ttReportHelper::getFavItems($options);
1552 $condition = str_replace('count', '', $condition);
1553 $count_required = (int) trim(str_replace('>', '', $condition));
1555 if (count($items) > $count_required)
1556 return true; // Condition ok.
1561 // prepareFavReportBody - prepares an email body for a favorite report.
1562 static function prepareFavReportBody($options)
1567 // Determine these once as they are used in multiple places in this function.
1568 $canViewReports = $user->can('view_reports');
1569 $isClient = $user->isClient();
1571 $items = ttReportHelper::getFavItems($options);
1572 $group_by = $options['group_by'];
1573 if ($group_by && 'no_grouping' != $group_by)
1574 $subtotals = ttReportHelper::getFavSubtotals($options);
1575 $totals = ttReportHelper::getFavTotals($options);
1577 // Use custom fields plugin if it is enabled.
1578 if ($user->isPluginEnabled('cf'))
1579 $custom_fields = new CustomFields($user->group_id);
1581 // Define some styles to use in email.
1582 $style_title = 'text-align: center; font-size: 15pt; font-family: Arial, Helvetica, sans-serif;';
1583 $tableHeader = 'font-weight: bold; background-color: #a6ccf7; text-align: left;';
1584 $tableHeaderCentered = 'font-weight: bold; background-color: #a6ccf7; text-align: center;';
1585 $rowItem = 'background-color: #ffffff;';
1586 $rowItemAlt = 'background-color: #f5f5f5;';
1587 $rowSubtotal = 'background-color: #e0e0e0;';
1588 $cellLeftAligned = 'text-align: left; vertical-align: top;';
1589 $cellRightAligned = 'text-align: right; vertical-align: top;';
1590 $cellLeftAlignedSubtotal = 'font-weight: bold; text-align: left; vertical-align: top;';
1591 $cellRightAlignedSubtotal = 'font-weight: bold; text-align: right; vertical-align: top;';
1593 // Start creating email body.
1595 $body .= '<head><meta http-equiv="content-type" content="text/html; charset='.CHARSET.'"></head>';
1599 $body .= '<p style="'.$style_title.'">'.$i18n->get('form.mail.report_subject').': '.$totals['start_date'].' - '.$totals['end_date'].'</p>';
1602 // if ($comment) $body .= '<p>'.htmlspecialchars($comment).'</p>'; // No comment for fav. reports.
1604 if ($options['show_totals_only']) {
1605 // Totals only report. Output subtotals.
1607 // Determine group_by header.
1608 if ('cf_1' == $group_by)
1609 $group_by_header = htmlspecialchars($custom_fields->fields[0]['label']);
1611 $key = 'label.'.$group_by;
1612 $group_by_header = $i18n->get($key);
1615 $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
1617 $body .= '<td style="'.$tableHeader.'">'.$group_by_header.'</td>';
1618 if ($options['show_duration'])
1619 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.duration').'</td>';
1620 if ($options['show_work_units'])
1621 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.work_units_short').'</td>';
1622 if ($options['show_cost'])
1623 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.cost').'</td>';
1625 foreach($subtotals as $subtotal) {
1626 $body .= '<tr style="'.$rowSubtotal.'">';
1627 $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($subtotal['name'] ? htmlspecialchars($subtotal['name']) : ' ').'</td>';
1628 if ($options['show_duration']) {
1629 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1630 if ($subtotal['time'] <> '0:00') $body .= $subtotal['time'];
1633 if ($options['show_work_units']) {
1634 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1635 $body .= $subtotal['units'];
1638 if ($options['show_cost']) {
1639 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1640 $body .= ($canViewReports || $isClient) ? $subtotal['cost'] : $subtotal['expenses'];
1647 $body .= '<tr><td> </td></tr>';
1648 $body .= '<tr style="'.$rowSubtotal.'">';
1649 $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.total').'</td>';
1650 if ($options['show_duration']) {
1651 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1652 if ($totals['time'] <> '0:00') $body .= $totals['time'];
1655 if ($options['show_work_units']) {
1656 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1657 $body .= $totals['units'];
1660 if ($options['show_cost']) {
1661 $body .= '<td nowrap style="'.$cellRightAlignedSubtotal.'">'.htmlspecialchars($user->currency).' ';
1662 $body .= ($canViewReports || $isClient) ? $totals['cost'] : $totals['expenses'];
1667 $body .= '</table>';
1671 // Print table header.
1672 $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
1674 $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.date').'</td>';
1675 if ($canViewReports || $isClient)
1676 $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.user').'</td>';
1677 if ($options['show_client'])
1678 $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.client').'</td>';
1679 if ($options['show_project'])
1680 $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.project').'</td>';
1681 if ($options['show_task'])
1682 $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.task').'</td>';
1683 if ($options['show_custom_field_1'])
1684 $body .= '<td style="'.$tableHeader.'">'.htmlspecialchars($custom_fields->fields[0]['label']).'</td>';
1685 if ($options['show_start'])
1686 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.start').'</td>';
1687 if ($options['show_end'])
1688 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.finish').'</td>';
1689 if ($options['show_duration'])
1690 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.duration').'</td>';
1691 if ($options['show_work_units'])
1692 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.work_units_short').'</td>';
1693 if ($options['show_note'])
1694 $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.note').'</td>';
1695 if ($options['show_cost'])
1696 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.cost').'</td>';
1697 if ($options['show_paid'])
1698 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.paid').'</td>';
1699 if ($options['show_ip'])
1700 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.ip').'</td>';
1701 if ($options['show_invoice'])
1702 $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.invoice').'</td>';
1705 // Initialize variables to print subtotals.
1706 if ($items && 'no_grouping' != $group_by) {
1707 $print_subtotals = true;
1709 $prev_grouped_by = '';
1710 $cur_grouped_by = '';
1712 // Initialize variables to alternate color of rows for different dates.
1715 $row_style = $rowItem;
1717 // Print report items.
1718 if (is_array($items)) {
1719 foreach ($items as $record) {
1720 $cur_date = $record['date'];
1721 // Print a subtotal row after a block of grouped items.
1722 if ($print_subtotals) {
1723 $cur_grouped_by = $record['grouped_by'];
1724 if ($cur_grouped_by != $prev_grouped_by && !$first_pass) {
1725 $body .= '<tr style="'.$rowSubtotal.'">';
1726 $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.subtotal').'</td>';
1727 $subtotal_name = htmlspecialchars($subtotals[$prev_grouped_by]['name']);
1728 if ($canViewReports || $isClient) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'user' ? $subtotal_name : '').'</td>';
1729 if ($options['show_client']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'client' ? $subtotal_name : '').'</td>';
1730 if ($options['show_project']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'project' ? $subtotal_name : '').'</td>';
1731 if ($options['show_task']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'task' ? $subtotal_name : '').'</td>';
1732 if ($options['show_custom_field_1']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'cf_1' ? $subtotal_name : '').'</td>';
1733 if ($options['show_start']) $body .= '<td></td>';
1734 if ($options['show_end']) $body .= '<td></td>';
1735 if ($options['show_duration']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['time'].'</td>';
1736 if ($options['show_work_units']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['units'].'</td>';
1737 if ($options['show_note']) $body .= '<td></td>';
1738 if ($options['show_cost']) {
1739 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1740 $body .= ($canViewReports || $isClient) ? $subtotals[$prev_grouped_by]['cost'] : $subtotals[$prev_grouped_by]['expenses'];
1743 if ($options['show_paid']) $body .= '<td></td>';
1744 if ($options['show_ip']) $body .= '<td></td>';
1745 if ($options['show_invoice']) $body .= '<td></td>';
1747 $body .= '<tr><td> </td></tr>';
1749 $first_pass = false;
1752 // Print a regular row.
1753 if ($cur_date != $prev_date)
1754 $row_style = ($row_style == $rowItem) ? $rowItemAlt : $rowItem;
1755 $body .= '<tr style="'.$row_style.'">';
1756 $body .= '<td style="'.$cellLeftAligned.'">'.$record['date'].'</td>';
1757 if ($canViewReports || $isClient)
1758 $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['user']).'</td>';
1759 if ($options['show_client'])
1760 $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['client']).'</td>';
1761 if ($options['show_project'])
1762 $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['project']).'</td>';
1763 if ($options['show_task'])
1764 $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['task']).'</td>';
1765 if ($options['show_custom_field_1'])
1766 $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['cf_1']).'</td>';
1767 if ($options['show_start'])
1768 $body .= '<td nowrap style="'.$cellRightAligned.'">'.$record['start'].'</td>';
1769 if ($options['show_end'])
1770 $body .= '<td nowrap style="'.$cellRightAligned.'">'.$record['finish'].'</td>';
1771 if ($options['show_duration'])
1772 $body .= '<td style="'.$cellRightAligned.'">'.$record['duration'].'</td>';
1773 if ($options['show_work_units'])
1774 $body .= '<td style="'.$cellRightAligned.'">'.$record['units'].'</td>';
1775 if ($options['show_note'])
1776 $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['note']).'</td>';
1777 if ($options['show_cost'])
1778 $body .= '<td style="'.$cellRightAligned.'">'.$record['cost'].'</td>';
1779 if ($options['show_paid']) {
1780 $body .= '<td style="'.$cellRightAligned.'">';
1781 $body .= $record['paid'] == 1 ? $i18n->get('label.yes') : $i18n->get('label.no');
1784 if ($options['show_ip']) {
1785 $body .= '<td style="'.$cellRightAligned.'">';
1786 $body .= $record['modified'] ? $record['modified_ip'].' '.$record['modified'] : $record['created_ip'].' '.$record['created'];
1789 if ($options['show_invoice'])
1790 $body .= '<td style="'.$cellRightAligned.'">'.htmlspecialchars($record['invoice']).'</td>';
1793 $prev_date = $record['date'];
1794 if ($print_subtotals)
1795 $prev_grouped_by = $record['grouped_by'];
1799 // Print a terminating subtotal.
1800 if ($print_subtotals) {
1801 $body .= '<tr style="'.$rowSubtotal.'">';
1802 $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.subtotal').'</td>';
1803 $subtotal_name = htmlspecialchars($subtotals[$cur_grouped_by]['name']);
1804 if ($canViewReports || $isClient) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'user' ? $subtotal_name : '').'</td>';
1805 if ($options['show_client']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'client' ? $subtotal_name : '').'</td>';
1806 if ($options['show_project']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'project' ? $subtotal_name : '').'</td>';
1807 if ($options['show_task']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'task' ? $subtotal_name : '').'</td>';
1808 if ($options['show_custom_field_1']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'cf_1' ? $subtotal_name : '').'</td>';
1809 if ($options['show_start']) $body .= '<td></td>';
1810 if ($options['show_end']) $body .= '<td></td>';
1811 if ($options['show_duration']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$cur_grouped_by]['time'].'</td>';
1812 if ($options['show_work_units']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$cur_grouped_by]['units'].'</td>';
1813 if ($options['show_note']) $body .= '<td></td>';
1814 if ($options['show_cost']) {
1815 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1816 $body .= ($canViewReports || $isClient) ? $subtotals[$cur_grouped_by]['cost'] : $subtotals[$cur_grouped_by]['expenses'];
1819 if ($options['show_paid']) $body .= '<td></td>';
1820 if ($options['show_ip']) $body .= '<td></td>';
1821 if ($options['show_invoice']) $body .= '<td></td>';
1826 $body .= '<tr><td> </td></tr>';
1827 $body .= '<tr style="'.$rowSubtotal.'">';
1828 $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.total').'</td>';
1829 if ($canViewReports || $isClient) $body .= '<td></td>';
1830 if ($options['show_client']) $body .= '<td></td>';
1831 if ($options['show_project']) $body .= '<td></td>';
1832 if ($options['show_task']) $body .= '<td></td>';
1833 if ($options['show_custom_field_1']) $body .= '<td></td>';
1834 if ($options['show_start']) $body .= '<td></td>';
1835 if ($options['show_end']) $body .= '<td></td>';
1836 if ($options['show_duration']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$totals['time'].'</td>';
1837 if ($options['show_work_units']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$totals['units'].'</td>';
1838 if ($options['show_note']) $body .= '<td></td>';
1839 if ($options['show_cost']) {
1840 $body .= '<td nowrap style="'.$cellRightAlignedSubtotal.'">'.htmlspecialchars($user->currency).' ';
1841 $body .= ($canViewReports || $isClient) ? $totals['cost'] : $totals['expenses'];
1844 if ($options['show_paid']) $body .= '<td></td>';
1845 if ($options['show_ip']) $body .= '<td></td>';
1846 if ($options['show_invoice']) $body .= '<td></td>';
1849 $body .= '</table>';
1853 if (!defined('REPORT_FOOTER') || !(REPORT_FOOTER == false))
1854 $body .= '<p style="text-align: center;">'.$i18n->get('form.mail.footer').'</p>';
1856 // Finish creating email body.
1857 $body .= '</body></html>';
1862 // sendFavReport - sends a favorite report to a specified email, called from cron.php
1863 static function sendFavReport($options, $subject, $email, $cc) {
1864 // We are called from cron.php, we have no $bean in session.
1865 // cron.php sets global $user and $i18n objects to match our favorite report user.
1869 // Prepare report body.
1870 $body = ttReportHelper::prepareFavReportBody($options);
1872 import('mail.Mailer');
1873 $mailer = new Mailer();
1874 $mailer->setCharSet(CHARSET);
1875 $mailer->setContentType('text/html');
1876 $mailer->setSender(SENDER);
1878 $mailer->setReceiverCC($cc);
1879 if (!empty($user->bcc_email))
1880 $mailer->setReceiverBCC($user->bcc_email);
1881 $mailer->setReceiver($email);
1882 $mailer->setMailMode(MAIL_MODE);
1883 if (empty($subject)) $subject = $options['name'];
1884 if (!$mailer->send($subject, $body))
1890 // getReportOptions - returns an array of report options constructed from session bean.
1892 // Note: similarly to ttFavReportHelper::getReportOptions, this function is a part of
1893 // refactoring to simplify maintenance of report generating functions, as we currently
1894 // have 2 sets: normal reporting (from bean), and fav report emailing (from db fields).
1895 // Using options obtained from either db or bean shall allow us to use only one set of functions.
1896 static function getReportOptions($bean) {
1899 // Prepare an array of report options.
1902 // Construct one by one.
1903 $options['name'] = null; // No name required.
1904 $options['user_id'] = $user->id; // Not sure if we need user_id here. Fav reports use it to recycle $user object in cron.php.
1905 $options['client_id'] = $bean->getAttribute('client');
1906 $options['cf_1_option_id'] = $bean->getAttribute('option');
1907 $options['project_id'] = $bean->getAttribute('project');
1908 $options['task_id'] = $bean->getAttribute('task');
1909 $options['billable'] = $bean->getAttribute('include_records');
1910 $options['invoice'] = $bean->getAttribute('invoice');
1911 $options['paid_status'] = $bean->getAttribute('paid_status');
1914 * TODO: remaining fields to fill in...
1915 `users` text default NULL, # Comma-separated list of user ids. Nothing here means "all" users.
1916 `period` tinyint(4) default NULL, # selected period type for report
1917 `period_start` date default NULL, # period start
1918 `period_end` date default NULL, # period end
1919 `show_client` tinyint(4) NOT NULL default 0, # whether to show client column
1920 `show_invoice` tinyint(4) NOT NULL default 0, # whether to show invoice column
1921 `show_paid` tinyint(4) NOT NULL default 0, # whether to show paid column
1922 `show_ip` tinyint(4) NOT NULL default 0, # whether to show ip column
1923 `show_project` tinyint(4) NOT NULL default 0, # whether to show project column
1924 `show_start` tinyint(4) NOT NULL default 0, # whether to show start field
1925 `show_duration` tinyint(4) NOT NULL default 0, # whether to show duration field
1926 `show_cost` tinyint(4) NOT NULL default 0, # whether to show cost field
1927 `show_task` tinyint(4) NOT NULL default 0, # whether to show task column
1928 `show_end` tinyint(4) NOT NULL default 0, # whether to show end field
1929 `show_note` tinyint(4) NOT NULL default 0, # whether to show note column
1930 `show_custom_field_1` tinyint(4) NOT NULL default 0, # whether to show custom field 1
1931 `show_work_units` tinyint(4) NOT NULL default 0, # whether to show work units
1932 `show_totals_only` tinyint(4) NOT NULL default 0, # whether to show totals only
1933 `group_by` varchar(20) default NULL, # group by field
1934 `status` tinyint(4) default 1, # favorite report status