Refactoring. Renamed team_id fields to become group_id.
[timetracker.git] / WEB-INF / lib / ttReportHelper.class.php
1 <?php
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.
10 // |
11 // | There are only two ways to violate the license:
12 // |
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).
16 // |
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).
20 // |
21 // | This license applies to this document only, not any other software
22 // | that it may be combined with.
23 // |
24 // +----------------------------------------------------------------------+
25 // | Contributors:
26 // | https://www.anuko.com/time_tracker/credits.htm
27 // +----------------------------------------------------------------------+
28
29 import('ttClientHelper');
30 import('DateAndTime');
31 import('Period');
32 import('ttTimeHelper');
33
34 require_once(dirname(__FILE__).'/../../plugins/CustomFields.class.php');
35
36 // Class ttReportHelper is used for help with reports.
37 class ttReportHelper {
38
39   // getWhere prepares a WHERE clause for a report query.
40   static function getWhere($bean) {
41     global $user;
42
43     // Prepare dropdown parts.
44     $dropdown_parts = '';
45     if ($bean->getAttribute('client'))
46       $dropdown_parts .= ' and l.client_id = '.$bean->getAttribute('client');
47     elseif ($user->isClient() && $user->client_id)
48       $dropdown_parts .= ' and l.client_id = '.$user->client_id;
49     if ($bean->getAttribute('option')) $dropdown_parts .= ' and l.id in(select log_id from tt_custom_field_log where status = 1 and option_id = '.$bean->getAttribute('option').')';
50     if ($bean->getAttribute('project')) $dropdown_parts .= ' and l.project_id = '.$bean->getAttribute('project');
51     if ($bean->getAttribute('task')) $dropdown_parts .= ' and l.task_id = '.$bean->getAttribute('task');
52     if ($bean->getAttribute('include_records')=='1') $dropdown_parts .= ' and l.billable = 1';
53     if ($bean->getAttribute('include_records')=='2') $dropdown_parts .= ' and l.billable = 0';
54     if ($bean->getAttribute('invoice')=='1') $dropdown_parts .= ' and l.invoice_id is not NULL';
55     if ($bean->getAttribute('invoice')=='2') $dropdown_parts .= ' and l.invoice_id is NULL';
56     if ($bean->getAttribute('paid_status')=='1') $dropdown_parts .= ' and l.paid = 1';
57     if ($bean->getAttribute('paid_status')=='2') $dropdown_parts .= ' and l.paid = 0';
58
59     // Prepare user list part.
60     $userlist = -1;
61     if (($user->can('view_reports') || $user->isClient()) && is_array($bean->getAttribute('users')))
62       $userlist = join(',', $bean->getAttribute('users'));
63     // Prepare sql query part for user list.
64     $user_list_part = null;
65     if ($user->can('view_reports') || $user->isClient())
66       $user_list_part = " and l.user_id in ($userlist)";
67     else
68       $user_list_part = " and l.user_id = ".$user->id;
69
70     // Prepare sql query part for where.
71     if ($bean->getAttribute('period'))
72       $period = new Period($bean->getAttribute('period'), new DateAndTime($user->date_format));
73     else {
74       $period = new Period();
75       $period->setPeriod(
76         new DateAndTime($user->date_format, $bean->getAttribute('start_date')),
77         new DateAndTime($user->date_format, $bean->getAttribute('end_date')));
78     }
79     $where = " where l.status = 1 and l.date >= '".$period->getStartDate(DB_DATEFORMAT)."' and l.date <= '".$period->getEndDate(DB_DATEFORMAT)."'".
80       " $user_list_part $dropdown_parts";
81     return $where;
82   }
83
84   // getFavWhere prepares a WHERE clause for a favorite report query.
85   static function getFavWhere($report) {
86     global $user;
87
88     // Prepare dropdown parts.
89     $dropdown_parts = '';
90     if ($report['client_id'])
91       $dropdown_parts .= ' and l.client_id = '.$report['client_id'];
92     elseif ($user->isClient() && $user->client_id)
93       $dropdown_parts .= ' and l.client_id = '.$user->client_id;
94     if ($report['cf_1_option_id']) $dropdown_parts .= ' and l.id in(select log_id from tt_custom_field_log where status = 1 and option_id = '.$report['cf_1_option_id'].')';
95     if ($report['project_id']) $dropdown_parts .= ' and l.project_id = '.$report['project_id'];
96     if ($report['task_id']) $dropdown_parts .= ' and l.task_id = '.$report['task_id'];
97     if ($report['billable']=='1') $dropdown_parts .= ' and l.billable = 1';
98     if ($report['billable']=='2') $dropdown_parts .= ' and l.billable = 0';
99     if ($report['invoice']=='1') $dropdown_parts .= ' and l.invoice_id is not NULL';
100     if ($report['invoice']=='2') $dropdown_parts .= ' and l.invoice_id is NULL';
101     if ($report['paid_status']=='1') $dropdown_parts .= ' and l.paid = 1';
102     if ($report['paid_status']=='2') $dropdown_parts .= ' and l.paid = 0';
103
104     // Prepare user list part.
105     $userlist = -1;
106     if (($user->can('view_reports') || $user->isClient())) {
107       if ($report['users'])
108         $userlist = $report['users'];
109       else {
110         $active_users = ttTeamHelper::getActiveUsers();
111         foreach ($active_users as $single_user)
112           $users[] = $single_user['id'];
113         $userlist = join(',', $users);
114       }
115     }
116     // Prepare sql query part for user list.
117     $user_list_part = null;
118     if ($user->can('view_reports') || $user->isClient())
119       $user_list_part = " and l.user_id in ($userlist)";
120     else
121       $user_list_part = " and l.user_id = ".$user->id;
122
123     // Prepare sql query part for where.
124     if ($report['period'])
125       $period = new Period($report['period'], new DateAndTime($user->date_format));
126     else {
127       $period = new Period();
128       $period->setPeriod(
129         new DateAndTime($user->date_format, $report['period_start']),
130         new DateAndTime($user->date_format, $report['period_end']));
131     }
132     $where = " where l.status = 1 and l.date >= '".$period->getStartDate(DB_DATEFORMAT)."' and l.date <= '".$period->getEndDate(DB_DATEFORMAT)."'".
133       " $user_list_part $dropdown_parts";
134     return $where;
135   }
136
137   // getExpenseWhere prepares WHERE clause for expenses query in a report.
138   static function getExpenseWhere($bean) {
139     global $user;
140
141     // Prepare dropdown parts.
142     $dropdown_parts = '';
143     if ($bean->getAttribute('client'))
144       $dropdown_parts .= ' and ei.client_id = '.$bean->getAttribute('client');
145     elseif ($user->isClient() && $user->client_id)
146       $dropdown_parts .= ' and ei.client_id = '.$user->client_id;
147     if ($bean->getAttribute('project')) $dropdown_parts .= ' and ei.project_id = '.$bean->getAttribute('project');
148     if ($bean->getAttribute('invoice')=='1') $dropdown_parts .= ' and ei.invoice_id is not NULL';
149     if ($bean->getAttribute('invoice')=='2') $dropdown_parts .= ' and ei.invoice_id is NULL';
150     if ($bean->getAttribute('paid_status')=='1') $dropdown_parts .= ' and ei.paid = 1';
151     if ($bean->getAttribute('paid_status')=='2') $dropdown_parts .= ' and ei.paid = 0';
152
153     // Prepare user list part.
154     $userlist = -1;
155     if (($user->can('view_reports') || $user->isClient()) && is_array($bean->getAttribute('users')))
156       $userlist = join(',', $bean->getAttribute('users'));
157     // Prepare sql query part for user list.
158     $user_list_part = null;
159     if ($user->can('view_reports') || $user->isClient())
160       $user_list_part = " and ei.user_id in ($userlist)";
161     else
162       $user_list_part = " and ei.user_id = ".$user->id;
163
164     // Prepare sql query part for where.
165     if ($bean->getAttribute('period'))
166       $period = new Period($bean->getAttribute('period'), new DateAndTime($user->date_format));
167     else {
168       $period = new Period();
169       $period->setPeriod(
170         new DateAndTime($user->date_format, $bean->getAttribute('start_date')),
171         new DateAndTime($user->date_format, $bean->getAttribute('end_date')));
172     }
173     $where = " where ei.status = 1 and ei.date >= '".$period->getStartDate(DB_DATEFORMAT)."' and ei.date <= '".$period->getEndDate(DB_DATEFORMAT)."'".
174       " $user_list_part $dropdown_parts";
175     return $where;
176   }
177
178   // getFavExpenseWhere prepares a WHERE clause for expenses query in a favorite report.
179   static function getFavExpenseWhere($report) {
180     global $user;
181
182     // Prepare dropdown parts.
183     $dropdown_parts = '';
184     if ($report['client_id'])
185       $dropdown_parts .= ' and ei.client_id = '.$report['client_id'];
186     elseif ($user->isClient() && $user->client_id)
187       $dropdown_parts .= ' and ei.client_id = '.$user->client_id;
188     if ($report['project_id']) $dropdown_parts .= ' and ei.project_id = '.$report['project_id'];
189     if ($report['invoice']=='1') $dropdown_parts .= ' and ei.invoice_id is not NULL';
190     if ($report['invoice']=='2') $dropdown_parts .= ' and ei.invoice_id is NULL';
191     if ($report['paid_status']=='1') $dropdown_parts .= ' and ei.paid = 1';
192     if ($report['paid_status']=='2') $dropdown_parts .= ' and ei.paid = 0';
193
194     // Prepare user list part.
195     $userlist = -1;
196     if (($user->can('view_reports') || $user->isClient())) {
197       if ($report['users'])
198         $userlist = $report['users'];
199       else {
200         $active_users = ttTeamHelper::getActiveUsers();
201         foreach ($active_users as $single_user)
202           $users[] = $single_user['id'];
203         $userlist = join(',', $users);
204       }
205     }
206     // Prepare sql query part for user list.
207     $user_list_part = null;
208     if ($user->can('view_reports') || $user->isClient())
209       $user_list_part = " and ei.user_id in ($userlist)";
210     else
211       $user_list_part = " and ei.user_id = ".$user->id;
212
213     // Prepare sql query part for where.
214     if ($report['period'])
215       $period = new Period($report['period'], new DateAndTime($user->date_format));
216     else {
217       $period = new Period();
218       $period->setPeriod(
219         new DateAndTime($user->date_format, $report['period_start']),
220         new DateAndTime($user->date_format, $report['period_end']));
221     }
222     $where = " where ei.status = 1 and ei.date >= '".$period->getStartDate(DB_DATEFORMAT)."' and ei.date <= '".$period->getEndDate(DB_DATEFORMAT)."'".
223       " $user_list_part $dropdown_parts";
224     return $where;
225   }
226
227   // getItems retrieves all items associated with a report.
228   // It combines tt_log and tt_expense_items in one array for presentation in one table using mysql union all.
229   // Expense items use the "note" field for item name.
230   static function getItems($bean) {
231     global $user;
232     $mdb2 = getConnection();
233
234     // Determine these once as they are used in multiple places in this function.
235     $canViewReports = $user->can('view_reports');
236     $isClient = $user->isClient();
237
238     $group_by_option = $bean->getAttribute('group_by');
239     $convertTo12Hour = ('%I:%M %p' == $user->time_format) && ($bean->getAttribute('chstart') || $bean->getAttribute('chfinish'));
240
241     // Prepare a query for time items in tt_log table.
242     $fields = array(); // An array of fields for database query.
243     array_push($fields, 'l.id as id');
244     array_push($fields, '1 as type'); // Type 1 is for tt_log entries.
245     array_push($fields, 'l.date as date');
246     if($canViewReports || $isClient)
247       array_push($fields, 'u.name as user');
248     // Add client name if it is selected.
249     if ($bean->getAttribute('chclient') || 'client' == $group_by_option)
250       array_push($fields, 'c.name as client');
251     // Add project name if it is selected.
252     if ($bean->getAttribute('chproject') || 'project' == $group_by_option)
253       array_push($fields, 'p.name as project');
254     // Add task name if it is selected.
255     if ($bean->getAttribute('chtask') || 'task' == $group_by_option)
256       array_push($fields, 't.name as task');
257     // Add custom field.
258     $include_cf_1 = $bean->getAttribute('chcf_1') || 'cf_1' == $group_by_option;
259     if ($include_cf_1) {
260       $custom_fields = new CustomFields($user->group_id);
261       $cf_1_type = $custom_fields->fields[0]['type'];
262       if ($cf_1_type == CustomFields::TYPE_TEXT) {
263         array_push($fields, 'cfl.value as cf_1');
264       } elseif ($cf_1_type == CustomFields::TYPE_DROPDOWN) {
265         array_push($fields, 'cfo.value as cf_1');
266       }
267     }
268     // Add start time.
269     if ($bean->getAttribute('chstart')) {
270       array_push($fields, "l.start as unformatted_start");
271       array_push($fields, "TIME_FORMAT(l.start, '%k:%i') as start");
272     }
273     // Add finish time.
274     if ($bean->getAttribute('chfinish'))
275       array_push($fields, "TIME_FORMAT(sec_to_time(time_to_sec(l.start) + time_to_sec(l.duration)), '%k:%i') as finish");
276     // Add duration.
277     if ($bean->getAttribute('chduration'))
278       array_push($fields, "TIME_FORMAT(l.duration, '%k:%i') as duration");
279     // Add note.
280     if ($bean->getAttribute('chnote'))
281       array_push($fields, 'l.comment as note');
282     // Handle cost.
283     $includeCost = $bean->getAttribute('chcost');
284     if ($includeCost) {
285       if (MODE_TIME == $user->tracking_mode)
286         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.
287       else
288         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.
289       array_push($fields, "null as expense"); 
290     }
291     // Add paid status.
292     if ($canViewReports && $bean->getAttribute('chpaid'))
293       array_push($fields, 'l.paid as paid');
294     // Add IP address.
295     if ($canViewReports && $bean->getAttribute('chip')) {
296       array_push($fields, 'l.created as created');
297       array_push($fields, 'l.created_ip as created_ip');
298       array_push($fields, 'l.modified as modified');
299       array_push($fields, 'l.modified_ip as modified_ip');
300     }
301
302     // Add invoice name if it is selected.
303     if (($canViewReports || $isClient) && $bean->getAttribute('chinvoice'))
304       array_push($fields, 'i.name as invoice');
305
306     // Prepare sql query part for left joins.
307     $left_joins = null;
308     if ($bean->getAttribute('chclient') || 'client' == $group_by_option)
309       $left_joins .= " left join tt_clients c on (c.id = l.client_id)";
310     if (($canViewReports || $isClient) && $bean->getAttribute('chinvoice'))
311       $left_joins .= " left join tt_invoices i on (i.id = l.invoice_id and i.status = 1)";
312     if ($canViewReports || $isClient || $user->isPluginEnabled('ex'))
313        $left_joins .= " left join tt_users u on (u.id = l.user_id)";
314     if ($bean->getAttribute('chproject') || 'project' == $group_by_option)
315       $left_joins .= " left join tt_projects p on (p.id = l.project_id)";
316     if ($bean->getAttribute('chtask') || 'task' == $group_by_option)
317       $left_joins .= " left join tt_tasks t on (t.id = l.task_id)";
318     if ($include_cf_1) {
319       if ($cf_1_type == CustomFields::TYPE_TEXT)
320         $left_joins .= " left join tt_custom_field_log cfl on (l.id = cfl.log_id and cfl.status = 1)";
321       elseif ($cf_1_type == CustomFields::TYPE_DROPDOWN) {
322         $left_joins .=  " left join tt_custom_field_log cfl on (l.id = cfl.log_id and cfl.status = 1)".
323           " left join tt_custom_field_options cfo on (cfl.option_id = cfo.id)";
324       }
325     }
326     if ($includeCost && MODE_TIME != $user->tracking_mode)
327       $left_joins .= " left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id)";
328
329     $where = ttReportHelper::getWhere($bean);
330
331     // Construct sql query for tt_log items.
332     $sql = "select ".join(', ', $fields)." from tt_log l $left_joins $where";
333     // If we don't have expense items (such as when the Expenses plugin is desabled), the above is all sql we need,
334     // with an exception of sorting part, that is added in the end.
335
336     // However, when we have expenses, we need to do a union with a separate query for expense items from tt_expense_items table.
337     if ($bean->getAttribute('chcost') && $user->isPluginEnabled('ex')) { // if ex(penses) plugin is enabled
338
339       $fields = array(); // An array of fields for database query.
340       array_push($fields, 'ei.id');
341       array_push($fields, '2 as type'); // Type 2 is for tt_expense_items entries.
342       array_push($fields, 'ei.date');
343       if($canViewReports || $isClient)
344         array_push($fields, 'u.name as user');
345       // Add client name if it is selected.
346       if ($bean->getAttribute('chclient') || 'client' == $group_by_option)
347         array_push($fields, 'c.name as client');
348       // Add project name if it is selected.
349       if ($bean->getAttribute('chproject') || 'project' == $group_by_option)
350         array_push($fields, 'p.name as project');
351       if ($bean->getAttribute('chtask') || 'task' == $group_by_option)
352         array_push($fields, 'null'); // null for task name. We need to match column count for union.
353       if ($bean->getAttribute('chcf_1') || 'cf_1' == $group_by_option)
354         array_push($fields, 'null'); // null for cf_1.
355       if ($bean->getAttribute('chstart')) {
356         array_push($fields, 'null'); // null for unformatted_start.
357         array_push($fields, 'null'); // null for start.
358       }
359       if ($bean->getAttribute('chfinish'))
360         array_push($fields, 'null'); // null for finish.
361       if ($bean->getAttribute('chduration'))
362         array_push($fields, 'null'); // null for duration.
363       // Use the note field to print item name.
364       if ($bean->getAttribute('chnote'))
365         array_push($fields, 'ei.name as note');
366       array_push($fields, 'ei.cost as cost');
367       array_push($fields, 'ei.cost as expense');
368       // Add paid status.
369       if ($canViewReports && $bean->getAttribute('chpaid'))
370         array_push($fields, 'ei.paid as paid');
371       // Add IP address.
372       if ($canViewReports && $bean->getAttribute('chip')) {
373         array_push($fields, 'ei.created as created');
374         array_push($fields, 'ei.created_ip as created_ip');
375         array_push($fields, 'ei.modified as modified');
376         array_push($fields, 'ei.modified_ip as modified_ip');
377       }
378
379       // Add invoice name if it is selected.
380       if (($canViewReports || $isClient) && $bean->getAttribute('chinvoice'))
381         array_push($fields, 'i.name as invoice');
382
383       // Prepare sql query part for left joins.
384       $left_joins = null;
385       if ($canViewReports || $isClient)
386         $left_joins .= " left join tt_users u on (u.id = ei.user_id)";
387       if ($bean->getAttribute('chclient') || 'client' == $group_by_option)
388         $left_joins .= " left join tt_clients c on (c.id = ei.client_id)";
389       if ($bean->getAttribute('chproject') || 'project' == $group_by_option)
390         $left_joins .= " left join tt_projects p on (p.id = ei.project_id)";
391       if (($canViewReports || $isClient) && $bean->getAttribute('chinvoice'))
392         $left_joins .= " left join tt_invoices i on (i.id = ei.invoice_id and i.status = 1)";
393
394       $where = ttReportHelper::getExpenseWhere($bean);
395
396       // Construct sql query for expense items.
397       $sql_for_expense_items = "select ".join(', ', $fields)." from tt_expense_items ei $left_joins $where";
398
399       // Construct a union.
400       $sql = "($sql) union all ($sql_for_expense_items)";
401     }
402
403     // Determine sort part.
404     $sort_part = ' order by ';
405     if ('no_grouping' == $group_by_option || 'date' == $group_by_option)
406       $sort_part .= 'date';
407     else
408       $sort_part .= $group_by_option.', date';
409     if (($canViewReports || $isClient) && is_array($bean->getAttribute('users')) && 'user' != $group_by_option)
410       $sort_part .= ', user, type';
411     if ($bean->getAttribute('chstart'))
412       $sort_part .= ', unformatted_start';
413     $sort_part .= ', id';
414
415     $sql .= $sort_part;
416     // By now we are ready with sql.
417
418     // Obtain items for report.
419     $res = $mdb2->query($sql);
420     if (is_a($res, 'PEAR_Error')) die($res->getMessage());
421
422     while ($val = $res->fetchRow()) {
423       if ($convertTo12Hour) {
424         if($val['start'] != '')
425           $val['start'] = ttTimeHelper::to12HourFormat($val['start']);
426         if($val['finish'] != '')
427           $val['finish'] = ttTimeHelper::to12HourFormat($val['finish']);
428       }
429       if (isset($val['cost'])) {
430         if ('.' != $user->decimal_mark)
431           $val['cost'] = str_replace('.', $user->decimal_mark, $val['cost']);
432       }
433       if (isset($val['expense'])) {
434         if ('.' != $user->decimal_mark)
435           $val['expense'] = str_replace('.', $user->decimal_mark, $val['expense']);
436       }
437       if ('no_grouping' != $group_by_option) {
438         $val['grouped_by'] = $val[$group_by_option];
439         if ('date' == $group_by_option) {
440           // This is needed to get the date in user date format.
441           $o_date = new DateAndTime(DB_DATEFORMAT, $val['grouped_by']);
442           $val['grouped_by'] = $o_date->toString($user->date_format);
443           unset($o_date);
444         }
445       }
446
447       // This is needed to get the date in user date format.
448       $o_date = new DateAndTime(DB_DATEFORMAT, $val['date']);
449       $val['date'] = $o_date->toString($user->date_format);
450       unset($o_date);
451
452       $row = $val;
453       $report_items[] = $row;
454     }
455
456     return $report_items;
457   }
458
459   // putInSession stores tt_log and tt_expense_items ids from a report in user session
460   // as 2 comma-separated lists.
461   static function putInSession($report_items) {
462     unset($_SESSION['report_item_ids']);
463     unset($_SESSION['report_item_expense_ids']);
464
465     // Iterate through records and build 2 comma-separated lists.
466     foreach($report_items as $item) {
467       if ($item['type'] == 1)
468         $report_item_ids .= ','.$item['id'];
469       else if ($item['type'] == 2)
470          $report_item_expense_ids .= ','.$item['id'];
471     }
472     $report_item_ids = trim($report_item_ids, ',');
473     $report_item_expense_ids = trim($report_item_expense_ids, ',');
474
475     // The lists are reqdy. Put them in session.
476     if ($report_item_ids) $_SESSION['report_item_ids'] = $report_item_ids;
477     if ($report_item_expense_ids) $_SESSION['report_item_expense_ids'] = $report_item_expense_ids;
478   }
479
480   // getFromSession obtains tt_log and tt_expense_items ids stored in user session.
481   static function getFromSession() {
482     $items = array();
483     $report_item_ids = $_SESSION['report_item_ids'];
484     if ($report_item_ids)
485       $items['report_item_ids'] = explode(',', $report_item_ids);
486     $report_item_expense_ids = $_SESSION['report_item_expense_ids'];
487     if ($report_item_expense_ids)
488       $items['report_item_expense_ids'] = explode(',', $report_item_expense_ids);
489     return $items;
490   }
491
492   // getFavItems retrieves all items associated with a favorite report.
493   // It combines tt_log and tt_expense_items in one array for presentation in one table using mysql union all.
494   // Expense items use the "note" field for item name.
495   static function getFavItems($report) {
496     global $user;
497     $mdb2 = getConnection();
498
499     // Determine these once as they are used in multiple places in this function.
500     $canViewReports = $user->can('view_reports');
501     $isClient = $user->isClient();
502
503     $group_by_option = $report['group_by'];
504     $convertTo12Hour = ('%I:%M %p' == $user->time_format) && ($report['show_start'] || $report['show_end']);
505
506     // Prepare a query for time items in tt_log table.
507     $fields = array(); // An array of fields for database query.
508     array_push($fields, 'l.id as id');
509     array_push($fields, '1 as type'); // Type 1 is for tt_log entries.
510     array_push($fields, 'l.date as date');
511     if($canViewReports || $isClient)
512       array_push($fields, 'u.name as user');
513     // Add client name if it is selected.
514     if ($report['show_client'] || 'client' == $group_by_option)
515       array_push($fields, 'c.name as client');
516     // Add project name if it is selected.
517     if ($report['show_project'] || 'project' == $group_by_option)
518       array_push($fields, 'p.name as project');
519     // Add task name if it is selected.
520     if ($report['show_task'] || 'task' == $group_by_option)
521       array_push($fields, 't.name as task');
522     // Add custom field.
523     $include_cf_1 = $report['show_custom_field_1'] || 'cf_1' == $group_by_option;
524     if ($include_cf_1) {
525       $custom_fields = new CustomFields($user->group_id);
526       $cf_1_type = $custom_fields->fields[0]['type'];
527       if ($cf_1_type == CustomFields::TYPE_TEXT) {
528         array_push($fields, 'cfl.value as cf_1');
529       } elseif ($cf_1_type == CustomFields::TYPE_DROPDOWN) {
530         array_push($fields, 'cfo.value as cf_1');
531       }
532     }
533     // Add start time.
534     if ($report['show_start']) {
535       array_push($fields, "l.start as unformatted_start");
536       array_push($fields, "TIME_FORMAT(l.start, '%k:%i') as start");
537     }
538     // Add finish time.
539     if ($report['show_end'])
540       array_push($fields, "TIME_FORMAT(sec_to_time(time_to_sec(l.start) + time_to_sec(l.duration)), '%k:%i') as finish");
541     // Add duration.
542     if ($report['show_duration'])
543       array_push($fields, "TIME_FORMAT(l.duration, '%k:%i') as duration");
544     // Add note.
545     if ($report['show_note'])
546       array_push($fields, 'l.comment as note');
547     // Handle cost.
548     $includeCost = $report['show_cost'];
549     if ($includeCost) {
550       if (MODE_TIME == $user->tracking_mode)
551         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.
552       else
553         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.
554       array_push($fields, "null as expense"); 
555     }
556     // Add paid status.
557     if ($canViewReports && $report['show_paid'])
558       array_push($fields, 'l.paid as paid');
559     // Add IP address.
560     if ($canViewReports && $report['show_ip']) {
561       array_push($fields, 'l.created as created');
562       array_push($fields, 'l.created_ip as created_ip');
563       array_push($fields, 'l.modified as modified');
564       array_push($fields, 'l.modified_ip as modified_ip');
565     }
566     // Add invoice name if it is selected.
567     if (($canViewReports || $isClient) && $report['show_invoice'])
568       array_push($fields, 'i.name as invoice');
569
570     // Prepare sql query part for left joins.
571     $left_joins = null;
572     if ($report['show_client'] || 'client' == $group_by_option)
573       $left_joins .= " left join tt_clients c on (c.id = l.client_id)";
574     if (($canViewReports || $isClient) && $report['show_invoice'])
575       $left_joins .= " left join tt_invoices i on (i.id = l.invoice_id and i.status = 1)";
576     if ($canViewReports || $isClient || $user->isPluginEnabled('ex'))
577        $left_joins .= " left join tt_users u on (u.id = l.user_id)";
578     if ($report['show_project'] || 'project' == $group_by_option)
579       $left_joins .= " left join tt_projects p on (p.id = l.project_id)";
580     if ($report['show_task'] || 'task' == $group_by_option)
581       $left_joins .= " left join tt_tasks t on (t.id = l.task_id)";
582     if ($include_cf_1) {
583       if ($cf_1_type == CustomFields::TYPE_TEXT)
584         $left_joins .= " left join tt_custom_field_log cfl on (l.id = cfl.log_id and cfl.status = 1)";
585       elseif ($cf_1_type == CustomFields::TYPE_DROPDOWN) {
586         $left_joins .=  " left join tt_custom_field_log cfl on (l.id = cfl.log_id and cfl.status = 1)".
587           " left join tt_custom_field_options cfo on (cfl.option_id = cfo.id)";
588       }
589     }
590     if ($includeCost && MODE_TIME != $user->tracking_mode)
591       $left_joins .= " left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id)";
592
593     $where = ttReportHelper::getFavWhere($report);
594
595     // Construct sql query for tt_log items.
596     $sql = "select ".join(', ', $fields)." from tt_log l $left_joins $where";
597     // If we don't have expense items (such as when the Expenses plugin is desabled), the above is all sql we need,
598     // with an exception of sorting part, that is added in the end.
599
600     // However, when we have expenses, we need to do a union with a separate query for expense items from tt_expense_items table.
601     if ($report['show_cost'] && $user->isPluginEnabled('ex')) { // if ex(penses) plugin is enabled
602
603       $fields = array(); // An array of fields for database query.
604       array_push($fields, 'ei.id');
605       array_push($fields, '2 as type'); // Type 2 is for tt_expense_items entries.
606       array_push($fields, 'ei.date');
607       if($canViewReports || $isClient)
608         array_push($fields, 'u.name as user');
609       // Add client name if it is selected.
610       if ($report['show_client'] || 'client' == $group_by_option)
611         array_push($fields, 'c.name as client');
612       // Add project name if it is selected.
613       if ($report['show_project'] || 'project' == $group_by_option)
614         array_push($fields, 'p.name as project');
615       if ($report['show_task'] || 'task' == $group_by_option)
616         array_push($fields, 'null'); // null for task name. We need to match column count for union.
617       if ($report['show_custom_field_1'] || 'cf_1' == $group_by_option)
618         array_push($fields, 'null'); // null for cf_1.
619       if ($report['show_start']) {
620         array_push($fields, 'null'); // null for unformatted_start.
621         array_push($fields, 'null'); // null for start.
622       }
623       if ($report['show_end'])
624         array_push($fields, 'null'); // null for finish.
625       if ($report['show_duration'])
626         array_push($fields, 'null'); // null for duration.
627       // Use the note field to print item name.
628       if ($report['show_note'])
629         array_push($fields, 'ei.name as note');
630       array_push($fields, 'ei.cost as cost');
631       array_push($fields, 'ei.cost as expense');
632       // Add paid status.
633       if ($canViewReports && $report['show_paid'])
634         array_push($fields, 'ei.paid as paid');
635       // Add IP address.
636       if ($canViewReports && $report['show_ip']) {
637         array_push($fields, 'ei.created as created');
638         array_push($fields, 'ei.created_ip as created_ip');
639         array_push($fields, 'ei.modified as modified');
640         array_push($fields, 'ei.modified_ip as modified_ip');
641       }
642       // Add invoice name if it is selected.
643       if (($canViewReports || $isClient) && $report['show_invoice'])
644         array_push($fields, 'i.name as invoice');
645
646       // Prepare sql query part for left joins.
647       $left_joins = null;
648       if ($canViewReports || $isClient)
649         $left_joins .= " left join tt_users u on (u.id = ei.user_id)";
650       if ($report['show_client'] || 'client' == $group_by_option)
651         $left_joins .= " left join tt_clients c on (c.id = ei.client_id)";
652       if ($report['show_project'] || 'project' == $group_by_option)
653         $left_joins .= " left join tt_projects p on (p.id = ei.project_id)";
654       if (($canViewReports || $isClient) && $report['show_invoice'])
655         $left_joins .= " left join tt_invoices i on (i.id = ei.invoice_id and i.status = 1)";
656
657       $where = ttReportHelper::getFavExpenseWhere($report);
658
659       // Construct sql query for expense items.
660       $sql_for_expense_items = "select ".join(', ', $fields)." from tt_expense_items ei $left_joins $where";
661
662       // Construct a union.
663       $sql = "($sql) union all ($sql_for_expense_items)";
664     }
665
666     // Determine sort part.
667     $sort_part = ' order by ';
668     if ($group_by_option == null || 'no_grouping' == $group_by_option || 'date' == $group_by_option) // TODO: fix DB for NULL values in group_by field.
669       $sort_part .= 'date';
670     else
671       $sort_part .= $group_by_option.', date';
672     if (($canViewReports || $isClient) /*&& is_array($bean->getAttribute('users'))*/ && 'user' != $group_by_option)
673       $sort_part .= ', user, type';
674     if ($report['show_start'])
675       $sort_part .= ', unformatted_start';
676     $sort_part .= ', id';
677
678     $sql .= $sort_part;
679     // By now we are ready with sql.
680
681     // Obtain items for report.
682     $res = $mdb2->query($sql);
683     if (is_a($res, 'PEAR_Error')) die($res->getMessage());
684
685     while ($val = $res->fetchRow()) {
686       if ($convertTo12Hour) {
687         if($val['start'] != '')
688           $val['start'] = ttTimeHelper::to12HourFormat($val['start']);
689         if($val['finish'] != '')
690           $val['finish'] = ttTimeHelper::to12HourFormat($val['finish']);
691       }
692       if (isset($val['cost'])) {
693         if ('.' != $user->decimal_mark)
694           $val['cost'] = str_replace('.', $user->decimal_mark, $val['cost']);
695       }
696       if (isset($val['expense'])) {
697         if ('.' != $user->decimal_mark)
698           $val['expense'] = str_replace('.', $user->decimal_mark, $val['expense']);
699       }
700       if ('no_grouping' != $group_by_option) {
701         $val['grouped_by'] = $val[$group_by_option];
702         if ('date' == $group_by_option) {
703           // This is needed to get the date in user date format.
704           $o_date = new DateAndTime(DB_DATEFORMAT, $val['grouped_by']);
705           $val['grouped_by'] = $o_date->toString($user->date_format);
706           unset($o_date);
707         }
708       }
709
710       // This is needed to get the date in user date format.
711       $o_date = new DateAndTime(DB_DATEFORMAT, $val['date']);
712       $val['date'] = $o_date->toString($user->date_format);
713       unset($o_date);
714
715       $row = $val;
716       $report_items[] = $row;
717     }
718
719     return $report_items;
720   }
721
722   // getSubtotals calculates report items subtotals when a report is grouped by.
723   // Without expenses, it's a simple select with group by.
724   // With expenses, it becomes a select with group by from a combined set of records obtained with "union all".
725   static function getSubtotals($bean) {
726     global $user;
727
728     $group_by_option = $bean->getAttribute('group_by');
729     if ('no_grouping' == $group_by_option) return null;
730
731     $mdb2 = getConnection();
732
733     // Start with sql to obtain subtotals for time items. This simple sql will be used when we have no expenses.
734
735     // Determine group by field and a required join.
736     switch ($group_by_option) {
737       case 'date':
738         $group_field = 'l.date';
739         $group_join = '';
740         break;
741       case 'user':
742         $group_field = 'u.name';
743         $group_join = 'left join tt_users u on (l.user_id = u.id) ';
744         break;
745       case 'client':
746         $group_field = 'c.name';
747         $group_join = 'left join tt_clients c on (l.client_id = c.id) ';
748         break;
749       case 'project':
750         $group_field = 'p.name';
751         $group_join = 'left join tt_projects p on (l.project_id = p.id) ';
752         break;
753       case 'task':
754         $group_field = 't.name';
755         $group_join = 'left join tt_tasks t on (l.task_id = t.id) ';
756         break;
757       case 'cf_1':
758         $group_field = 'cfo.value';
759         $custom_fields = new CustomFields($user->group_id);
760         if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_TEXT)
761           $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) ';
762         elseif ($custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN)
763           $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) ';
764         break;
765     }
766
767     $where = ttReportHelper::getWhere($bean);
768     if ($bean->getAttribute('chcost')) {
769       if (MODE_TIME == $user->tracking_mode) {
770         if ($group_by_option != 'user')
771           $left_join = 'left join tt_users u on (l.user_id = u.id)';
772         $sql = "select $group_field as group_field, sum(time_to_sec(l.duration)) as time, 
773           sum(cast(l.billable * coalesce(u.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10, 2))) as cost,
774           null as expenses from tt_log l
775           $group_join $left_join $where group by $group_field";
776       } else {
777         // If we are including cost and tracking projects, our query (the same as above) needs to join the tt_user_project_binds table.
778         $sql = "select $group_field as group_field, sum(time_to_sec(l.duration)) as time, 
779           sum(cast(l.billable * coalesce(upb.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10,2))) as cost,
780           null as expenses from tt_log l
781           $group_join
782           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";
783       }
784     } else {
785       $sql = "select $group_field as group_field, sum(time_to_sec(l.duration)) as time, null as expenses from tt_log l
786          $group_join $where group by $group_field";
787     }
788     // By now we have sql for time items.
789
790     // However, when we have expenses, we need to do a union with a separate query for expense items from tt_expense_items table.
791     if ($bean->getAttribute('chcost') && $user->isPluginEnabled('ex')) { // if ex(penses) plugin is enabled
792
793       // Determine group by field and a required join.
794       $group_join = null;
795       $group_field = 'null';
796       switch ($group_by_option) {
797         case 'date':
798           $group_field = 'ei.date';
799           $group_join = '';
800           break;
801         case 'user':
802           $group_field = 'u.name';
803           $group_join = 'left join tt_users u on (ei.user_id = u.id) ';
804           break;
805         case 'client':
806           $group_field = 'c.name';
807           $group_join = 'left join tt_clients c on (ei.client_id = c.id) ';
808           break;
809         case 'project':
810           $group_field = 'p.name';
811           $group_join = 'left join tt_projects p on (ei.project_id = p.id) ';
812           break;
813       }
814
815       $where = ttReportHelper::getExpenseWhere($bean);
816       $sql_for_expenses = "select $group_field as group_field, null as time, sum(ei.cost) as cost, sum(ei.cost) as expenses from tt_expense_items ei 
817         $group_join $where";
818       // Add a "group by" clause if we are grouping.
819       if ('null' != $group_field) $sql_for_expenses .= " group by $group_field";
820
821       // Create a combined query.
822       $sql = "select group_field, sum(time) as time, sum(cost) as cost, sum(expenses) as expenses from (($sql) union all ($sql_for_expenses)) t group by group_field";
823     }
824
825     // Execute query.
826     $res = $mdb2->query($sql);
827     if (is_a($res, 'PEAR_Error')) die($res->getMessage());
828
829     while ($val = $res->fetchRow()) {
830       if ('date' == $group_by_option) {
831         // This is needed to get the date in user date format.
832         $o_date = new DateAndTime(DB_DATEFORMAT, $val['group_field']);
833         $val['group_field'] = $o_date->toString($user->date_format);
834         unset($o_date);
835       }
836       $time = $val['time'] ? sec_to_time_fmt_hm($val['time']) : null;
837       if ($bean->getAttribute('chcost')) {
838         if ('.' != $user->decimal_mark) {
839           $val['cost'] = str_replace('.', $user->decimal_mark, $val['cost']);
840           $val['expenses'] = str_replace('.', $user->decimal_mark, $val['expenses']);
841         }
842         $subtotals[$val['group_field']] = array('name'=>$val['group_field'],'time'=>$time,'cost'=>$val['cost'],'expenses'=>$val['expenses']);
843       } else
844         $subtotals[$val['group_field']] = array('name'=>$val['group_field'],'time'=>$time);
845     }
846
847     return $subtotals;
848   }
849
850   // getFavSubtotals calculates report items subtotals when a favorite report is grouped by.
851   // Without expenses, it's a simple select with group by.
852   // With expenses, it becomes a select with group by from a combined set of records obtained with "union all".
853   static function getFavSubtotals($report) {
854     global $user;
855
856     $group_by_option = $report['group_by'];
857     if ('no_grouping' == $group_by_option) return null;
858
859     $mdb2 = getConnection();
860
861     // Start with sql to obtain subtotals for time items. This simple sql will be used when we have no expenses.
862
863     // Determine group by field and a required join.
864     switch ($group_by_option) {
865       case 'date':
866         $group_field = 'l.date';
867         $group_join = '';
868         break;
869       case 'user':
870         $group_field = 'u.name';
871         $group_join = 'left join tt_users u on (l.user_id = u.id) ';
872         break;
873       case 'client':
874         $group_field = 'c.name';
875         $group_join = 'left join tt_clients c on (l.client_id = c.id) ';
876         break;
877       case 'project':
878         $group_field = 'p.name';
879         $group_join = 'left join tt_projects p on (l.project_id = p.id) ';
880         break;
881       case 'task':
882         $group_field = 't.name';
883         $group_join = 'left join tt_tasks t on (l.task_id = t.id) ';
884         break;
885       case 'cf_1':
886         $group_field = 'cfo.value';
887         $custom_fields = new CustomFields($user->group_id);
888         if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_TEXT)
889           $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) ';
890         elseif ($custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN)
891           $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) ';
892         break;
893     }
894
895     $where = ttReportHelper::getFavWhere($report);
896     if ($report['show_cost']) {
897       if (MODE_TIME == $user->tracking_mode) {
898         if ($group_by_option != 'user')
899           $left_join = 'left join tt_users u on (l.user_id = u.id)';
900         $sql = "select $group_field as group_field, sum(time_to_sec(l.duration)) as time, 
901           sum(cast(l.billable * coalesce(u.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10, 2))) as cost,
902           null as expenses from tt_log l
903           $group_join $left_join $where group by $group_field";
904       } else {
905         // If we are including cost and tracking projects, our query (the same as above) needs to join the tt_user_project_binds table.
906         $sql = "select $group_field as group_field, sum(time_to_sec(l.duration)) as time, 
907           sum(cast(l.billable * coalesce(upb.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10,2))) as cost,
908           null as expenses from tt_log l 
909           $group_join
910           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";
911       }
912     } else {
913       $sql = "select $group_field as group_field, sum(time_to_sec(l.duration)) as time, null as expenses from tt_log l 
914          $group_join $where group by $group_field";
915     }
916     // By now we have sql for time items.
917
918     // However, when we have expenses, we need to do a union with a separate query for expense items from tt_expense_items table.
919     if ($report['show_cost'] && $user->isPluginEnabled('ex')) { // if ex(penses) plugin is enabled
920
921       // Determine group by field and a required join.
922       $group_join = null;
923       $group_field = 'null';
924       switch ($group_by_option) {
925         case 'date':
926           $group_field = 'ei.date';
927           $group_join = '';
928           break;
929         case 'user':
930           $group_field = 'u.name';
931           $group_join = 'left join tt_users u on (ei.user_id = u.id) ';
932           break;
933         case 'client':
934           $group_field = 'c.name';
935           $group_join = 'left join tt_clients c on (ei.client_id = c.id) ';
936           break;
937         case 'project':
938           $group_field = 'p.name';
939           $group_join = 'left join tt_projects p on (ei.project_id = p.id) ';
940           break;
941       }
942
943       $where = ttReportHelper::getFavExpenseWhere($report);
944       $sql_for_expenses = "select $group_field as group_field, null as time, sum(ei.cost) as cost, sum(ei.cost) as expenses from tt_expense_items ei 
945         $group_join $where";
946       // Add a "group by" clause if we are grouping.
947       if ('null' != $group_field) $sql_for_expenses .= " group by $group_field";
948
949       // Create a combined query.
950       $sql = "select group_field, sum(time) as time, sum(cost) as cost, sum(expenses) as expenses from (($sql) union all ($sql_for_expenses)) t group by group_field";
951     }
952
953     // Execute query.
954     $res = $mdb2->query($sql);
955     if (is_a($res, 'PEAR_Error')) die($res->getMessage());
956
957     while ($val = $res->fetchRow()) {
958       if ('date' == $group_by_option) {
959         // This is needed to get the date in user date format.
960         $o_date = new DateAndTime(DB_DATEFORMAT, $val['group_field']);
961         $val['group_field'] = $o_date->toString($user->date_format);
962         unset($o_date);
963       }
964       $time = $val['time'] ? sec_to_time_fmt_hm($val['time']) : null;
965       if ($report['show_cost']) {
966         if ('.' != $user->decimal_mark) {
967           $val['cost'] = str_replace('.', $user->decimal_mark, $val['cost']);
968           $val['expenses'] = str_replace('.', $user->decimal_mark, $val['expenses']);
969         }
970         $subtotals[$val['group_field']] = array('name'=>$val['group_field'],'time'=>$time,'cost'=>$val['cost'],'expenses'=>$val['expenses']);
971       } else
972         $subtotals[$val['group_field']] = array('name'=>$val['group_field'],'time'=>$time);
973     }
974
975     return $subtotals;
976   }
977
978   // getTotals calculates total hours and cost for all report items.
979   static function getTotals($bean)
980   {
981     global $user;
982
983     $mdb2 = getConnection();
984
985     $where = ttReportHelper::getWhere($bean);
986
987     // Start with a query for time items.
988     if ($bean->getAttribute('chcost')) {
989       if (MODE_TIME == $user->tracking_mode) {
990         $sql = "select sum(time_to_sec(l.duration)) as time,
991           sum(cast(l.billable * coalesce(u.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10,2))) as cost,
992           null as expenses 
993           from tt_log l
994           left join tt_users u on (l.user_id = u.id) $where";
995       } else {
996         $sql = "select sum(time_to_sec(l.duration)) as time,
997           sum(cast(l.billable * coalesce(upb.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10,2))) as cost,
998           null as expenses
999           from tt_log l
1000           left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id) $where";
1001       }
1002     } else
1003       $sql = "select sum(time_to_sec(l.duration)) as time, null as cost, null as expenses from tt_log l $where";
1004
1005     // If we have expenses, query becomes a bit more complex.
1006     if ($bean->getAttribute('chcost') && $user->isPluginEnabled('ex')) {
1007       $where = ttReportHelper::getExpenseWhere($bean);
1008       $sql_for_expenses = "select null as time, sum(cost) as cost, sum(cost) as expenses from tt_expense_items ei $where";
1009       // Create a combined query.
1010       $sql = "select sum(time) as time, sum(cost) as cost, sum(expenses) as expenses from (($sql) union all ($sql_for_expenses)) t";
1011     }
1012
1013     // Execute query.
1014     $res = $mdb2->query($sql);
1015     if (is_a($res, 'PEAR_Error')) die($res->getMessage());
1016
1017     $val = $res->fetchRow();
1018     $total_time = $val['time'] ? sec_to_time_fmt_hm($val['time']) : null;
1019     if ($bean->getAttribute('chcost')) {
1020       $total_cost = $val['cost'];
1021       if (!$total_cost) $total_cost = '0.00';
1022       if ('.' != $user->decimal_mark)
1023         $total_cost = str_replace('.', $user->decimal_mark, $total_cost);
1024       $total_expenses = $val['expenses'];
1025       if (!$total_expenses) $total_expenses = '0.00';
1026       if ('.' != $user->decimal_mark)
1027         $total_expenses = str_replace('.', $user->decimal_mark, $total_expenses);
1028     }
1029
1030     if ($bean->getAttribute('period'))
1031       $period = new Period($bean->getAttribute('period'), new DateAndTime($user->date_format));
1032     else {
1033       $period = new Period();
1034       $period->setPeriod(
1035         new DateAndTime($user->date_format, $bean->getAttribute('start_date')),
1036         new DateAndTime($user->date_format, $bean->getAttribute('end_date')));
1037     }
1038
1039     $totals['start_date'] = $period->getStartDate();
1040     $totals['end_date'] = $period->getEndDate();
1041     $totals['time'] = $total_time;
1042     $totals['cost'] = $total_cost;
1043     $totals['expenses'] = $total_expenses;
1044
1045     return $totals;
1046   }
1047
1048   // getFavTotals calculates total hours and cost for all favorite report items.
1049   static function getFavTotals($report)
1050   {
1051     global $user;
1052
1053     $mdb2 = getConnection();
1054
1055     $where = ttReportHelper::getFavWhere($report);
1056
1057     // Start with a query for time items.
1058     if ($report['show_cost']) {
1059       if (MODE_TIME == $user->tracking_mode) {
1060         $sql = "select sum(time_to_sec(l.duration)) as time,
1061           sum(cast(l.billable * coalesce(u.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10,2))) as cost,
1062           null as expenses 
1063           from tt_log l
1064           left join tt_users u on (l.user_id = u.id) $where";
1065       } else {
1066         $sql = "select sum(time_to_sec(l.duration)) as time,
1067           sum(cast(l.billable * coalesce(upb.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10,2))) as cost,
1068           null as expenses
1069           from tt_log l
1070           left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id) $where";
1071       }
1072     } else
1073       $sql = "select sum(time_to_sec(l.duration)) as time, null as cost, null as expenses from tt_log l $where";
1074
1075     // If we have expenses, query becomes a bit more complex.
1076     if ($report['show_cost'] && $user->isPluginEnabled('ex')) {
1077       $where = ttReportHelper::getFavExpenseWhere($report);
1078       $sql_for_expenses = "select null as time, sum(cost) as cost, sum(cost) as expenses from tt_expense_items ei $where";
1079       // Create a combined query.
1080       $sql = "select sum(time) as time, sum(cost) as cost, sum(expenses) as expenses from (($sql) union all ($sql_for_expenses)) t";
1081     }
1082
1083     // Execute query.
1084     $res = $mdb2->query($sql);
1085     if (is_a($res, 'PEAR_Error')) die($res->getMessage());
1086
1087     $val = $res->fetchRow();
1088     $total_time = $val['time'] ? sec_to_time_fmt_hm($val['time']) : null;
1089     if ($report['show_cost']) {
1090       $total_cost = $val['cost'];
1091       if (!$total_cost) $total_cost = '0.00';
1092       if ('.' != $user->decimal_mark)
1093         $total_cost = str_replace('.', $user->decimal_mark, $total_cost);
1094       $total_expenses = $val['expenses'];
1095       if (!$total_expenses) $total_expenses = '0.00';
1096       if ('.' != $user->decimal_mark)
1097         $total_expenses = str_replace('.', $user->decimal_mark, $total_expenses);
1098     }
1099
1100     if ($report['period'])
1101       $period = new Period($report['period'], new DateAndTime($user->date_format));
1102     else {
1103       $period = new Period();
1104       $period->setPeriod(
1105         new DateAndTime($user->date_format, $report['period_start']),
1106         new DateAndTime($user->date_format, $report['period_end']));
1107     }
1108
1109     $totals['start_date'] = $period->getStartDate();
1110     $totals['end_date'] = $period->getEndDate();
1111     $totals['time'] = $total_time;
1112     $totals['cost'] = $total_cost;
1113     $totals['expenses'] = $total_expenses;
1114
1115     return $totals;
1116   }
1117
1118   // The assignToInvoice assigns a set of records to a specific invoice.
1119   static function assignToInvoice($invoice_id, $time_log_ids, $expense_item_ids)
1120   {
1121     $mdb2 = getConnection();
1122     if ($time_log_ids) {
1123       $sql = "update tt_log set invoice_id = ".$mdb2->quote($invoice_id).
1124         " where id in(".join(', ', $time_log_ids).")";
1125       $affected = $mdb2->exec($sql);
1126       if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
1127     }
1128     if ($expense_item_ids) {
1129       $sql = "update tt_expense_items set invoice_id = ".$mdb2->quote($invoice_id).
1130         " where id in(".join(', ', $expense_item_ids).")";
1131       $affected = $mdb2->exec($sql);
1132       if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
1133     }
1134   }
1135
1136   // The markPaid marks a set of records as either paid or unpaid.
1137   static function markPaid($time_log_ids, $expense_item_ids, $paid = true)
1138   {
1139     $mdb2 = getConnection();
1140     $paid_val = (int) $paid;
1141     if ($time_log_ids) {
1142       $sql = "update tt_log set paid = $paid_val where id in(".join(', ', $time_log_ids).")";
1143       $affected = $mdb2->exec($sql);
1144       if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
1145     }
1146     if ($expense_item_ids) {
1147       $sql = "update tt_expense_items set paid = $paid_val where id in(".join(', ', $expense_item_ids).")";
1148       $affected = $mdb2->exec($sql);
1149       if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
1150     }
1151   }
1152
1153   // prepareReportBody - prepares an email body for report.
1154   static function prepareReportBody($bean, $comment)
1155   {
1156     global $user;
1157     global $i18n;
1158
1159     // Determine these once as they are used in multiple places in this function.
1160     $canViewReports = $user->can('view_reports');
1161     $isClient = $user->isClient();
1162
1163     $items = ttReportHelper::getItems($bean);
1164     $group_by = $bean->getAttribute('group_by');
1165     if ($group_by && 'no_grouping' != $group_by)
1166       $subtotals = ttReportHelper::getSubtotals($bean);
1167     $totals = ttReportHelper::getTotals($bean);
1168
1169     // Use custom fields plugin if it is enabled.
1170     if ($user->isPluginEnabled('cf'))
1171       $custom_fields = new CustomFields($user->group_id);
1172
1173     // Define some styles to use in email.
1174     $style_title = 'text-align: center; font-size: 15pt; font-family: Arial, Helvetica, sans-serif;';
1175     $tableHeader = 'font-weight: bold; background-color: #a6ccf7; text-align: left;';
1176     $tableHeaderCentered = 'font-weight: bold; background-color: #a6ccf7; text-align: center;';
1177     $rowItem = 'background-color: #ffffff;';
1178     $rowItemAlt = 'background-color: #f5f5f5;';
1179     $rowSubtotal = 'background-color: #e0e0e0;';
1180     $cellLeftAligned = 'text-align: left; vertical-align: top;';
1181     $cellRightAligned = 'text-align: right; vertical-align: top;';
1182     $cellLeftAlignedSubtotal = 'font-weight: bold; text-align: left; vertical-align: top;';
1183     $cellRightAlignedSubtotal = 'font-weight: bold; text-align: right; vertical-align: top;';
1184
1185     // Start creating email body.
1186     $body = '<html>';
1187     $body .= '<head><meta http-equiv="content-type" content="text/html; charset='.CHARSET.'"></head>';
1188     $body .= '<body>';
1189
1190     // Output title.
1191     $body .= '<p style="'.$style_title.'">'.$i18n->get('form.mail.report_subject').': '.$totals['start_date'].' - '.$totals['end_date'].'</p>';
1192
1193     // Output comment.
1194     if ($comment) $body .= '<p>'.htmlspecialchars($comment).'</p>';
1195
1196     if ($bean->getAttribute('chtotalsonly')) {
1197       // Totals only report. Output subtotals.
1198
1199       // Determine group_by header.
1200       if ('cf_1' == $group_by)
1201         $group_by_header = htmlspecialchars($custom_fields->fields[0]['label']);
1202       else {
1203         $key = 'label.'.$group_by;
1204         $group_by_header = $i18n->get($key);
1205       }
1206
1207       $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
1208       $body .= '<tr>';
1209       $body .= '<td style="'.$tableHeader.'">'.$group_by_header.'</td>';
1210       if ($bean->getAttribute('chduration'))
1211         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.duration').'</td>';
1212       if ($bean->getAttribute('chcost'))
1213         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.cost').'</td>';
1214       $body .= '</tr>';
1215       foreach($subtotals as $subtotal) {
1216         $body .= '<tr style="'.$rowSubtotal.'">';
1217         $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($subtotal['name'] ? htmlspecialchars($subtotal['name']) : '&nbsp;').'</td>';
1218         if ($bean->getAttribute('chduration')) {
1219           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1220           if ($subtotal['time'] <> '0:00') $body .= $subtotal['time'];
1221           $body .= '</td>';
1222         }
1223         if ($bean->getAttribute('chcost')) {
1224           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1225           $body .= ($canViewReports || $isClient) ? $subtotal['cost'] : $subtotal['expenses'];
1226           $body .= '</td>';
1227         }
1228         $body .= '</tr>';
1229       }
1230
1231       // Print totals.
1232       $body .= '<tr><td>&nbsp;</td></tr>';
1233       $body .= '<tr style="'.$rowSubtotal.'">';
1234       $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.total').'</td>';
1235       if ($bean->getAttribute('chduration')) {
1236         $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1237         if ($totals['time'] <> '0:00') $body .= $totals['time'];
1238         $body .= '</td>';
1239       }
1240       if ($bean->getAttribute('chcost')) {
1241         $body .= '<td nowrap style="'.$cellRightAlignedSubtotal.'">'.htmlspecialchars($user->currency).' ';
1242         $body .= ($canViewReports || $isClient) ? $totals['cost'] : $totals['expenses'];
1243         $body .= '</td>';
1244       }
1245       $body .= '</tr>';
1246
1247       $body .= '</table>';
1248     } else {
1249       // Regular report.
1250
1251       // Print table header.
1252       $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
1253       $body .= '<tr>';
1254       $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.date').'</td>';
1255       if ($canViewReports || $isClient)
1256         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.user').'</td>';
1257       if ($bean->getAttribute('chclient'))
1258         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.client').'</td>';
1259       if ($bean->getAttribute('chproject'))
1260         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.project').'</td>';
1261       if ($bean->getAttribute('chtask'))
1262         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.task').'</td>';
1263       if ($bean->getAttribute('chcf_1'))
1264         $body .= '<td style="'.$tableHeader.'">'.htmlspecialchars($custom_fields->fields[0]['label']).'</td>';
1265       if ($bean->getAttribute('chstart'))
1266         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.start').'</td>';
1267       if ($bean->getAttribute('chfinish'))
1268         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.finish').'</td>';
1269       if ($bean->getAttribute('chduration'))
1270         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.duration').'</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>';
1281       $body .= '</tr>';
1282
1283       // Initialize variables to print subtotals.
1284       if ($items && 'no_grouping' != $group_by) {
1285         $print_subtotals = true;
1286         $first_pass = true;
1287         $prev_grouped_by = '';
1288         $cur_grouped_by = '';
1289       }
1290       // Initialize variables to alternate color of rows for different dates.
1291       $prev_date = '';
1292       $cur_date = '';
1293       $row_style = $rowItem;
1294
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('chnote')) $body .= '<td></td>';
1315               if ($bean->getAttribute('chcost')) {
1316                 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1317                 $body .= ($canViewReports || $isClient) ? $subtotals[$prev_grouped_by]['cost'] : $subtotals[$prev_grouped_by]['expenses'];
1318                 $body .= '</td>';
1319               }
1320               if ($bean->getAttribute('chpaid')) $body .= '<td></td>';
1321               if ($bean->getAttribute('chip')) $body .= '<td></td>';
1322               if ($bean->getAttribute('chinvoice')) $body .= '<td></td>';
1323               $body .= '</tr>';
1324               $body .= '<tr><td>&nbsp;</td></tr>';
1325             }
1326             $first_pass = false;
1327           }
1328
1329           // Print a regular row.
1330           if ($cur_date != $prev_date)
1331             $row_style = ($row_style == $rowItem) ? $rowItemAlt : $rowItem;
1332           $body .= '<tr style="'.$row_style.'">';
1333           $body .= '<td style="'.$cellLeftAligned.'">'.$record['date'].'</td>';
1334           if ($canViewReports || $isClient)
1335             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['user']).'</td>';
1336           if ($bean->getAttribute('chclient'))
1337             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['client']).'</td>';
1338           if ($bean->getAttribute('chproject'))
1339             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['project']).'</td>';
1340           if ($bean->getAttribute('chtask'))
1341             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['task']).'</td>';
1342           if ($bean->getAttribute('chcf_1'))
1343             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['cf_1']).'</td>';
1344           if ($bean->getAttribute('chstart'))
1345             $body .= '<td nowrap style="'.$cellRightAligned.'">'.$record['start'].'</td>';
1346           if ($bean->getAttribute('chfinish'))
1347             $body .= '<td nowrap style="'.$cellRightAligned.'">'.$record['finish'].'</td>';
1348           if ($bean->getAttribute('chduration'))
1349             $body .= '<td style="'.$cellRightAligned.'">'.$record['duration'].'</td>';
1350           if ($bean->getAttribute('chnote'))
1351             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['note']).'</td>';
1352           if ($bean->getAttribute('chcost'))
1353             $body .= '<td style="'.$cellRightAligned.'">'.$record['cost'].'</td>';
1354           if ($bean->getAttribute('chpaid')) {
1355             $body .= '<td style="'.$cellRightAligned.'">';
1356             $body .= $record['paid'] == 1 ? $i18n->get('label.yes') : $i18n->get('label.no');
1357             $body .= '</td>';
1358           }
1359           if ($bean->getAttribute('chip')) {
1360             $body .= '<td style="'.$cellRightAligned.'">';
1361             $body .= $record['modified'] ? $record['modified_ip'].' '.$record['modified'] : $record['created_ip'].' '.$record['created'];
1362             $body .= '</td>';
1363           }
1364           if ($bean->getAttribute('chinvoice'))
1365             $body .= '<td style="'.$cellRightAligned.'">'.htmlspecialchars($record['invoice']).'</td>';
1366           $body .= '</tr>';
1367
1368           $prev_date = $record['date'];
1369           if ($print_subtotals)
1370             $prev_grouped_by = $record['grouped_by'];
1371         }
1372       }
1373
1374       // Print a terminating subtotal.
1375       if ($print_subtotals) {
1376         $body .= '<tr style="'.$rowSubtotal.'">';
1377         $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.subtotal').'</td>';
1378         $subtotal_name = htmlspecialchars($subtotals[$cur_grouped_by]['name']);
1379         if ($canViewReports || $isClient) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'user' ? $subtotal_name : '').'</td>';
1380         if ($bean->getAttribute('chclient')) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'client' ? $subtotal_name : '').'</td>';
1381         if ($bean->getAttribute('chproject')) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'project' ? $subtotal_name : '').'</td>';
1382         if ($bean->getAttribute('chtask')) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'task' ? $subtotal_name : '').'</td>';
1383         if ($bean->getAttribute('chcf_1')) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'cf_1' ? $subtotal_name : '').'</td>';
1384         if ($bean->getAttribute('chstart')) $body .= '<td></td>';
1385         if ($bean->getAttribute('chfinish')) $body .= '<td></td>';
1386         if ($bean->getAttribute('chduration')) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$cur_grouped_by]['time'].'</td>';
1387         if ($bean->getAttribute('chnote')) $body .= '<td></td>';
1388         if ($bean->getAttribute('chcost')) {
1389           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1390           $body .= ($canViewReports || $isClient) ? $subtotals[$cur_grouped_by]['cost'] : $subtotals[$cur_grouped_by]['expenses'];
1391           $body .= '</td>';
1392         }
1393         if ($bean->getAttribute('chpaid')) $body .= '<td></td>';
1394         if ($bean->getAttribute('chip')) $body .= '<td></td>';
1395         if ($bean->getAttribute('chinvoice')) $body .= '<td></td>';
1396         $body .= '</tr>';
1397       }
1398
1399       // Print totals.
1400       $body .= '<tr><td>&nbsp;</td></tr>';
1401       $body .= '<tr style="'.$rowSubtotal.'">';
1402       $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.total').'</td>';
1403       if ($canViewReports || $isClient) $body .= '<td></td>';
1404       if ($bean->getAttribute('chclient')) $body .= '<td></td>';
1405       if ($bean->getAttribute('chproject')) $body .= '<td></td>';
1406       if ($bean->getAttribute('chtask')) $body .= '<td></td>';
1407       if ($bean->getAttribute('chcf_1')) $body .= '<td></td>';
1408       if ($bean->getAttribute('chstart')) $body .= '<td></td>';
1409       if ($bean->getAttribute('chfinish')) $body .= '<td></td>';
1410       if ($bean->getAttribute('chduration')) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$totals['time'].'</td>';
1411       if ($bean->getAttribute('chnote')) $body .= '<td></td>';
1412       if ($bean->getAttribute('chcost')) {
1413         $body .= '<td nowrap style="'.$cellRightAlignedSubtotal.'">'.htmlspecialchars($user->currency).' ';
1414         $body .= ($canViewReports || $isClient) ? $totals['cost'] : $totals['expenses'];
1415         $body .= '</td>';
1416       }
1417       if ($bean->getAttribute('chpaid')) $body .= '<td></td>';
1418       if ($bean->getAttribute('chip')) $body .= '<td></td>';
1419       if ($bean->getAttribute('chinvoice')) $body .= '<td></td>';
1420       $body .= '</tr>';
1421
1422       $body .= '</table>';
1423     }
1424
1425     // Output footer.
1426     if (!defined('REPORT_FOOTER') || !(REPORT_FOOTER == false))
1427       $body .= '<p style="text-align: center;">'.$i18n->get('form.mail.footer').'</p>';
1428
1429     // Finish creating email body.
1430     $body .= '</body></html>';
1431
1432     return $body;
1433   }
1434
1435   // checkFavReportCondition - checks whether it is okay to send fav report.
1436   static function checkFavReportCondition($report, $condition)
1437   {
1438     $items = ttReportHelper::getFavItems($report);
1439
1440     $condition = str_replace('count', '', $condition);
1441     $count_required = (int) trim(str_replace('>', '', $condition));
1442
1443     if (count($items) > $count_required)
1444       return true; // Condition ok.
1445
1446     return false;
1447   }
1448
1449   // prepareFavReportBody - prepares an email body for a favorite report.
1450   static function prepareFavReportBody($report)
1451   {
1452     global $user;
1453     global $i18n;
1454
1455     // Determine these once as they are used in multiple places in this function.
1456     $canViewReports = $user->can('view_reports');
1457     $isClient = $user->isClient();
1458
1459     $items = ttReportHelper::getFavItems($report);
1460     $group_by = $report['group_by'];
1461     if ($group_by && 'no_grouping' != $group_by)
1462       $subtotals = ttReportHelper::getFavSubtotals($report);
1463     $totals = ttReportHelper::getFavTotals($report);
1464
1465     // Use custom fields plugin if it is enabled.
1466     if ($user->isPluginEnabled('cf'))
1467       $custom_fields = new CustomFields($user->group_id);
1468
1469     // Define some styles to use in email.
1470     $style_title = 'text-align: center; font-size: 15pt; font-family: Arial, Helvetica, sans-serif;';
1471     $tableHeader = 'font-weight: bold; background-color: #a6ccf7; text-align: left;';
1472     $tableHeaderCentered = 'font-weight: bold; background-color: #a6ccf7; text-align: center;';
1473     $rowItem = 'background-color: #ffffff;';
1474     $rowItemAlt = 'background-color: #f5f5f5;';
1475     $rowSubtotal = 'background-color: #e0e0e0;';
1476     $cellLeftAligned = 'text-align: left; vertical-align: top;';
1477     $cellRightAligned = 'text-align: right; vertical-align: top;';
1478     $cellLeftAlignedSubtotal = 'font-weight: bold; text-align: left; vertical-align: top;';
1479     $cellRightAlignedSubtotal = 'font-weight: bold; text-align: right; vertical-align: top;';
1480
1481     // Start creating email body.
1482     $body = '<html>';
1483     $body .= '<head><meta http-equiv="content-type" content="text/html; charset='.CHARSET.'"></head>';
1484     $body .= '<body>';
1485
1486     // Output title.
1487     $body .= '<p style="'.$style_title.'">'.$i18n->get('form.mail.report_subject').': '.$totals['start_date'].' - '.$totals['end_date'].'</p>';
1488
1489     // Output comment.
1490     // if ($comment) $body .= '<p>'.htmlspecialchars($comment).'</p>'; // No comment for fav. reports.
1491
1492     if ($report['show_totals_only']) {
1493       // Totals only report. Output subtotals.
1494
1495       // Determine group_by header.
1496       if ('cf_1' == $group_by)
1497         $group_by_header = htmlspecialchars($custom_fields->fields[0]['label']);
1498       else {
1499         $key = 'label.'.$group_by;
1500         $group_by_header = $i18n->get($key);
1501       }
1502
1503       $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
1504       $body .= '<tr>';
1505       $body .= '<td style="'.$tableHeader.'">'.$group_by_header.'</td>';
1506       if ($report['show_duration'])
1507         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.duration').'</td>';
1508       if ($report['show_cost'])
1509         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.cost').'</td>';
1510       $body .= '</tr>';
1511       foreach($subtotals as $subtotal) {
1512         $body .= '<tr style="'.$rowSubtotal.'">';
1513         $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($subtotal['name'] ? htmlspecialchars($subtotal['name']) : '&nbsp;').'</td>';
1514         if ($report['show_duration']) {
1515           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1516           if ($subtotal['time'] <> '0:00') $body .= $subtotal['time'];
1517           $body .= '</td>';
1518         }
1519         if ($report['show_cost']) {
1520           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1521           $body .= ($canViewReports || $isClient) ? $subtotal['cost'] : $subtotal['expenses'];
1522           $body .= '</td>';
1523         }
1524         $body .= '</tr>';
1525       }
1526
1527       // Print totals.
1528       $body .= '<tr><td>&nbsp;</td></tr>';
1529       $body .= '<tr style="'.$rowSubtotal.'">';
1530       $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.total').'</td>';
1531       if ($report['show_duration']) {
1532         $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1533         if ($totals['time'] <> '0:00') $body .= $totals['time'];
1534         $body .= '</td>';
1535       }
1536       if ($report['show_cost']) {
1537         $body .= '<td nowrap style="'.$cellRightAlignedSubtotal.'">'.htmlspecialchars($user->currency).' ';
1538         $body .= ($canViewReports || $isClient) ? $totals['cost'] : $totals['expenses'];
1539         $body .= '</td>';
1540       }
1541       $body .= '</tr>';
1542
1543       $body .= '</table>';
1544     } else {
1545       // Regular report.
1546
1547       // Print table header.
1548       $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
1549       $body .= '<tr>';
1550       $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.date').'</td>';
1551       if ($canViewReports || $isClient)
1552         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.user').'</td>';
1553       if ($report['show_client'])
1554         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.client').'</td>';
1555       if ($report['show_project'])
1556         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.project').'</td>';
1557       if ($report['show_task'])
1558         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.task').'</td>';
1559       if ($report['show_custom_field_1'])
1560         $body .= '<td style="'.$tableHeader.'">'.htmlspecialchars($custom_fields->fields[0]['label']).'</td>';
1561       if ($report['show_start'])
1562         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.start').'</td>';
1563       if ($report['show_end'])
1564         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.finish').'</td>';
1565       if ($report['show_duration'])
1566         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.duration').'</td>';
1567       if ($report['show_note'])
1568         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.note').'</td>';
1569       if ($report['show_cost'])
1570         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.cost').'</td>';
1571       if ($report['show_paid'])
1572         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.paid').'</td>';
1573       if ($report['show_ip'])
1574         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.ip').'</td>';
1575       if ($report['show_invoice'])
1576         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.invoice').'</td>';
1577       $body .= '</tr>';
1578
1579       // Initialize variables to print subtotals.
1580       if ($items && 'no_grouping' != $group_by) {
1581         $print_subtotals = true;
1582         $first_pass = true;
1583         $prev_grouped_by = '';
1584         $cur_grouped_by = '';
1585       }
1586       // Initialize variables to alternate color of rows for different dates.
1587       $prev_date = '';
1588       $cur_date = '';
1589       $row_style = $rowItem;
1590
1591       // Print report items.
1592       if (is_array($items)) {
1593         foreach ($items as $record) {
1594           $cur_date = $record['date'];
1595           // Print a subtotal row after a block of grouped items.
1596           if ($print_subtotals) {
1597             $cur_grouped_by = $record['grouped_by'];
1598             if ($cur_grouped_by != $prev_grouped_by && !$first_pass) {
1599               $body .= '<tr style="'.$rowSubtotal.'">';
1600               $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.subtotal').'</td>';
1601               $subtotal_name = htmlspecialchars($subtotals[$prev_grouped_by]['name']);
1602               if ($canViewReports || $isClient) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'user' ? $subtotal_name : '').'</td>';
1603               if ($report['show_client']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'client' ? $subtotal_name : '').'</td>';
1604               if ($report['show_project']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'project' ? $subtotal_name : '').'</td>';
1605               if ($report['show_task']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'task' ? $subtotal_name : '').'</td>';
1606               if ($report['show_custom_field_1']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'cf_1' ? $subtotal_name : '').'</td>';
1607               if ($report['show_start']) $body .= '<td></td>';
1608               if ($report['show_end']) $body .= '<td></td>';
1609               if ($report['show_duration']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['time'].'</td>';
1610               if ($report['show_note']) $body .= '<td></td>';
1611               if ($report['show_cost']) {
1612                 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1613                 $body .= ($canViewReports || $isClient) ? $subtotals[$prev_grouped_by]['cost'] : $subtotals[$prev_grouped_by]['expenses'];
1614                 $body .= '</td>';
1615               }
1616               if ($report['show_paid']) $body .= '<td></td>';
1617               if ($report['show_ip']) $body .= '<td></td>';
1618               if ($report['show_invoice']) $body .= '<td></td>';
1619               $body .= '</tr>';
1620               $body .= '<tr><td>&nbsp;</td></tr>';
1621             }
1622             $first_pass = false;
1623           }
1624
1625           // Print a regular row.
1626           if ($cur_date != $prev_date)
1627             $row_style = ($row_style == $rowItem) ? $rowItemAlt : $rowItem;
1628           $body .= '<tr style="'.$row_style.'">';
1629           $body .= '<td style="'.$cellLeftAligned.'">'.$record['date'].'</td>';
1630           if ($canViewReports || $isClient)
1631             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['user']).'</td>';
1632           if ($report['show_client'])
1633             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['client']).'</td>';
1634           if ($report['show_project'])
1635             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['project']).'</td>';
1636           if ($report['show_task'])
1637             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['task']).'</td>';
1638           if ($report['show_custom_field_1'])
1639             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['cf_1']).'</td>';
1640           if ($report['show_start'])
1641             $body .= '<td nowrap style="'.$cellRightAligned.'">'.$record['start'].'</td>';
1642           if ($report['show_end'])
1643             $body .= '<td nowrap style="'.$cellRightAligned.'">'.$record['finish'].'</td>';
1644           if ($report['show_duration'])
1645             $body .= '<td style="'.$cellRightAligned.'">'.$record['duration'].'</td>';
1646           if ($report['show_note'])
1647             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['note']).'</td>';
1648           if ($report['show_cost'])
1649             $body .= '<td style="'.$cellRightAligned.'">'.$record['cost'].'</td>';
1650           if ($report['show_paid']) {
1651             $body .= '<td style="'.$cellRightAligned.'">';
1652             $body .= $record['paid'] == 1 ? $i18n->get('label.yes') : $i18n->get('label.no');
1653             $body .= '</td>';
1654           }
1655           if ($report['show_ip']) {
1656             $body .= '<td style="'.$cellRightAligned.'">';
1657             $body .= $record['modified'] ? $record['modified_ip'].' '.$record['modified'] : $record['created_ip'].' '.$record['created'];
1658             $body .= '</td>';
1659           }
1660           if ($report['show_invoice'])
1661             $body .= '<td style="'.$cellRightAligned.'">'.htmlspecialchars($record['invoice']).'</td>';
1662           $body .= '</tr>';
1663
1664           $prev_date = $record['date'];
1665           if ($print_subtotals)
1666             $prev_grouped_by = $record['grouped_by'];
1667         }
1668       }
1669
1670       // Print a terminating subtotal.
1671       if ($print_subtotals) {
1672         $body .= '<tr style="'.$rowSubtotal.'">';
1673         $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.subtotal').'</td>';
1674         $subtotal_name = htmlspecialchars($subtotals[$cur_grouped_by]['name']);
1675         if ($canViewReports || $isClient) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'user' ? $subtotal_name : '').'</td>';
1676         if ($report['show_client']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'client' ? $subtotal_name : '').'</td>';
1677         if ($report['show_project']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'project' ? $subtotal_name : '').'</td>';
1678         if ($report['show_task']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'task' ? $subtotal_name : '').'</td>';
1679         if ($report['show_custom_field_1']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'cf_1' ? $subtotal_name : '').'</td>';
1680         if ($report['show_start']) $body .= '<td></td>';
1681         if ($report['show_end']) $body .= '<td></td>';
1682         if ($report['show_duration']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$cur_grouped_by]['time'].'</td>';
1683         if ($report['show_note']) $body .= '<td></td>';
1684         if ($report['show_cost']) {
1685           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
1686           $body .= ($canViewReports || $isClient) ? $subtotals[$cur_grouped_by]['cost'] : $subtotals[$cur_grouped_by]['expenses'];
1687           $body .= '</td>';
1688         }
1689         if ($report['show_paid']) $body .= '<td></td>';
1690         if ($report['show_ip']) $body .= '<td></td>';
1691         if ($report['show_invoice']) $body .= '<td></td>';
1692         $body .= '</tr>';
1693       }
1694
1695       // Print totals.
1696       $body .= '<tr><td>&nbsp;</td></tr>';
1697       $body .= '<tr style="'.$rowSubtotal.'">';
1698       $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.total').'</td>';
1699       if ($canViewReports || $isClient) $body .= '<td></td>';
1700       if ($report['show_client']) $body .= '<td></td>';
1701       if ($report['show_project']) $body .= '<td></td>';
1702       if ($report['show_task']) $body .= '<td></td>';
1703       if ($report['show_custom_field_1']) $body .= '<td></td>';
1704       if ($report['show_start']) $body .= '<td></td>';
1705       if ($report['show_end']) $body .= '<td></td>';
1706       if ($report['show_duration']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$totals['time'].'</td>';
1707       if ($report['show_note']) $body .= '<td></td>';
1708       if ($report['show_cost']) {
1709         $body .= '<td nowrap style="'.$cellRightAlignedSubtotal.'">'.htmlspecialchars($user->currency).' ';
1710         $body .= ($canViewReports || $isClient) ? $totals['cost'] : $totals['expenses'];
1711         $body .= '</td>';
1712       }
1713       if ($report['show_paid']) $body .= '<td></td>';
1714       if ($report['show_ip']) $body .= '<td></td>';
1715       if ($report['show_invoice']) $body .= '<td></td>';
1716       $body .= '</tr>';
1717
1718       $body .= '</table>';
1719     }
1720
1721     // Output footer.
1722     if (!defined('REPORT_FOOTER') || !(REPORT_FOOTER == false))
1723       $body .= '<p style="text-align: center;">'.$i18n->get('form.mail.footer').'</p>';
1724
1725     // Finish creating email body.
1726     $body .= '</body></html>';
1727
1728     return $body;
1729   }
1730
1731   // sendFavReport - sends a favorite report to a specified email, called from cron.php
1732   static function sendFavReport($report, $subject, $email, $cc) {
1733     // We are called from cron.php, we have no $bean in session.
1734     // cron.php sets global $user and $i18n objects to match our favorite report user.
1735     global $user;
1736     global $i18n;
1737
1738     // Prepare report body.
1739     $body = ttReportHelper::prepareFavReportBody($report);
1740
1741     import('mail.Mailer');
1742     $mailer = new Mailer();
1743     $mailer->setCharSet(CHARSET);
1744     $mailer->setContentType('text/html');
1745     $mailer->setSender(SENDER);
1746     if (!empty($cc))
1747       $mailer->setReceiverCC($cc);
1748     if (!empty($user->bcc_email))
1749       $mailer->setReceiverBCC($user->bcc_email);
1750     $mailer->setReceiver($email);
1751     $mailer->setMailMode(MAIL_MODE);
1752     if (empty($subject)) $subject = $report['name'];
1753     if (!$mailer->send($subject, $body))
1754       return false;
1755
1756     return true;
1757   }
1758 }