2 // +----------------------------------------------------------------------+
3 // | Anuko Time Tracker
4 // +----------------------------------------------------------------------+
5 // | Copyright (c) Anuko International Ltd. (https://www.anuko.com)
6 // +----------------------------------------------------------------------+
7 // | LIBERAL FREEWARE LICENSE: This source code document may be used
8 // | by anyone for any purpose, and freely redistributed alone or in
9 // | combination with other software, provided that the license is obeyed.
11 // | There are only two ways to violate the license:
13 // | 1. To redistribute this code in source form, with the copyright
14 // | notice or license removed or altered. (Distributing in compiled
15 // | forms without embedded copyright notices is permitted).
17 // | 2. To redistribute modified versions of this code in *any* form
18 // | that bears insufficient indications that the modifications are
19 // | not the work of the original author(s).
21 // | This license applies to this document only, not any other software
22 // | that it may be combined with.
24 // +----------------------------------------------------------------------+
26 // | https://www.anuko.com/time_tracker/credits.htm
27 // +----------------------------------------------------------------------+
29 import('ttClientHelper');
30 import('DateAndTime');
32 import('ttTimeHelper');
34 require_once(dirname(__FILE__).'/../../plugins/CustomFields.class.php');
36 // Class ttReportHelper is used for help with reports.
37 class ttReportHelper {
39 // getWhere prepares a WHERE clause for a report query.
40 static function getWhere($options) {
43 // Prepare dropdown parts.
45 if ($options['client_id'])
46 $dropdown_parts .= ' and l.client_id = '.$options['client_id'];
47 elseif ($user->isClient() && $user->client_id)
48 $dropdown_parts .= ' and l.client_id = '.$user->client_id;
49 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'].')';
50 if ($options['project_id']) $dropdown_parts .= ' and l.project_id = '.$options['project_id'];
51 if ($options['task_id']) $dropdown_parts .= ' and l.task_id = '.$options['task_id'];
52 if ($options['billable']=='1') $dropdown_parts .= ' and l.billable = 1';
53 if ($options['billable']=='2') $dropdown_parts .= ' and l.billable = 0';
54 if ($options['invoice']=='1') $dropdown_parts .= ' and l.invoice_id is not NULL';
55 if ($options['invoice']=='2') $dropdown_parts .= ' and l.invoice_id is NULL';
56 if ($options['paid_status']=='1') $dropdown_parts .= ' and l.paid = 1';
57 if ($options['paid_status']=='2') $dropdown_parts .= ' and l.paid = 0';
59 // Prepare sql query part for user list.
60 $userlist = $options['users'] ? $options['users'] : '-1';
61 if ($user->can('view_reports') || $user->can('view_all_reports') || $user->isClient())
62 $user_list_part = " and l.user_id in ($userlist)";
64 $user_list_part = " and l.user_id = ".$user->id;
65 $user_list_part .= " and l.group_id = ".$user->getActiveGroup();
67 // Prepare sql query part for where.
68 if ($options['period'])
69 $period = new Period($options['period'], new DateAndTime($user->date_format));
71 $period = new Period();
73 new DateAndTime($user->date_format, $options['period_start']),
74 new DateAndTime($user->date_format, $options['period_end']));
76 $where = " where l.status = 1 and l.date >= '".$period->getStartDate(DB_DATEFORMAT)."' and l.date <= '".$period->getEndDate(DB_DATEFORMAT)."'".
77 " $user_list_part $dropdown_parts";
81 // getExpenseWhere prepares WHERE clause for expenses query in a report.
82 static function getExpenseWhere($options) {
85 // Prepare dropdown parts.
87 if ($options['client_id'])
88 $dropdown_parts .= ' and ei.client_id = '.$options['client_id'];
89 elseif ($user->isClient() && $user->client_id)
90 $dropdown_parts .= ' and ei.client_id = '.$user->client_id;
91 if ($options['project_id']) $dropdown_parts .= ' and ei.project_id = '.$options['project_id'];
92 if ($options['invoice']=='1') $dropdown_parts .= ' and ei.invoice_id is not NULL';
93 if ($options['invoice']=='2') $dropdown_parts .= ' and ei.invoice_id is NULL';
94 if ($options['paid_status']=='1') $dropdown_parts .= ' and ei.paid = 1';
95 if ($options['paid_status']=='2') $dropdown_parts .= ' and ei.paid = 0';
97 // Prepare sql query part for user list.
98 $userlist = $options['users'] ? $options['users'] : '-1';
99 if ($user->can('view_reports') || $user->can('view_all_reports') || $user->isClient())
100 $user_list_part = " and ei.user_id in ($userlist)";
102 $user_list_part = " and ei.user_id = ".$user->id;
103 $user_list_part .= " and ei.group_id = ".$user->getActiveGroup();
105 // Prepare sql query part for where.
106 if ($options['period'])
107 $period = new Period($options['period'], new DateAndTime($user->date_format));
109 $period = new Period();
111 new DateAndTime($user->date_format, $options['period_start']),
112 new DateAndTime($user->date_format, $options['period_end']));
114 $where = " where ei.status = 1 and ei.date >= '".$period->getStartDate(DB_DATEFORMAT)."' and ei.date <= '".$period->getEndDate(DB_DATEFORMAT)."'".
115 " $user_list_part $dropdown_parts";
119 // getItems retrieves all items associated with a report.
120 // It combines tt_log and tt_expense_items in one array for presentation in one table using mysql union all.
121 // Expense items use the "note" field for item name.
122 static function getItems($bean, $options) {
124 $mdb2 = getConnection();
126 // Determine these once as they are used in multiple places in this function.
127 $canViewReports = $user->can('view_reports');
128 $isClient = $user->isClient();
130 $group_by_option = $options['group_by'];
131 $convertTo12Hour = ('%I:%M %p' == $user->time_format) && ($options['show_start'] || $options['show_end']);
133 // Prepare a query for time items in tt_log table.
134 $fields = array(); // An array of fields for database query.
135 array_push($fields, 'l.id as id');
136 array_push($fields, '1 as type'); // Type 1 is for tt_log entries.
137 array_push($fields, 'l.date as date');
138 if($canViewReports || $isClient)
139 array_push($fields, 'u.name as user');
140 // Add client name if it is selected.
141 if ($options['show_client'] || 'client' == $group_by_option)
142 array_push($fields, 'c.name as client');
143 // Add project name if it is selected.
144 if ($options['show_project'] || 'project' == $group_by_option)
145 array_push($fields, 'p.name as project');
146 // Add task name if it is selected.
147 if ($options['show_task'] || 'task' == $group_by_option)
148 array_push($fields, 't.name as task');
150 $include_cf_1 = $options['show_custom_field_1'] || 'cf_1' == $group_by_option;
152 $custom_fields = new CustomFields($user->group_id);
153 $cf_1_type = $custom_fields->fields[0]['type'];
154 if ($cf_1_type == CustomFields::TYPE_TEXT) {
155 array_push($fields, 'cfl.value as cf_1');
156 } elseif ($cf_1_type == CustomFields::TYPE_DROPDOWN) {
157 array_push($fields, 'cfo.value as cf_1');
161 // TODO: refactoring in progress down from here... The above is identical to getFavItems and is ready to merge.
163 if ($bean->getAttribute('chstart')) {
164 array_push($fields, "l.start as unformatted_start");
165 array_push($fields, "TIME_FORMAT(l.start, '%k:%i') as start");
168 if ($bean->getAttribute('chfinish'))
169 array_push($fields, "TIME_FORMAT(sec_to_time(time_to_sec(l.start) + time_to_sec(l.duration)), '%k:%i') as finish");
171 if ($bean->getAttribute('chduration'))
172 array_push($fields, "TIME_FORMAT(l.duration, '%k:%i') as duration");
174 if ($bean->getAttribute('chunits')) {
175 if ($user->unit_totals_only)
176 array_push($fields, "null as units");
178 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");
181 if ($bean->getAttribute('chnote'))
182 array_push($fields, 'l.comment as note');
184 $includeCost = $bean->getAttribute('chcost');
186 if (MODE_TIME == $user->tracking_mode)
187 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.
189 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.
190 array_push($fields, "null as expense");
193 if ($canViewReports && $bean->getAttribute('chpaid'))
194 array_push($fields, 'l.paid as paid');
196 if ($canViewReports && $bean->getAttribute('chip')) {
197 array_push($fields, 'l.created as created');
198 array_push($fields, 'l.created_ip as created_ip');
199 array_push($fields, 'l.modified as modified');
200 array_push($fields, 'l.modified_ip as modified_ip');
203 // Add invoice name if it is selected.
204 if (($canViewReports || $isClient) && $bean->getAttribute('chinvoice'))
205 array_push($fields, 'i.name as invoice');
207 // Prepare sql query part for left joins.
209 if ($bean->getAttribute('chclient') || 'client' == $group_by_option)
210 $left_joins .= " left join tt_clients c on (c.id = l.client_id)";
211 if (($canViewReports || $isClient) && $bean->getAttribute('chinvoice'))
212 $left_joins .= " left join tt_invoices i on (i.id = l.invoice_id and i.status = 1)";
213 if ($canViewReports || $isClient || $user->isPluginEnabled('ex'))
214 $left_joins .= " left join tt_users u on (u.id = l.user_id)";
215 if ($bean->getAttribute('chproject') || 'project' == $group_by_option)
216 $left_joins .= " left join tt_projects p on (p.id = l.project_id)";
217 if ($bean->getAttribute('chtask') || 'task' == $group_by_option)
218 $left_joins .= " left join tt_tasks t on (t.id = l.task_id)";
220 if ($cf_1_type == CustomFields::TYPE_TEXT)
221 $left_joins .= " left join tt_custom_field_log cfl on (l.id = cfl.log_id and cfl.status = 1)";
222 elseif ($cf_1_type == CustomFields::TYPE_DROPDOWN) {
223 $left_joins .= " left join tt_custom_field_log cfl on (l.id = cfl.log_id and cfl.status = 1)".
224 " left join tt_custom_field_options cfo on (cfl.option_id = cfo.id)";
227 if ($includeCost && MODE_TIME != $user->tracking_mode)
228 $left_joins .= " left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id)";
230 $where = ttReportHelper::getWhere($options);
232 // Construct sql query for tt_log items.
233 $sql = "select ".join(', ', $fields)." from tt_log l $left_joins $where";
234 // If we don't have expense items (such as when the Expenses plugin is desabled), the above is all sql we need,
235 // with an exception of sorting part, that is added in the end.
237 // However, when we have expenses, we need to do a union with a separate query for expense items from tt_expense_items table.
238 if ($bean->getAttribute('chcost') && $user->isPluginEnabled('ex')) { // if ex(penses) plugin is enabled
240 $fields = array(); // An array of fields for database query.
241 array_push($fields, 'ei.id');
242 array_push($fields, '2 as type'); // Type 2 is for tt_expense_items entries.
243 array_push($fields, 'ei.date');
244 if($canViewReports || $isClient)
245 array_push($fields, 'u.name as user');
246 // Add client name if it is selected.
247 if ($bean->getAttribute('chclient') || 'client' == $group_by_option)
248 array_push($fields, 'c.name as client');
249 // Add project name if it is selected.
250 if ($bean->getAttribute('chproject') || 'project' == $group_by_option)
251 array_push($fields, 'p.name as project');
252 if ($bean->getAttribute('chtask') || 'task' == $group_by_option)
253 array_push($fields, 'null'); // null for task name. We need to match column count for union.
254 if ($bean->getAttribute('chcf_1') || 'cf_1' == $group_by_option)
255 array_push($fields, 'null'); // null for cf_1.
256 if ($bean->getAttribute('chstart')) {
257 array_push($fields, 'null'); // null for unformatted_start.
258 array_push($fields, 'null'); // null for start.
260 if ($bean->getAttribute('chfinish'))
261 array_push($fields, 'null'); // null for finish.
262 if ($bean->getAttribute('chduration'))
263 array_push($fields, 'null'); // null for duration.
265 if ($bean->getAttribute('chunits'))
266 array_push($fields, 'null as units'); // null for work units.
267 // Use the note field to print item name.
268 if ($bean->getAttribute('chnote'))
269 array_push($fields, 'ei.name as note');
270 array_push($fields, 'ei.cost as cost');
271 array_push($fields, 'ei.cost as expense');
273 if ($canViewReports && $bean->getAttribute('chpaid'))
274 array_push($fields, 'ei.paid as paid');
276 if ($canViewReports && $bean->getAttribute('chip')) {
277 array_push($fields, 'ei.created as created');
278 array_push($fields, 'ei.created_ip as created_ip');
279 array_push($fields, 'ei.modified as modified');
280 array_push($fields, 'ei.modified_ip as modified_ip');
283 // Add invoice name if it is selected.
284 if (($canViewReports || $isClient) && $bean->getAttribute('chinvoice'))
285 array_push($fields, 'i.name as invoice');
287 // Prepare sql query part for left joins.
289 if ($canViewReports || $isClient)
290 $left_joins .= " left join tt_users u on (u.id = ei.user_id)";
291 if ($bean->getAttribute('chclient') || 'client' == $group_by_option)
292 $left_joins .= " left join tt_clients c on (c.id = ei.client_id)";
293 if ($bean->getAttribute('chproject') || 'project' == $group_by_option)
294 $left_joins .= " left join tt_projects p on (p.id = ei.project_id)";
295 if (($canViewReports || $isClient) && $bean->getAttribute('chinvoice'))
296 $left_joins .= " left join tt_invoices i on (i.id = ei.invoice_id and i.status = 1)";
298 $where = ttReportHelper::getExpenseWhere($options);
300 // Construct sql query for expense items.
301 $sql_for_expense_items = "select ".join(', ', $fields)." from tt_expense_items ei $left_joins $where";
303 // Construct a union.
304 $sql = "($sql) union all ($sql_for_expense_items)";
307 // Determine sort part.
308 $sort_part = ' order by ';
309 if ('no_grouping' == $group_by_option || 'date' == $group_by_option)
310 $sort_part .= 'date';
312 $sort_part .= $group_by_option.', date';
313 if (($canViewReports || $isClient) && is_array($bean->getAttribute('users')) && 'user' != $group_by_option)
314 $sort_part .= ', user, type';
315 if ($bean->getAttribute('chstart'))
316 $sort_part .= ', unformatted_start';
317 $sort_part .= ', id';
320 // By now we are ready with sql.
322 // Obtain items for report.
323 $res = $mdb2->query($sql);
324 if (is_a($res, 'PEAR_Error')) die($res->getMessage());
326 while ($val = $res->fetchRow()) {
327 if ($convertTo12Hour) {
328 if($val['start'] != '')
329 $val['start'] = ttTimeHelper::to12HourFormat($val['start']);
330 if($val['finish'] != '')
331 $val['finish'] = ttTimeHelper::to12HourFormat($val['finish']);
333 if (isset($val['cost'])) {
334 if ('.' != $user->decimal_mark)
335 $val['cost'] = str_replace('.', $user->decimal_mark, $val['cost']);
337 if (isset($val['expense'])) {
338 if ('.' != $user->decimal_mark)
339 $val['expense'] = str_replace('.', $user->decimal_mark, $val['expense']);
341 if ('no_grouping' != $group_by_option) {
342 $val['grouped_by'] = $val[$group_by_option];
343 if ('date' == $group_by_option) {
344 // This is needed to get the date in user date format.
345 $o_date = new DateAndTime(DB_DATEFORMAT, $val['grouped_by']);
346 $val['grouped_by'] = $o_date->toString($user->date_format);
351 // This is needed to get the date in user date format.
352 $o_date = new DateAndTime(DB_DATEFORMAT, $val['date']);
353 $val['date'] = $o_date->toString($user->date_format);
357 $report_items[] = $row;
360 return $report_items;
363 // putInSession stores tt_log and tt_expense_items ids from a report in user session
364 // as 2 comma-separated lists.
365 static function putInSession($report_items) {
366 unset($_SESSION['report_item_ids']);
367 unset($_SESSION['report_item_expense_ids']);
369 // Iterate through records and build 2 comma-separated lists.
370 foreach($report_items as $item) {
371 if ($item['type'] == 1)
372 $report_item_ids .= ','.$item['id'];
373 else if ($item['type'] == 2)
374 $report_item_expense_ids .= ','.$item['id'];
376 $report_item_ids = trim($report_item_ids, ',');
377 $report_item_expense_ids = trim($report_item_expense_ids, ',');
379 // The lists are reqdy. Put them in session.
380 if ($report_item_ids) $_SESSION['report_item_ids'] = $report_item_ids;
381 if ($report_item_expense_ids) $_SESSION['report_item_expense_ids'] = $report_item_expense_ids;
384 // getFromSession obtains tt_log and tt_expense_items ids stored in user session.
385 static function getFromSession() {
387 $report_item_ids = $_SESSION['report_item_ids'];
388 if ($report_item_ids)
389 $items['report_item_ids'] = explode(',', $report_item_ids);
390 $report_item_expense_ids = $_SESSION['report_item_expense_ids'];
391 if ($report_item_expense_ids)
392 $items['report_item_expense_ids'] = explode(',', $report_item_expense_ids);
396 // getFavItems retrieves all items associated with a favorite report.
397 // It combines tt_log and tt_expense_items in one array for presentation in one table using mysql union all.
398 // Expense items use the "note" field for item name.
399 static function getFavItems($options) {
401 $mdb2 = getConnection();
403 // Determine these once as they are used in multiple places in this function.
404 $canViewReports = $user->can('view_reports');
405 $isClient = $user->isClient();
407 $group_by_option = $options['group_by'];
408 $convertTo12Hour = ('%I:%M %p' == $user->time_format) && ($options['show_start'] || $options['show_end']);
410 // Prepare a query for time items in tt_log table.
411 $fields = array(); // An array of fields for database query.
412 array_push($fields, 'l.id as id');
413 array_push($fields, '1 as type'); // Type 1 is for tt_log entries.
414 array_push($fields, 'l.date as date');
415 if($canViewReports || $isClient)
416 array_push($fields, 'u.name as user');
417 // Add client name if it is selected.
418 if ($options['show_client'] || 'client' == $group_by_option)
419 array_push($fields, 'c.name as client');
420 // Add project name if it is selected.
421 if ($options['show_project'] || 'project' == $group_by_option)
422 array_push($fields, 'p.name as project');
423 // Add task name if it is selected.
424 if ($options['show_task'] || 'task' == $group_by_option)
425 array_push($fields, 't.name as task');
427 $include_cf_1 = $options['show_custom_field_1'] || 'cf_1' == $group_by_option;
429 $custom_fields = new CustomFields($user->group_id);
430 $cf_1_type = $custom_fields->fields[0]['type'];
431 if ($cf_1_type == CustomFields::TYPE_TEXT) {
432 array_push($fields, 'cfl.value as cf_1');
433 } elseif ($cf_1_type == CustomFields::TYPE_DROPDOWN) {
434 array_push($fields, 'cfo.value as cf_1');
438 if ($options['show_start']) {
439 array_push($fields, "l.start as unformatted_start");
440 array_push($fields, "TIME_FORMAT(l.start, '%k:%i') as start");
443 if ($options['show_end'])
444 array_push($fields, "TIME_FORMAT(sec_to_time(time_to_sec(l.start) + time_to_sec(l.duration)), '%k:%i') as finish");
446 if ($options['show_duration'])
447 array_push($fields, "TIME_FORMAT(l.duration, '%k:%i') as duration");
449 if ($options['show_work_units']) {
450 if ($user->unit_totals_only)
451 array_push($fields, "null as units");
453 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");
457 if ($options['show_note'])
458 array_push($fields, 'l.comment as note');
460 $includeCost = $options['show_cost'];
462 if (MODE_TIME == $user->tracking_mode)
463 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.
465 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.
466 array_push($fields, "null as expense");
469 if ($canViewReports && $options['show_paid'])
470 array_push($fields, 'l.paid as paid');
472 if ($canViewReports && $options['show_ip']) {
473 array_push($fields, 'l.created as created');
474 array_push($fields, 'l.created_ip as created_ip');
475 array_push($fields, 'l.modified as modified');
476 array_push($fields, 'l.modified_ip as modified_ip');
478 // Add invoice name if it is selected.
479 if (($canViewReports || $isClient) && $options['show_invoice'])
480 array_push($fields, 'i.name as invoice');
482 // Prepare sql query part for left joins.
484 if ($options['show_client'] || 'client' == $group_by_option)
485 $left_joins .= " left join tt_clients c on (c.id = l.client_id)";
486 if (($canViewReports || $isClient) && $options['show_invoice'])
487 $left_joins .= " left join tt_invoices i on (i.id = l.invoice_id and i.status = 1)";
488 if ($canViewReports || $isClient || $user->isPluginEnabled('ex'))
489 $left_joins .= " left join tt_users u on (u.id = l.user_id)";
490 if ($options['show_project'] || 'project' == $group_by_option)
491 $left_joins .= " left join tt_projects p on (p.id = l.project_id)";
492 if ($options['show_task'] || 'task' == $group_by_option)
493 $left_joins .= " left join tt_tasks t on (t.id = l.task_id)";
495 if ($cf_1_type == CustomFields::TYPE_TEXT)
496 $left_joins .= " left join tt_custom_field_log cfl on (l.id = cfl.log_id and cfl.status = 1)";
497 elseif ($cf_1_type == CustomFields::TYPE_DROPDOWN) {
498 $left_joins .= " left join tt_custom_field_log cfl on (l.id = cfl.log_id and cfl.status = 1)".
499 " left join tt_custom_field_options cfo on (cfl.option_id = cfo.id)";
502 if ($includeCost && MODE_TIME != $user->tracking_mode)
503 $left_joins .= " left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id)";
505 $where = ttReportHelper::getWhere($options);
507 // Construct sql query for tt_log items.
508 $sql = "select ".join(', ', $fields)." from tt_log l $left_joins $where";
509 // If we don't have expense items (such as when the Expenses plugin is desabled), the above is all sql we need,
510 // with an exception of sorting part, that is added in the end.
512 // However, when we have expenses, we need to do a union with a separate query for expense items from tt_expense_items table.
513 if ($options['show_cost'] && $user->isPluginEnabled('ex')) { // if ex(penses) plugin is enabled
515 $fields = array(); // An array of fields for database query.
516 array_push($fields, 'ei.id');
517 array_push($fields, '2 as type'); // Type 2 is for tt_expense_items entries.
518 array_push($fields, 'ei.date');
519 if($canViewReports || $isClient)
520 array_push($fields, 'u.name as user');
521 // Add client name if it is selected.
522 if ($options['show_client'] || 'client' == $group_by_option)
523 array_push($fields, 'c.name as client');
524 // Add project name if it is selected.
525 if ($options['show_project'] || 'project' == $group_by_option)
526 array_push($fields, 'p.name as project');
527 if ($options['show_task'] || 'task' == $group_by_option)
528 array_push($fields, 'null'); // null for task name. We need to match column count for union.
529 if ($options['show_custom_field_1'] || 'cf_1' == $group_by_option)
530 array_push($fields, 'null'); // null for cf_1.
531 if ($options['show_start']) {
532 array_push($fields, 'null'); // null for unformatted_start.
533 array_push($fields, 'null'); // null for start.
535 if ($options['show_end'])
536 array_push($fields, 'null'); // null for finish.
537 if ($options['show_duration'])
538 array_push($fields, 'null'); // null for duration.
539 if ($options['show_work_units'])
540 array_push($fields, 'null as units'); // null for work units.
541 // Use the note field to print item name.
542 if ($options['show_note'])
543 array_push($fields, 'ei.name as note');
544 array_push($fields, 'ei.cost as cost');
545 array_push($fields, 'ei.cost as expense');
547 if ($canViewReports && $options['show_paid'])
548 array_push($fields, 'ei.paid as paid');
550 if ($canViewReports && $options['show_ip']) {
551 array_push($fields, 'ei.created as created');
552 array_push($fields, 'ei.created_ip as created_ip');
553 array_push($fields, 'ei.modified as modified');
554 array_push($fields, 'ei.modified_ip as modified_ip');
556 // Add invoice name if it is selected.
557 if (($canViewReports || $isClient) && $options['show_invoice'])
558 array_push($fields, 'i.name as invoice');
560 // Prepare sql query part for left joins.
562 if ($canViewReports || $isClient)
563 $left_joins .= " left join tt_users u on (u.id = ei.user_id)";
564 if ($options['show_client'] || 'client' == $group_by_option)
565 $left_joins .= " left join tt_clients c on (c.id = ei.client_id)";
566 if ($options['show_project'] || 'project' == $group_by_option)
567 $left_joins .= " left join tt_projects p on (p.id = ei.project_id)";
568 if (($canViewReports || $isClient) && $options['show_invoice'])
569 $left_joins .= " left join tt_invoices i on (i.id = ei.invoice_id and i.status = 1)";
571 $where = ttReportHelper::getExpenseWhere($options);
573 // Construct sql query for expense items.
574 $sql_for_expense_items = "select ".join(', ', $fields)." from tt_expense_items ei $left_joins $where";
576 // Construct a union.
577 $sql = "($sql) union all ($sql_for_expense_items)";
580 // Determine sort part.
581 $sort_part = ' order by ';
582 if ($group_by_option == null || 'no_grouping' == $group_by_option || 'date' == $group_by_option) // TODO: fix DB for NULL values in group_by field.
583 $sort_part .= 'date';
585 $sort_part .= $group_by_option.', date';
586 if (($canViewReports || $isClient) /*&& is_array($bean->getAttribute('users'))*/ && 'user' != $group_by_option)
587 $sort_part .= ', user, type';
588 if ($options['show_start'])
589 $sort_part .= ', unformatted_start';
590 $sort_part .= ', id';
593 // By now we are ready with sql.
595 // Obtain items for report.
596 $res = $mdb2->query($sql);
597 if (is_a($res, 'PEAR_Error')) die($res->getMessage());
599 while ($val = $res->fetchRow()) {
600 if ($convertTo12Hour) {
601 if($val['start'] != '')
602 $val['start'] = ttTimeHelper::to12HourFormat($val['start']);
603 if($val['finish'] != '')
604 $val['finish'] = ttTimeHelper::to12HourFormat($val['finish']);
606 if (isset($val['cost'])) {
607 if ('.' != $user->decimal_mark)
608 $val['cost'] = str_replace('.', $user->decimal_mark, $val['cost']);
610 if (isset($val['expense'])) {
611 if ('.' != $user->decimal_mark)
612 $val['expense'] = str_replace('.', $user->decimal_mark, $val['expense']);
614 if ('no_grouping' != $group_by_option) {
615 $val['grouped_by'] = $val[$group_by_option];
616 if ('date' == $group_by_option) {
617 // This is needed to get the date in user date format.
618 $o_date = new DateAndTime(DB_DATEFORMAT, $val['grouped_by']);
619 $val['grouped_by'] = $o_date->toString($user->date_format);
624 // This is needed to get the date in user date format.
625 $o_date = new DateAndTime(DB_DATEFORMAT, $val['date']);
626 $val['date'] = $o_date->toString($user->date_format);
630 $report_items[] = $row;
633 return $report_items;
636 // getSubtotals calculates report items subtotals when a report is grouped by.
637 // Without expenses, it's a simple select with group by.
638 // With expenses, it becomes a select with group by from a combined set of records obtained with "union all".
639 static function getSubtotals($bean, $options) {
642 $group_by_option = $bean->getAttribute('group_by');
643 if ('no_grouping' == $group_by_option) return null;
645 $mdb2 = getConnection();
647 // Start with sql to obtain subtotals for time items. This simple sql will be used when we have no expenses.
649 // Determine group by field and a required join.
650 switch ($group_by_option) {
652 $group_field = 'l.date';
656 $group_field = 'u.name';
657 $group_join = 'left join tt_users u on (l.user_id = u.id) ';
660 $group_field = 'c.name';
661 $group_join = 'left join tt_clients c on (l.client_id = c.id) ';
664 $group_field = 'p.name';
665 $group_join = 'left join tt_projects p on (l.project_id = p.id) ';
668 $group_field = 't.name';
669 $group_join = 'left join tt_tasks t on (l.task_id = t.id) ';
672 $group_field = 'cfo.value';
673 $custom_fields = new CustomFields($user->group_id);
674 if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_TEXT)
675 $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) ';
676 elseif ($custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN)
677 $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) ';
681 $where = ttReportHelper::getWhere($options);
682 if ($bean->getAttribute('chcost')) {
683 if (MODE_TIME == $user->tracking_mode) {
684 if ($group_by_option != 'user')
685 $left_join = 'left join tt_users u on (l.user_id = u.id)';
686 $sql = "select $group_field as group_field, sum(time_to_sec(l.duration)) as time";
687 if ($bean->getAttribute('chunits')) {
688 if ($user->unit_totals_only)
689 $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";
691 $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";
693 $sql .= ", sum(cast(l.billable * coalesce(u.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10, 2))) as cost,
694 null as expenses from tt_log l
695 $group_join $left_join $where group by $group_field";
697 // If we are including cost and tracking projects, our query (the same as above) needs to join the tt_user_project_binds table.
698 $sql = "select $group_field as group_field, sum(time_to_sec(l.duration)) as time";
699 if ($bean->getAttribute('chunits')) {
700 if ($user->unit_totals_only)
701 $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";
703 $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";
705 $sql .= ", sum(cast(l.billable * coalesce(upb.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10,2))) as cost,
706 null as expenses from tt_log l
708 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";
711 $sql = "select $group_field as group_field, sum(time_to_sec(l.duration)) as time";
712 if ($bean->getAttribute('chunits')) {
713 if ($user->unit_totals_only)
714 $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";
716 $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";
718 $sql .= ", null as expenses from tt_log l
719 $group_join $where group by $group_field";
721 // By now we have sql for time items.
723 // However, when we have expenses, we need to do a union with a separate query for expense items from tt_expense_items table.
724 if ($bean->getAttribute('chcost') && $user->isPluginEnabled('ex')) { // if ex(penses) plugin is enabled
726 // Determine group by field and a required join.
728 $group_field = 'null';
729 switch ($group_by_option) {
731 $group_field = 'ei.date';
735 $group_field = 'u.name';
736 $group_join = 'left join tt_users u on (ei.user_id = u.id) ';
739 $group_field = 'c.name';
740 $group_join = 'left join tt_clients c on (ei.client_id = c.id) ';
743 $group_field = 'p.name';
744 $group_join = 'left join tt_projects p on (ei.project_id = p.id) ';
748 $where = ttReportHelper::getExpenseWhere($options);
749 $sql_for_expenses = "select $group_field as group_field, null as time";
750 if ($bean->getAttribute('chunits')) $sql_for_expenses .= ", null as units";
751 $sql_for_expenses .= ", sum(ei.cost) as cost, sum(ei.cost) as expenses from tt_expense_items ei $group_join $where";
752 // Add a "group by" clause if we are grouping.
753 if ('null' != $group_field) $sql_for_expenses .= " group by $group_field";
755 // Create a combined query.
756 $combined = "select group_field, sum(time) as time";
757 if ($bean->getAttribute('chunits')) $combined .= ", sum(units) as units";
758 $combined .= ", sum(cost) as cost, sum(expenses) as expenses from (($sql) union all ($sql_for_expenses)) t group by group_field";
763 $res = $mdb2->query($sql);
764 if (is_a($res, 'PEAR_Error')) die($res->getMessage());
766 while ($val = $res->fetchRow()) {
767 if ('date' == $group_by_option) {
768 // This is needed to get the date in user date format.
769 $o_date = new DateAndTime(DB_DATEFORMAT, $val['group_field']);
770 $val['group_field'] = $o_date->toString($user->date_format);
773 $time = $val['time'] ? sec_to_time_fmt_hm($val['time']) : null;
774 if ($bean->getAttribute('chcost')) {
775 if ('.' != $user->decimal_mark) {
776 $val['cost'] = str_replace('.', $user->decimal_mark, $val['cost']);
777 $val['expenses'] = str_replace('.', $user->decimal_mark, $val['expenses']);
779 $subtotals[$val['group_field']] = array('name'=>$val['group_field'],'time'=>$time, 'units'=> $val['units'],'cost'=>$val['cost'],'expenses'=>$val['expenses']);
781 $subtotals[$val['group_field']] = array('name'=>$val['group_field'],'time'=>$time, 'units'=> $val['units']);
787 // getFavSubtotals calculates report items subtotals when a favorite report is grouped by.
788 // Without expenses, it's a simple select with group by.
789 // With expenses, it becomes a select with group by from a combined set of records obtained with "union all".
790 static function getFavSubtotals($options) {
793 $group_by_option = $options['group_by'];
794 if ('no_grouping' == $group_by_option) return null;
796 $mdb2 = getConnection();
798 // Start with sql to obtain subtotals for time items. This simple sql will be used when we have no expenses.
800 // Determine group by field and a required join.
801 switch ($group_by_option) {
803 $group_field = 'l.date';
807 $group_field = 'u.name';
808 $group_join = 'left join tt_users u on (l.user_id = u.id) ';
811 $group_field = 'c.name';
812 $group_join = 'left join tt_clients c on (l.client_id = c.id) ';
815 $group_field = 'p.name';
816 $group_join = 'left join tt_projects p on (l.project_id = p.id) ';
819 $group_field = 't.name';
820 $group_join = 'left join tt_tasks t on (l.task_id = t.id) ';
823 $group_field = 'cfo.value';
824 $custom_fields = new CustomFields($user->group_id);
825 if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_TEXT)
826 $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) ';
827 elseif ($custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN)
828 $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) ';
832 $where = ttReportHelper::getWhere($options);
833 if ($options['show_cost']) {
834 if (MODE_TIME == $user->tracking_mode) {
835 if ($group_by_option != 'user')
836 $left_join = 'left join tt_users u on (l.user_id = u.id)';
837 $sql = "select $group_field as group_field, sum(time_to_sec(l.duration)) as time";
838 if ($options['show_work_units']) {
839 if ($user->unit_totals_only)
840 $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";
842 $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";
844 $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";
845 $sql .= ", sum(cast(l.billable * coalesce(u.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10, 2))) as cost,
846 null as expenses from tt_log l
847 $group_join $left_join $where group by $group_field";
849 // If we are including cost and tracking projects, our query (the same as above) needs to join the tt_user_project_binds table.
850 $sql = "select $group_field as group_field, sum(time_to_sec(l.duration)) as time";
851 if ($options['show_work_units']) {
852 if ($user->unit_totals_only)
853 $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";
855 $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";
857 $sql .= ", sum(cast(l.billable * coalesce(upb.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10,2))) as cost,
858 null as expenses from tt_log l
860 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";
863 $sql = "select $group_field as group_field, sum(time_to_sec(l.duration)) as time";
864 if ($options['show_work_units']) {
865 if ($user->unit_totals_only)
866 $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";
868 $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";
870 $sql .= ", null as expenses from tt_log l
871 $group_join $where group by $group_field";
873 // By now we have sql for time items.
875 // However, when we have expenses, we need to do a union with a separate query for expense items from tt_expense_items table.
876 if ($options['show_cost'] && $user->isPluginEnabled('ex')) { // if ex(penses) plugin is enabled
878 // Determine group by field and a required join.
880 $group_field = 'null';
881 switch ($group_by_option) {
883 $group_field = 'ei.date';
887 $group_field = 'u.name';
888 $group_join = 'left join tt_users u on (ei.user_id = u.id) ';
891 $group_field = 'c.name';
892 $group_join = 'left join tt_clients c on (ei.client_id = c.id) ';
895 $group_field = 'p.name';
896 $group_join = 'left join tt_projects p on (ei.project_id = p.id) ';
900 $where = ttReportHelper::getExpenseWhere($options);
901 $sql_for_expenses = "select $group_field as group_field, null as time";
902 if ($options['show_work_units']) $sql_for_expenses .= ", null as units";
903 $sql_for_expenses .= ", sum(ei.cost) as cost, sum(ei.cost) as expenses from tt_expense_items ei $group_join $where";
904 // Add a "group by" clause if we are grouping.
905 if ('null' != $group_field) $sql_for_expenses .= " group by $group_field";
907 // Create a combined query.
908 $combined = "select group_field, sum(time) as time";
909 if ($options['show_work_units']) $combined .= ", sum(units) as units";
910 $combined .= ", sum(cost) as cost, sum(expenses) as expenses from (($sql) union all ($sql_for_expenses)) t group by group_field";
915 $res = $mdb2->query($sql);
916 if (is_a($res, 'PEAR_Error')) die($res->getMessage());
918 while ($val = $res->fetchRow()) {
919 if ('date' == $group_by_option) {
920 // This is needed to get the date in user date format.
921 $o_date = new DateAndTime(DB_DATEFORMAT, $val['group_field']);
922 $val['group_field'] = $o_date->toString($user->date_format);
925 $time = $val['time'] ? sec_to_time_fmt_hm($val['time']) : null;
926 if ($options['show_cost']) {
927 if ('.' != $user->decimal_mark) {
928 $val['cost'] = str_replace('.', $user->decimal_mark, $val['cost']);
929 $val['expenses'] = str_replace('.', $user->decimal_mark, $val['expenses']);
931 $subtotals[$val['group_field']] = array('name'=>$val['group_field'],'time'=>$time, 'units'=> $val['units'], 'cost'=>$val['cost'],'expenses'=>$val['expenses']);
933 $subtotals[$val['group_field']] = array('name'=>$val['group_field'],'time'=>$time, 'units'=> $val['units']);
939 // getTotals calculates total hours and cost for all report items.
940 static function getTotals($bean, $options)
944 $mdb2 = getConnection();
946 $where = ttReportHelper::getWhere($options);
949 $time_part = "sum(time_to_sec(l.duration)) as time";
950 if ($bean->getAttribute('chunits')) {
951 $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";
953 if ($bean->getAttribute('chcost')) {
954 if (MODE_TIME == $user->tracking_mode)
955 $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";
957 $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";
959 $cost_part = ", null as cost, null as expenses";
961 if ($bean->getAttribute('chcost')) {
962 if (MODE_TIME == $user->tracking_mode) {
963 $left_joins = "left join tt_users u on (l.user_id = u.id)";
965 $left_joins = "left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id)";
968 // Prepare a query for time items.
969 $sql = "select $time_part $units_part $cost_part from tt_log l $left_joins $where";
971 // If we have expenses, query becomes a bit more complex.
972 if ($bean->getAttribute('chcost') && $user->isPluginEnabled('ex')) {
973 $where = ttReportHelper::getExpenseWhere($options);
974 $sql_for_expenses = "select null as time";
975 if ($bean->getAttribute('chunits')) $sql_for_expenses .= ", null as units";
976 $sql_for_expenses .= ", sum(cost) as cost, sum(cost) as expenses from tt_expense_items ei $where";
978 // Create a combined query.
979 $combined = "select sum(time) as time";
980 if ($bean->getAttribute('chunits')) $combined .= ", sum(units) as units";
981 $combined .= ", sum(cost) as cost, sum(expenses) as expenses from (($sql) union all ($sql_for_expenses)) t";
986 $res = $mdb2->query($sql);
987 if (is_a($res, 'PEAR_Error')) die($res->getMessage());
989 $val = $res->fetchRow();
990 $total_time = $val['time'] ? sec_to_time_fmt_hm($val['time']) : null;
991 if ($bean->getAttribute('chcost')) {
992 $total_cost = $val['cost'];
993 if (!$total_cost) $total_cost = '0.00';
994 if ('.' != $user->decimal_mark)
995 $total_cost = str_replace('.', $user->decimal_mark, $total_cost);
996 $total_expenses = $val['expenses'];
997 if (!$total_expenses) $total_expenses = '0.00';
998 if ('.' != $user->decimal_mark)
999 $total_expenses = str_replace('.', $user->decimal_mark, $total_expenses);
1002 if ($bean->getAttribute('period'))
1003 $period = new Period($bean->getAttribute('period'), new DateAndTime($user->date_format));
1005 $period = new Period();
1007 new DateAndTime($user->date_format, $bean->getAttribute('start_date')),
1008 new DateAndTime($user->date_format, $bean->getAttribute('end_date')));
1011 $totals['start_date'] = $period->getStartDate();
1012 $totals['end_date'] = $period->getEndDate();
1013 $totals['time'] = $total_time;
1014 $totals['units'] = $val['units'];
1015 $totals['cost'] = $total_cost;
1016 $totals['expenses'] = $total_expenses;
1021 // getFavTotals calculates total hours and cost for all favorite report items.
1022 static function getFavTotals($options)
1026 $mdb2 = getConnection();
1028 $where = ttReportHelper::getWhere($options);
1031 $time_part = "sum(time_to_sec(l.duration)) as time";
1032 if ($options['show_work_units']) {
1033 $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";
1035 if ($options['show_cost']) {
1036 if (MODE_TIME == $user->tracking_mode)
1037 $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";
1039 $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";
1041 $cost_part = ", null as cost, null as expenses";
1043 if ($options['show_cost']) {
1044 if (MODE_TIME == $user->tracking_mode) {
1045 $left_joins = "left join tt_users u on (l.user_id = u.id)";
1047 $left_joins = "left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id)";
1050 // Prepare a query for time items.
1051 $sql = "select $time_part $units_part $cost_part from tt_log l $left_joins $where";
1053 // If we have expenses, query becomes a bit more complex.
1054 if ($options['show_cost'] && $user->isPluginEnabled('ex')) {
1055 $where = ttReportHelper::getExpenseWhere($options);
1056 $sql_for_expenses = "select null as time";
1057 if ($options['show_work_units']) $sql_for_expenses .= ", null as units";
1058 $sql_for_expenses .= ", sum(cost) as cost, sum(cost) as expenses from tt_expense_items ei $where";
1060 // Create a combined query.
1061 $combined = "select sum(time) as time";
1062 if ($options['show_work_units']) $combined .= ", sum(units) as units";
1063 $combined .= ", sum(cost) as cost, sum(expenses) as expenses from (($sql) union all ($sql_for_expenses)) t";
1068 $res = $mdb2->query($sql);
1069 if (is_a($res, 'PEAR_Error')) die($res->getMessage());
1071 $val = $res->fetchRow();
1072 $total_time = $val['time'] ? sec_to_time_fmt_hm($val['time']) : null;
1073 if ($options['show_cost']) {
1074 $total_cost = $val['cost'];
1075 if (!$total_cost) $total_cost = '0.00';
1076 if ('.' != $user->decimal_mark)
1077 $total_cost = str_replace('.', $user->decimal_mark, $total_cost);
1078 $total_expenses = $val['expenses'];
1079 if (!$total_expenses) $total_expenses = '0.00';
1080 if ('.' != $user->decimal_mark)
1081 $total_expenses = str_replace('.', $user->decimal_mark, $total_expenses);
1084 if ($options['period'])
1085 $period = new Period($options['period'], new DateAndTime($user->date_format));
1087 $period = new Period();
1089 new DateAndTime($user->date_format, $options['period_start']),
1090 new DateAndTime($user->date_format, $options['period_end']));
1093 $totals['start_date'] = $period->getStartDate();
1094 $totals['end_date'] = $period->getEndDate();
1095 $totals['time'] = $total_time;
1096 $totals['units'] = $val['units'];
1097 $totals['cost'] = $total_cost;
1098 $totals['expenses'] = $total_expenses;
1103 // The assignToInvoice assigns a set of records to a specific invoice.
1104 static function assignToInvoice($invoice_id, $time_log_ids, $expense_item_ids)
1106 $mdb2 = getConnection();
1107 if ($time_log_ids) {
1108 $sql = "update tt_log set invoice_id = ".$mdb2->quote($invoice_id).
1109 " where id in(".join(', ', $time_log_ids).")";
1110 $affected = $mdb2->exec($sql);
1111 if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
1113 if ($expense_item_ids) {
1114 $sql = "update tt_expense_items set invoice_id = ".$mdb2->quote($invoice_id).
1115 " where id in(".join(', ', $expense_item_ids).")";
1116 $affected = $mdb2->exec($sql);
1117 if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
1121 // The markPaid marks a set of records as either paid or unpaid.
1122 static function markPaid($time_log_ids, $expense_item_ids, $paid = true)
1124 $mdb2 = getConnection();
1125 $paid_val = (int) $paid;
1126 if ($time_log_ids) {
1127 $sql = "update tt_log set paid = $paid_val where id in(".join(', ', $time_log_ids).")";
1128 $affected = $mdb2->exec($sql);
1129 if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
1131 if ($expense_item_ids) {
1132 $sql = "update tt_expense_items set paid = $paid_val where id in(".join(', ', $expense_item_ids).")";
1133 $affected = $mdb2->exec($sql);
1134 if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
1138 // prepareReportBody - prepares an email body for report.
1139 static function prepareReportBody($bean, $comment)
1144 // Determine these once as they are used in multiple places in this function.
1145 $canViewReports = $user->can('view_reports');
1146 $isClient = $user->isClient();
1147 $options = ttReportHelper::getReportOptions($bean);
1149 $items = ttReportHelper::getItems($bean, $options);
1150 $group_by = $bean->getAttribute('group_by');
1151 if ($group_by && 'no_grouping' != $group_by)
1152 $subtotals = ttReportHelper::getSubtotals($bean, $options);
1153 $totals = ttReportHelper::getTotals($bean, $options);
1155 // Use custom fields plugin if it is enabled.
1156 if ($user->isPluginEnabled('cf'))
1157 $custom_fields = new CustomFields($user->group_id);
1159 // Define some styles to use in email.
1160 $style_title = 'text-align: center; font-size: 15pt; font-family: Arial, Helvetica, sans-serif;';
1161 $tableHeader = 'font-weight: bold; background-color: #a6ccf7; text-align: left;';
1162 $tableHeaderCentered = 'font-weight: bold; background-color: #a6ccf7; text-align: center;';
1163 $rowItem = 'background-color: #ffffff;';
1164 $rowItemAlt = 'background-color: #f5f5f5;';
1165 $rowSubtotal = 'background-color: #e0e0e0;';
1166 $cellLeftAligned = 'text-align: left; vertical-align: top;';
1167 $cellRightAligned = 'text-align: right; vertical-align: top;';
1168 $cellLeftAlignedSubtotal = 'font-weight: bold; text-align: left; vertical-align: top;';
1169 $cellRightAlignedSubtotal = 'font-weight: bold; text-align: right; vertical-align: top;';
1171 // Start creating email body.
1173 $body .= '<head><meta http-equiv="content-type" content="text/html; charset='.CHARSET.'"></head>';
1177 $body .= '<p style="'.$style_title.'">'.$i18n->get('form.mail.report_subject').': '.$totals['start_date'].' - '.$totals['end_date'].'</p>';
1180 if ($comment) $body .= '<p>'.htmlspecialchars($comment).'</p>';
1182 if ($bean->getAttribute('chtotalsonly')) {
1183 // Totals only report. Output subtotals.
1185 // Determine group_by header.
1186 if ('cf_1' == $group_by)
1187 $group_by_header = htmlspecialchars($custom_fields->fields[0]['label']);
1189 $key = 'label.'.$group_by;
1190 $group_by_header = $i18n->get($key);
1193 $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
1195 $body .= '<td style="'.$tableHeader.'">'.$group_by_header.'</td>';
1196 if ($bean->getAttribute('chduration'))
1197 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.duration').'</td>';
1198 if ($bean->getAttribute('chunits'))
1199 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.work_units_short').'</td>';
1200 if ($bean->getAttribute('chcost'))
1201 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.cost').'</td>';
1203 foreach($subtotals as $subtotal) {
1204 $body .= '<tr style="'.$rowSubtotal.'">';
1205 $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($subtotal['name'] ? htmlspecialchars($subtotal['name']) : ' ').'</td>';
1206 if ($bean->getAttribute('chduration')) {
1207 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1208 if ($subtotal['time'] <> '0:00') $body .= $subtotal['time'];
1211 if ($bean->getAttribute('chunits')) {
1212 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1213 $body .= $subtotal['units'];
1216 if ($bean->getAttribute('chcost')) {
1217 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1218 $body .= ($canViewReports || $isClient) ? $subtotal['cost'] : $subtotal['expenses'];
1225 $body .= '<tr><td> </td></tr>';
1226 $body .= '<tr style="'.$rowSubtotal.'">';
1227 $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.total').'</td>';
1228 if ($bean->getAttribute('chduration')) {
1229 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1230 if ($totals['time'] <> '0:00') $body .= $totals['time'];
1233 if ($bean->getAttribute('chunits')) {
1234 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1235 $body .= $totals['units'];
1238 if ($bean->getAttribute('chcost')) {
1239 $body .= '<td nowrap style="'.$cellRightAlignedSubtotal.'">'.htmlspecialchars($user->currency).' ';
1240 $body .= ($canViewReports || $isClient) ? $totals['cost'] : $totals['expenses'];
1245 $body .= '</table>';
1249 // Print table header.
1250 $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
1252 $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.date').'</td>';
1253 if ($canViewReports || $isClient)
1254 $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.user').'</td>';
1255 if ($bean->getAttribute('chclient'))
1256 $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.client').'</td>';
1257 if ($bean->getAttribute('chproject'))
1258 $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.project').'</td>';
1259 if ($bean->getAttribute('chtask'))
1260 $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.task').'</td>';
1261 if ($bean->getAttribute('chcf_1'))
1262 $body .= '<td style="'.$tableHeader.'">'.htmlspecialchars($custom_fields->fields[0]['label']).'</td>';
1263 if ($bean->getAttribute('chstart'))
1264 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.start').'</td>';
1265 if ($bean->getAttribute('chfinish'))
1266 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.finish').'</td>';
1267 if ($bean->getAttribute('chduration'))
1268 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.duration').'</td>';
1269 if ($bean->getAttribute('chunits'))
1270 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.work_units_short').'</td>';
1271 if ($bean->getAttribute('chnote'))
1272 $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.note').'</td>';
1273 if ($bean->getAttribute('chcost'))
1274 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.cost').'</td>';
1275 if ($bean->getAttribute('chpaid'))
1276 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.paid').'</td>';
1277 if ($bean->getAttribute('chip'))
1278 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.ip').'</td>';
1279 if ($bean->getAttribute('chinvoice'))
1280 $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.invoice').'</td>';
1283 // Initialize variables to print subtotals.
1284 if ($items && 'no_grouping' != $group_by) {
1285 $print_subtotals = true;
1287 $prev_grouped_by = '';
1288 $cur_grouped_by = '';
1290 // Initialize variables to alternate color of rows for different dates.
1293 $row_style = $rowItem;
1295 // Print report items.
1296 if (is_array($items)) {
1297 foreach ($items as $record) {
1298 $cur_date = $record['date'];
1299 // Print a subtotal row after a block of grouped items.
1300 if ($print_subtotals) {
1301 $cur_grouped_by = $record['grouped_by'];
1302 if ($cur_grouped_by != $prev_grouped_by && !$first_pass) {
1303 $body .= '<tr style="'.$rowSubtotal.'">';
1304 $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.subtotal').'</td>';
1305 $subtotal_name = htmlspecialchars($subtotals[$prev_grouped_by]['name']);
1306 if ($canViewReports || $isClient) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'user' ? $subtotal_name : '').'</td>';
1307 if ($bean->getAttribute('chclient')) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'client' ? $subtotal_name : '').'</td>';
1308 if ($bean->getAttribute('chproject')) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'project' ? $subtotal_name : '').'</td>';
1309 if ($bean->getAttribute('chtask')) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'task' ? $subtotal_name : '').'</td>';
1310 if ($bean->getAttribute('chcf_1')) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'cf_1' ? $subtotal_name : '').'</td>';
1311 if ($bean->getAttribute('chstart')) $body .= '<td></td>';
1312 if ($bean->getAttribute('chfinish')) $body .= '<td></td>';
1313 if ($bean->getAttribute('chduration')) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['time'].'</td>';
1314 if ($bean->getAttribute('chunits')) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['units'].'</td>';
1315 if ($bean->getAttribute('chnote')) $body .= '<td></td>';
1316 if ($bean->getAttribute('chcost')) {
1317 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1318 $body .= ($canViewReports || $isClient) ? $subtotals[$prev_grouped_by]['cost'] : $subtotals[$prev_grouped_by]['expenses'];
1321 if ($bean->getAttribute('chpaid')) $body .= '<td></td>';
1322 if ($bean->getAttribute('chip')) $body .= '<td></td>';
1323 if ($bean->getAttribute('chinvoice')) $body .= '<td></td>';
1325 $body .= '<tr><td> </td></tr>';
1327 $first_pass = false;
1330 // Print a regular row.
1331 if ($cur_date != $prev_date)
1332 $row_style = ($row_style == $rowItem) ? $rowItemAlt : $rowItem;
1333 $body .= '<tr style="'.$row_style.'">';
1334 $body .= '<td style="'.$cellLeftAligned.'">'.$record['date'].'</td>';
1335 if ($canViewReports || $isClient)
1336 $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['user']).'</td>';
1337 if ($bean->getAttribute('chclient'))
1338 $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['client']).'</td>';
1339 if ($bean->getAttribute('chproject'))
1340 $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['project']).'</td>';
1341 if ($bean->getAttribute('chtask'))
1342 $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['task']).'</td>';
1343 if ($bean->getAttribute('chcf_1'))
1344 $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['cf_1']).'</td>';
1345 if ($bean->getAttribute('chstart'))
1346 $body .= '<td nowrap style="'.$cellRightAligned.'">'.$record['start'].'</td>';
1347 if ($bean->getAttribute('chfinish'))
1348 $body .= '<td nowrap style="'.$cellRightAligned.'">'.$record['finish'].'</td>';
1349 if ($bean->getAttribute('chduration'))
1350 $body .= '<td style="'.$cellRightAligned.'">'.$record['duration'].'</td>';
1351 if ($bean->getAttribute('chunits'))
1352 $body .= '<td style="'.$cellRightAligned.'">'.$record['units'].'</td>';
1353 if ($bean->getAttribute('chnote'))
1354 $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['note']).'</td>';
1355 if ($bean->getAttribute('chcost'))
1356 $body .= '<td style="'.$cellRightAligned.'">'.$record['cost'].'</td>';
1357 if ($bean->getAttribute('chpaid')) {
1358 $body .= '<td style="'.$cellRightAligned.'">';
1359 $body .= $record['paid'] == 1 ? $i18n->get('label.yes') : $i18n->get('label.no');
1362 if ($bean->getAttribute('chip')) {
1363 $body .= '<td style="'.$cellRightAligned.'">';
1364 $body .= $record['modified'] ? $record['modified_ip'].' '.$record['modified'] : $record['created_ip'].' '.$record['created'];
1367 if ($bean->getAttribute('chinvoice'))
1368 $body .= '<td style="'.$cellRightAligned.'">'.htmlspecialchars($record['invoice']).'</td>';
1371 $prev_date = $record['date'];
1372 if ($print_subtotals)
1373 $prev_grouped_by = $record['grouped_by'];
1377 // Print a terminating subtotal.
1378 if ($print_subtotals) {
1379 $body .= '<tr style="'.$rowSubtotal.'">';
1380 $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.subtotal').'</td>';
1381 $subtotal_name = htmlspecialchars($subtotals[$cur_grouped_by]['name']);
1382 if ($canViewReports || $isClient) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'user' ? $subtotal_name : '').'</td>';
1383 if ($bean->getAttribute('chclient')) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'client' ? $subtotal_name : '').'</td>';
1384 if ($bean->getAttribute('chproject')) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'project' ? $subtotal_name : '').'</td>';
1385 if ($bean->getAttribute('chtask')) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'task' ? $subtotal_name : '').'</td>';
1386 if ($bean->getAttribute('chcf_1')) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'cf_1' ? $subtotal_name : '').'</td>';
1387 if ($bean->getAttribute('chstart')) $body .= '<td></td>';
1388 if ($bean->getAttribute('chfinish')) $body .= '<td></td>';
1389 if ($bean->getAttribute('chduration')) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$cur_grouped_by]['time'].'</td>';
1390 if ($bean->getAttribute('chunits')) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$cur_grouped_by]['units'].'</td>';
1391 if ($bean->getAttribute('chnote')) $body .= '<td></td>';
1392 if ($bean->getAttribute('chcost')) {
1393 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1394 $body .= ($canViewReports || $isClient) ? $subtotals[$cur_grouped_by]['cost'] : $subtotals[$cur_grouped_by]['expenses'];
1397 if ($bean->getAttribute('chpaid')) $body .= '<td></td>';
1398 if ($bean->getAttribute('chip')) $body .= '<td></td>';
1399 if ($bean->getAttribute('chinvoice')) $body .= '<td></td>';
1404 $body .= '<tr><td> </td></tr>';
1405 $body .= '<tr style="'.$rowSubtotal.'">';
1406 $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.total').'</td>';
1407 if ($canViewReports || $isClient) $body .= '<td></td>';
1408 if ($bean->getAttribute('chclient')) $body .= '<td></td>';
1409 if ($bean->getAttribute('chproject')) $body .= '<td></td>';
1410 if ($bean->getAttribute('chtask')) $body .= '<td></td>';
1411 if ($bean->getAttribute('chcf_1')) $body .= '<td></td>';
1412 if ($bean->getAttribute('chstart')) $body .= '<td></td>';
1413 if ($bean->getAttribute('chfinish')) $body .= '<td></td>';
1414 if ($bean->getAttribute('chduration')) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$totals['time'].'</td>';
1415 if ($bean->getAttribute('chunits')) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$totals['units'].'</td>';
1416 if ($bean->getAttribute('chnote')) $body .= '<td></td>';
1417 if ($bean->getAttribute('chcost')) {
1418 $body .= '<td nowrap style="'.$cellRightAlignedSubtotal.'">'.htmlspecialchars($user->currency).' ';
1419 $body .= ($canViewReports || $isClient) ? $totals['cost'] : $totals['expenses'];
1422 if ($bean->getAttribute('chpaid')) $body .= '<td></td>';
1423 if ($bean->getAttribute('chip')) $body .= '<td></td>';
1424 if ($bean->getAttribute('chinvoice')) $body .= '<td></td>';
1427 $body .= '</table>';
1431 if (!defined('REPORT_FOOTER') || !(REPORT_FOOTER == false))
1432 $body .= '<p style="text-align: center;">'.$i18n->get('form.mail.footer').'</p>';
1434 // Finish creating email body.
1435 $body .= '</body></html>';
1440 // checkFavReportCondition - checks whether it is okay to send fav report.
1441 static function checkFavReportCondition($options, $condition)
1443 $items = ttReportHelper::getFavItems($options);
1445 $condition = str_replace('count', '', $condition);
1446 $count_required = (int) trim(str_replace('>', '', $condition));
1448 if (count($items) > $count_required)
1449 return true; // Condition ok.
1454 // prepareFavReportBody - prepares an email body for a favorite report.
1455 static function prepareFavReportBody($options)
1460 // Determine these once as they are used in multiple places in this function.
1461 $canViewReports = $user->can('view_reports');
1462 $isClient = $user->isClient();
1464 $items = ttReportHelper::getFavItems($options);
1465 $group_by = $options['group_by'];
1466 if ($group_by && 'no_grouping' != $group_by)
1467 $subtotals = ttReportHelper::getFavSubtotals($options);
1468 $totals = ttReportHelper::getFavTotals($options);
1470 // Use custom fields plugin if it is enabled.
1471 if ($user->isPluginEnabled('cf'))
1472 $custom_fields = new CustomFields($user->group_id);
1474 // Define some styles to use in email.
1475 $style_title = 'text-align: center; font-size: 15pt; font-family: Arial, Helvetica, sans-serif;';
1476 $tableHeader = 'font-weight: bold; background-color: #a6ccf7; text-align: left;';
1477 $tableHeaderCentered = 'font-weight: bold; background-color: #a6ccf7; text-align: center;';
1478 $rowItem = 'background-color: #ffffff;';
1479 $rowItemAlt = 'background-color: #f5f5f5;';
1480 $rowSubtotal = 'background-color: #e0e0e0;';
1481 $cellLeftAligned = 'text-align: left; vertical-align: top;';
1482 $cellRightAligned = 'text-align: right; vertical-align: top;';
1483 $cellLeftAlignedSubtotal = 'font-weight: bold; text-align: left; vertical-align: top;';
1484 $cellRightAlignedSubtotal = 'font-weight: bold; text-align: right; vertical-align: top;';
1486 // Start creating email body.
1488 $body .= '<head><meta http-equiv="content-type" content="text/html; charset='.CHARSET.'"></head>';
1492 $body .= '<p style="'.$style_title.'">'.$i18n->get('form.mail.report_subject').': '.$totals['start_date'].' - '.$totals['end_date'].'</p>';
1495 // if ($comment) $body .= '<p>'.htmlspecialchars($comment).'</p>'; // No comment for fav. reports.
1497 if ($options['show_totals_only']) {
1498 // Totals only report. Output subtotals.
1500 // Determine group_by header.
1501 if ('cf_1' == $group_by)
1502 $group_by_header = htmlspecialchars($custom_fields->fields[0]['label']);
1504 $key = 'label.'.$group_by;
1505 $group_by_header = $i18n->get($key);
1508 $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
1510 $body .= '<td style="'.$tableHeader.'">'.$group_by_header.'</td>';
1511 if ($options['show_duration'])
1512 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.duration').'</td>';
1513 if ($options['show_work_units'])
1514 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.work_units_short').'</td>';
1515 if ($options['show_cost'])
1516 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.cost').'</td>';
1518 foreach($subtotals as $subtotal) {
1519 $body .= '<tr style="'.$rowSubtotal.'">';
1520 $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($subtotal['name'] ? htmlspecialchars($subtotal['name']) : ' ').'</td>';
1521 if ($options['show_duration']) {
1522 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1523 if ($subtotal['time'] <> '0:00') $body .= $subtotal['time'];
1526 if ($options['show_work_units']) {
1527 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1528 $body .= $subtotal['units'];
1531 if ($options['show_cost']) {
1532 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1533 $body .= ($canViewReports || $isClient) ? $subtotal['cost'] : $subtotal['expenses'];
1540 $body .= '<tr><td> </td></tr>';
1541 $body .= '<tr style="'.$rowSubtotal.'">';
1542 $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.total').'</td>';
1543 if ($options['show_duration']) {
1544 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1545 if ($totals['time'] <> '0:00') $body .= $totals['time'];
1548 if ($options['show_work_units']) {
1549 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1550 $body .= $totals['units'];
1553 if ($options['show_cost']) {
1554 $body .= '<td nowrap style="'.$cellRightAlignedSubtotal.'">'.htmlspecialchars($user->currency).' ';
1555 $body .= ($canViewReports || $isClient) ? $totals['cost'] : $totals['expenses'];
1560 $body .= '</table>';
1564 // Print table header.
1565 $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
1567 $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.date').'</td>';
1568 if ($canViewReports || $isClient)
1569 $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.user').'</td>';
1570 if ($options['show_client'])
1571 $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.client').'</td>';
1572 if ($options['show_project'])
1573 $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.project').'</td>';
1574 if ($options['show_task'])
1575 $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.task').'</td>';
1576 if ($options['show_custom_field_1'])
1577 $body .= '<td style="'.$tableHeader.'">'.htmlspecialchars($custom_fields->fields[0]['label']).'</td>';
1578 if ($options['show_start'])
1579 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.start').'</td>';
1580 if ($options['show_end'])
1581 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.finish').'</td>';
1582 if ($options['show_duration'])
1583 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.duration').'</td>';
1584 if ($options['show_work_units'])
1585 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.work_units_short').'</td>';
1586 if ($options['show_note'])
1587 $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.note').'</td>';
1588 if ($options['show_cost'])
1589 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.cost').'</td>';
1590 if ($options['show_paid'])
1591 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.paid').'</td>';
1592 if ($options['show_ip'])
1593 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.ip').'</td>';
1594 if ($options['show_invoice'])
1595 $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.invoice').'</td>';
1598 // Initialize variables to print subtotals.
1599 if ($items && 'no_grouping' != $group_by) {
1600 $print_subtotals = true;
1602 $prev_grouped_by = '';
1603 $cur_grouped_by = '';
1605 // Initialize variables to alternate color of rows for different dates.
1608 $row_style = $rowItem;
1610 // Print report items.
1611 if (is_array($items)) {
1612 foreach ($items as $record) {
1613 $cur_date = $record['date'];
1614 // Print a subtotal row after a block of grouped items.
1615 if ($print_subtotals) {
1616 $cur_grouped_by = $record['grouped_by'];
1617 if ($cur_grouped_by != $prev_grouped_by && !$first_pass) {
1618 $body .= '<tr style="'.$rowSubtotal.'">';
1619 $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.subtotal').'</td>';
1620 $subtotal_name = htmlspecialchars($subtotals[$prev_grouped_by]['name']);
1621 if ($canViewReports || $isClient) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'user' ? $subtotal_name : '').'</td>';
1622 if ($options['show_client']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'client' ? $subtotal_name : '').'</td>';
1623 if ($options['show_project']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'project' ? $subtotal_name : '').'</td>';
1624 if ($options['show_task']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'task' ? $subtotal_name : '').'</td>';
1625 if ($options['show_custom_field_1']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'cf_1' ? $subtotal_name : '').'</td>';
1626 if ($options['show_start']) $body .= '<td></td>';
1627 if ($options['show_end']) $body .= '<td></td>';
1628 if ($options['show_duration']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['time'].'</td>';
1629 if ($options['show_work_units']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['units'].'</td>';
1630 if ($options['show_note']) $body .= '<td></td>';
1631 if ($options['show_cost']) {
1632 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1633 $body .= ($canViewReports || $isClient) ? $subtotals[$prev_grouped_by]['cost'] : $subtotals[$prev_grouped_by]['expenses'];
1636 if ($options['show_paid']) $body .= '<td></td>';
1637 if ($options['show_ip']) $body .= '<td></td>';
1638 if ($options['show_invoice']) $body .= '<td></td>';
1640 $body .= '<tr><td> </td></tr>';
1642 $first_pass = false;
1645 // Print a regular row.
1646 if ($cur_date != $prev_date)
1647 $row_style = ($row_style == $rowItem) ? $rowItemAlt : $rowItem;
1648 $body .= '<tr style="'.$row_style.'">';
1649 $body .= '<td style="'.$cellLeftAligned.'">'.$record['date'].'</td>';
1650 if ($canViewReports || $isClient)
1651 $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['user']).'</td>';
1652 if ($options['show_client'])
1653 $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['client']).'</td>';
1654 if ($options['show_project'])
1655 $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['project']).'</td>';
1656 if ($options['show_task'])
1657 $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['task']).'</td>';
1658 if ($options['show_custom_field_1'])
1659 $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['cf_1']).'</td>';
1660 if ($options['show_start'])
1661 $body .= '<td nowrap style="'.$cellRightAligned.'">'.$record['start'].'</td>';
1662 if ($options['show_end'])
1663 $body .= '<td nowrap style="'.$cellRightAligned.'">'.$record['finish'].'</td>';
1664 if ($options['show_duration'])
1665 $body .= '<td style="'.$cellRightAligned.'">'.$record['duration'].'</td>';
1666 if ($options['show_work_units'])
1667 $body .= '<td style="'.$cellRightAligned.'">'.$record['units'].'</td>';
1668 if ($options['show_note'])
1669 $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['note']).'</td>';
1670 if ($options['show_cost'])
1671 $body .= '<td style="'.$cellRightAligned.'">'.$record['cost'].'</td>';
1672 if ($options['show_paid']) {
1673 $body .= '<td style="'.$cellRightAligned.'">';
1674 $body .= $record['paid'] == 1 ? $i18n->get('label.yes') : $i18n->get('label.no');
1677 if ($options['show_ip']) {
1678 $body .= '<td style="'.$cellRightAligned.'">';
1679 $body .= $record['modified'] ? $record['modified_ip'].' '.$record['modified'] : $record['created_ip'].' '.$record['created'];
1682 if ($options['show_invoice'])
1683 $body .= '<td style="'.$cellRightAligned.'">'.htmlspecialchars($record['invoice']).'</td>';
1686 $prev_date = $record['date'];
1687 if ($print_subtotals)
1688 $prev_grouped_by = $record['grouped_by'];
1692 // Print a terminating subtotal.
1693 if ($print_subtotals) {
1694 $body .= '<tr style="'.$rowSubtotal.'">';
1695 $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.subtotal').'</td>';
1696 $subtotal_name = htmlspecialchars($subtotals[$cur_grouped_by]['name']);
1697 if ($canViewReports || $isClient) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'user' ? $subtotal_name : '').'</td>';
1698 if ($options['show_client']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'client' ? $subtotal_name : '').'</td>';
1699 if ($options['show_project']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'project' ? $subtotal_name : '').'</td>';
1700 if ($options['show_task']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'task' ? $subtotal_name : '').'</td>';
1701 if ($options['show_custom_field_1']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'cf_1' ? $subtotal_name : '').'</td>';
1702 if ($options['show_start']) $body .= '<td></td>';
1703 if ($options['show_end']) $body .= '<td></td>';
1704 if ($options['show_duration']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$cur_grouped_by]['time'].'</td>';
1705 if ($options['show_work_units']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$cur_grouped_by]['units'].'</td>';
1706 if ($options['show_note']) $body .= '<td></td>';
1707 if ($options['show_cost']) {
1708 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1709 $body .= ($canViewReports || $isClient) ? $subtotals[$cur_grouped_by]['cost'] : $subtotals[$cur_grouped_by]['expenses'];
1712 if ($options['show_paid']) $body .= '<td></td>';
1713 if ($options['show_ip']) $body .= '<td></td>';
1714 if ($options['show_invoice']) $body .= '<td></td>';
1719 $body .= '<tr><td> </td></tr>';
1720 $body .= '<tr style="'.$rowSubtotal.'">';
1721 $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.total').'</td>';
1722 if ($canViewReports || $isClient) $body .= '<td></td>';
1723 if ($options['show_client']) $body .= '<td></td>';
1724 if ($options['show_project']) $body .= '<td></td>';
1725 if ($options['show_task']) $body .= '<td></td>';
1726 if ($options['show_custom_field_1']) $body .= '<td></td>';
1727 if ($options['show_start']) $body .= '<td></td>';
1728 if ($options['show_end']) $body .= '<td></td>';
1729 if ($options['show_duration']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$totals['time'].'</td>';
1730 if ($options['show_work_units']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$totals['units'].'</td>';
1731 if ($options['show_note']) $body .= '<td></td>';
1732 if ($options['show_cost']) {
1733 $body .= '<td nowrap style="'.$cellRightAlignedSubtotal.'">'.htmlspecialchars($user->currency).' ';
1734 $body .= ($canViewReports || $isClient) ? $totals['cost'] : $totals['expenses'];
1737 if ($options['show_paid']) $body .= '<td></td>';
1738 if ($options['show_ip']) $body .= '<td></td>';
1739 if ($options['show_invoice']) $body .= '<td></td>';
1742 $body .= '</table>';
1746 if (!defined('REPORT_FOOTER') || !(REPORT_FOOTER == false))
1747 $body .= '<p style="text-align: center;">'.$i18n->get('form.mail.footer').'</p>';
1749 // Finish creating email body.
1750 $body .= '</body></html>';
1755 // sendFavReport - sends a favorite report to a specified email, called from cron.php
1756 static function sendFavReport($options, $subject, $email, $cc) {
1757 // We are called from cron.php, we have no $bean in session.
1758 // cron.php sets global $user and $i18n objects to match our favorite report user.
1762 // Prepare report body.
1763 $body = ttReportHelper::prepareFavReportBody($options);
1765 import('mail.Mailer');
1766 $mailer = new Mailer();
1767 $mailer->setCharSet(CHARSET);
1768 $mailer->setContentType('text/html');
1769 $mailer->setSender(SENDER);
1771 $mailer->setReceiverCC($cc);
1772 if (!empty($user->bcc_email))
1773 $mailer->setReceiverBCC($user->bcc_email);
1774 $mailer->setReceiver($email);
1775 $mailer->setMailMode(MAIL_MODE);
1776 if (empty($subject)) $subject = $options['name'];
1777 if (!$mailer->send($subject, $body))
1783 // getReportOptions - returns an array of report options constructed from session bean.
1785 // Note: similarly to ttFavReportHelper::getReportOptions, this function is a part of
1786 // refactoring to simplify maintenance of report generating functions, as we currently
1787 // have 2 sets: normal reporting (from bean), and fav report emailing (from db fields).
1788 // Using options obtained from either db or bean shall allow us to use only one set of functions.
1789 static function getReportOptions($bean) {
1792 // Prepare an array of report options.
1795 // Construct one by one.
1796 $options['name'] = null; // No name required.
1797 $options['user_id'] = $user->id; // Not sure if we need user_id here. Fav reports use it to recycle $user object in cron.php.
1798 $options['client_id'] = $bean->getAttribute('client');
1799 $options['cf_1_option_id'] = $bean->getAttribute('option');
1800 $options['project_id'] = $bean->getAttribute('project');
1801 $options['task_id'] = $bean->getAttribute('task');
1802 $options['billable'] = $bean->getAttribute('include_records');
1803 $options['invoice'] = $bean->getAttribute('invoice');
1804 $options['paid_status'] = $bean->getAttribute('paid_status');
1805 if (is_array($bean->getAttribute('users'))) $options['users'] = join(',', $bean->getAttribute('users'));
1806 $options['period'] = $bean->getAttribute('period');
1807 $options['period_start'] = $bean->getAttribute('start_date');
1808 $options['period_end'] = $bean->getAttribute('end_date');
1809 $options['show_client'] = $bean->getAttribute('chclient');
1812 * TODO: remaining fields to fill in...
1813 `show_invoice` tinyint(4) NOT NULL default 0, # whether to show invoice column
1814 `show_paid` tinyint(4) NOT NULL default 0, # whether to show paid column
1815 `show_ip` tinyint(4) NOT NULL default 0, # whether to show ip column
1817 $options['show_project'] = $bean->getAttribute('chproject');
1818 $options['show_start'] = $bean->getAttribute('chstart');
1820 `show_duration` tinyint(4) NOT NULL default 0, # whether to show duration field
1821 `show_cost` tinyint(4) NOT NULL default 0, # whether to show cost field
1823 $options['show_task'] = $bean->getAttribute('chtask');
1824 $options['show_end'] = $bean->getAttribute('chfinish');
1826 `show_note` tinyint(4) NOT NULL default 0, # whether to show note column
1827 `show_custom_field_1` tinyint(4) NOT NULL default 0, # whether to show custom field 1
1829 $options['show_custom_field_1'] = $bean->getAttribute('chcf_1');
1831 `show_work_units` tinyint(4) NOT NULL default 0, # whether to show work units
1832 `show_totals_only` tinyint(4) NOT NULL default 0, # whether to show totals only
1834 $options['group_by'] = $bean->getAttribute('group_by');
1836 * TODO: remaining fields to fill in...
1837 `status` tinyint(4) default 1, # favorite report status
1844 // verifyBean is a security function to make sure data in bean makes sense for a group.
1845 static function verifyBean($bean) {
1849 $users_in_bean = $bean->getAttribute('users');
1850 if (is_array($users_in_bean)) {
1851 $users_in_group = ttTeamHelper::getUsers();
1852 foreach ($users_in_group as $user_in_group) {
1853 $valid_ids[] = $user_in_group['id'];
1855 foreach ($users_in_bean as $user_in_bean) {
1856 if (!in_array($user_in_bean, $valid_ids)) {
1862 // TODO: add additional checks here. Perhaps do it before saving the bean for consistency.