2 // +----------------------------------------------------------------------+
 
   3 // | Anuko Time Tracker
 
   4 // +----------------------------------------------------------------------+
 
   5 // | Copyright (c) Anuko International Ltd. (https://www.anuko.com)
 
   6 // +----------------------------------------------------------------------+
 
   7 // | LIBERAL FREEWARE LICENSE: This source code document may be used
 
   8 // | by anyone for any purpose, and freely redistributed alone or in
 
   9 // | combination with other software, provided that the license is obeyed.
 
  11 // | There are only two ways to violate the license:
 
  13 // | 1. To redistribute this code in source form, with the copyright
 
  14 // |    notice or license removed or altered. (Distributing in compiled
 
  15 // |    forms without embedded copyright notices is permitted).
 
  17 // | 2. To redistribute modified versions of this code in *any* form
 
  18 // |    that bears insufficient indications that the modifications are
 
  19 // |    not the work of the original author(s).
 
  21 // | This license applies to this document only, not any other software
 
  22 // | that it may be combined with.
 
  24 // +----------------------------------------------------------------------+
 
  26 // | https://www.anuko.com/time_tracker/credits.htm
 
  27 // +----------------------------------------------------------------------+
 
  29 import('ttClientHelper');
 
  30 import('DateAndTime');
 
  32 import('ttTimeHelper');
 
  34 require_once(dirname(__FILE__).'/../../plugins/CustomFields.class.php');
 
  36 // Class ttReportHelper is used for help with reports.
 
  37 class ttReportHelper {
 
  39   // getWhere prepares a WHERE clause for a report query.
 
  40   static function getWhere($options) {
 
  43     $group_id = $user->getGroup();
 
  44     $org_id = $user->org_id;
 
  46     // Prepare dropdown parts.
 
  48     if ($options['client_id'])
 
  49       $dropdown_parts .= ' and l.client_id = '.$options['client_id'];
 
  50     elseif ($user->isClient() && $user->client_id)
 
  51       $dropdown_parts .= ' and l.client_id = '.$user->client_id;
 
  52     if ($options['cf_1_option_id']) $dropdown_parts .= ' and l.id in(select log_id from tt_custom_field_log where status = 1 and option_id = '.$options['cf_1_option_id'].')';
 
  53     if ($options['project_id']) $dropdown_parts .= ' and l.project_id = '.$options['project_id'];
 
  54     if ($options['task_id']) $dropdown_parts .= ' and l.task_id = '.$options['task_id'];
 
  55     if ($options['billable']=='1') $dropdown_parts .= ' and l.billable = 1';
 
  56     if ($options['billable']=='2') $dropdown_parts .= ' and l.billable = 0';
 
  57     if ($options['invoice']=='1') $dropdown_parts .= ' and l.invoice_id is not NULL';
 
  58     if ($options['invoice']=='2') $dropdown_parts .= ' and l.invoice_id is NULL';
 
  59     if ($options['paid_status']=='1') $dropdown_parts .= ' and l.paid = 1';
 
  60     if ($options['paid_status']=='2') $dropdown_parts .= ' and l.paid = 0';
 
  62     // Prepare sql query part for user list.
 
  63     $userlist = $options['users'] ? $options['users'] : '-1';
 
  64     if ($user->can('view_reports') || $user->can('view_all_reports') || $user->isClient())
 
  65       $user_list_part = " and l.user_id in ($userlist)";
 
  67       $user_list_part = " and l.user_id = ".$user->getUser();
 
  68     $user_list_part .= " and l.group_id = $group_id and l.org_id = $org_id";
 
  70     // Prepare sql query part for where.
 
  71     $dateFormat = $user->getDateFormat();
 
  72     if ($options['period'])
 
  73       $period = new Period($options['period'], new DateAndTime($dateFormat));
 
  75       $period = new Period();
 
  77         new DateAndTime($dateFormat, $options['period_start']),
 
  78         new DateAndTime($dateFormat, $options['period_end']));
 
  80     $where = " where l.status = 1 and l.date >= '".$period->getStartDate(DB_DATEFORMAT)."' and l.date <= '".$period->getEndDate(DB_DATEFORMAT)."'".
 
  81       " $user_list_part $dropdown_parts";
 
  85   // getExpenseWhere prepares WHERE clause for expenses query in a report.
 
  86   static function getExpenseWhere($options) {
 
  89     $group_id = $user->getGroup();
 
  90     $org_id = $user->org_id;
 
  92     // Prepare dropdown parts.
 
  94     if ($options['client_id'])
 
  95       $dropdown_parts .= ' and ei.client_id = '.$options['client_id'];
 
  96     elseif ($user->isClient() && $user->client_id)
 
  97       $dropdown_parts .= ' and ei.client_id = '.$user->client_id;
 
  98     if ($options['project_id']) $dropdown_parts .= ' and ei.project_id = '.$options['project_id'];
 
  99     if ($options['invoice']=='1') $dropdown_parts .= ' and ei.invoice_id is not NULL';
 
 100     if ($options['invoice']=='2') $dropdown_parts .= ' and ei.invoice_id is NULL';
 
 101     if ($options['paid_status']=='1') $dropdown_parts .= ' and ei.paid = 1';
 
 102     if ($options['paid_status']=='2') $dropdown_parts .= ' and ei.paid = 0';
 
 104     // Prepare sql query part for user list.
 
 105     $userlist = $options['users'] ? $options['users'] : '-1';
 
 106     if ($user->can('view_reports') || $user->can('view_all_reports') || $user->isClient())
 
 107       $user_list_part = " and ei.user_id in ($userlist)";
 
 109       $user_list_part = " and ei.user_id = ".$user->getUser();
 
 110     $user_list_part .= " and ei.group_id = $group_id and ei.org_id = $org_id";
 
 112     // Prepare sql query part for where.
 
 113     $dateFormat = $user->getDateFormat();
 
 114     if ($options['period'])
 
 115       $period = new Period($options['period'], new DateAndTime($dateFormat));
 
 117       $period = new Period();
 
 119         new DateAndTime($dateFormat, $options['period_start']),
 
 120         new DateAndTime($dateFormat, $options['period_end']));
 
 122     $where = " where ei.status = 1 and ei.date >= '".$period->getStartDate(DB_DATEFORMAT)."' and ei.date <= '".$period->getEndDate(DB_DATEFORMAT)."'".
 
 123       " $user_list_part $dropdown_parts";
 
 127   // getItems retrieves all items associated with a report.
 
 128   // It combines tt_log and tt_expense_items in one array for presentation in one table using mysql union all.
 
 129   // Expense items use the "note" field for item name.
 
 130   static function getItems($options) {
 
 132     $mdb2 = getConnection();
 
 134     // Determine these once as they are used in multiple places in this function.
 
 135     $canViewReports = $user->can('view_reports') || $user->can('view_all_reports');
 
 136     $isClient = $user->isClient();
 
 138     $grouping = ttReportHelper::grouping($options);
 
 140       $grouping_by_date = ttReportHelper::groupingBy('date', $options);
 
 141       $grouping_by_client = ttReportHelper::groupingBy('client', $options);
 
 142       $grouping_by_project = ttReportHelper::groupingBy('project', $options);
 
 143       $grouping_by_task = ttReportHelper::groupingBy('task', $options);
 
 144       $grouping_by_user = ttReportHelper::groupingBy('user', $options);
 
 145       $grouping_by_cf_1 = ttReportHelper::groupingBy('cf_1', $options);
 
 147     $convertTo12Hour = ('%I:%M %p' == $user->getTimeFormat()) && ($options['show_start'] || $options['show_end']);
 
 148     $trackingMode = $user->getTrackingMode();
 
 149     $decimalMark = $user->getDecimalMark();
 
 151     // Prepare a query for time items in tt_log table.
 
 152     $fields = array(); // An array of fields for database query.
 
 153     array_push($fields, 'l.id');
 
 154     array_push($fields, 'l.user_id');
 
 155     array_push($fields, '1 as type'); // Type 1 is for tt_log entries.
 
 156     array_push($fields, 'l.date');
 
 157     array_push($fields, 'l.timesheet_id');
 
 158     if($canViewReports || $isClient)
 
 159       array_push($fields, 'u.name as user');
 
 160     // Add client name if it is selected.
 
 161     if ($options['show_client'] || $grouping_by_client)
 
 162       array_push($fields, 'c.name as client');
 
 163     // Add project name if it is selected.
 
 164     if ($options['show_project'] || $grouping_by_project)
 
 165       array_push($fields, 'p.name as project');
 
 166     // Add task name if it is selected.
 
 167     if ($options['show_task'] || $grouping_by_task)
 
 168       array_push($fields, 't.name as task');
 
 170     $include_cf_1 = $options['show_custom_field_1'] || $grouping_by_cf_1;
 
 172       $custom_fields = new CustomFields();
 
 173       $cf_1_type = $custom_fields->fields[0]['type'];
 
 174       if ($cf_1_type == CustomFields::TYPE_TEXT) {
 
 175         array_push($fields, 'cfl.value as cf_1');
 
 176       } elseif ($cf_1_type == CustomFields::TYPE_DROPDOWN) {
 
 177         array_push($fields, 'cfo.value as cf_1');
 
 181     if ($options['show_start']) {
 
 182       array_push($fields, "l.start as unformatted_start");
 
 183       array_push($fields, "TIME_FORMAT(l.start, '%k:%i') as start");
 
 186     if ($options['show_end'])
 
 187       array_push($fields, "TIME_FORMAT(sec_to_time(time_to_sec(l.start) + time_to_sec(l.duration)), '%k:%i') as finish");
 
 189     if ($options['show_duration'])
 
 190       array_push($fields, "TIME_FORMAT(l.duration, '%k:%i') as duration");
 
 192     if ($options['show_work_units']) {
 
 193       if ($user->getConfigOption('unit_totals_only'))
 
 194         array_push($fields, "null as units");
 
 196         $firstUnitThreshold = $user->getConfigInt('1st_unit_threshold', 0);
 
 197         $minutesInUnit = $user->getConfigInt('minutes_in_unit', 15);
 
 198         array_push($fields, "if(l.billable = 0 or time_to_sec(l.duration)/60 < $firstUnitThreshold, 0, ceil(time_to_sec(l.duration)/60/$minutesInUnit)) as units");
 
 202     if ($options['show_note'])
 
 203       array_push($fields, 'l.comment as note');
 
 205     $includeCost = $options['show_cost'];
 
 207       if (MODE_TIME == $trackingMode)
 
 208         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.
 
 210         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.
 
 211       array_push($fields, "null as expense"); 
 
 214     if ($canViewReports && $options['show_paid'])
 
 215       array_push($fields, 'l.paid');
 
 217     if ($canViewReports && $options['show_ip']) {
 
 218       array_push($fields, 'l.created');
 
 219       array_push($fields, 'l.created_ip');
 
 220       array_push($fields, 'l.modified');
 
 221       array_push($fields, 'l.modified_ip');
 
 223     // Add invoice name if it is selected.
 
 224     if (($canViewReports || $isClient) && $options['show_invoice'])
 
 225       array_push($fields, 'i.name as invoice');
 
 227     // Prepare sql query part for left joins.
 
 229     if ($options['show_client'] || $grouping_by_client)
 
 230       $left_joins .= " left join tt_clients c on (c.id = l.client_id)";
 
 231     if (($canViewReports || $isClient) && $options['show_invoice'])
 
 232       $left_joins .= " left join tt_invoices i on (i.id = l.invoice_id and i.status = 1)";
 
 233     if ($canViewReports || $isClient || $user->isPluginEnabled('ex'))
 
 234        $left_joins .= " left join tt_users u on (u.id = l.user_id)";
 
 235     if ($options['show_project'] || $grouping_by_project)
 
 236       $left_joins .= " left join tt_projects p on (p.id = l.project_id)";
 
 237     if ($options['show_task'] || $grouping_by_task)
 
 238       $left_joins .= " left join tt_tasks t on (t.id = l.task_id)";
 
 240       if ($cf_1_type == CustomFields::TYPE_TEXT)
 
 241         $left_joins .= " left join tt_custom_field_log cfl on (l.id = cfl.log_id and cfl.status = 1)";
 
 242       elseif ($cf_1_type == CustomFields::TYPE_DROPDOWN) {
 
 243         $left_joins .=  " left join tt_custom_field_log cfl on (l.id = cfl.log_id and cfl.status = 1)".
 
 244           " left join tt_custom_field_options cfo on (cfl.option_id = cfo.id)";
 
 247     if ($includeCost && MODE_TIME != $trackingMode)
 
 248       $left_joins .= " left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id)";
 
 250     $where = ttReportHelper::getWhere($options);
 
 252     // Construct sql query for tt_log items.
 
 253     $sql = "select ".join(', ', $fields)." from tt_log l $left_joins $where";
 
 254     // If we don't have expense items (such as when the Expenses plugin is disabled), the above is all sql we need,
 
 255     // with an exception of sorting part, that is added in the end.
 
 257     // However, when we have expenses, we need to do a union with a separate query for expense items from tt_expense_items table.
 
 258     if ($options['show_cost'] && $user->isPluginEnabled('ex')) { // if ex(penses) plugin is enabled
 
 260       $fields = array(); // An array of fields for database query.
 
 261       array_push($fields, 'ei.id');
 
 262       array_push($fields, 'ei.user_id');
 
 263       array_push($fields, '2 as type'); // Type 2 is for tt_expense_items entries.
 
 264       array_push($fields, 'ei.date');
 
 265       array_push($fields, 'ei.timesheet_id');
 
 266       if($canViewReports || $isClient)
 
 267         array_push($fields, 'u.name as user');
 
 268       // Add client name if it is selected.
 
 269       if ($options['show_client'] || $grouping_by_client)
 
 270         array_push($fields, 'c.name as client');
 
 271       // Add project name if it is selected.
 
 272       if ($options['show_project'] || $grouping_by_project)
 
 273         array_push($fields, 'p.name as project');
 
 274       if ($options['show_task'] || $grouping_by_task)
 
 275         array_push($fields, 'null'); // null for task name. We need to match column count for union.
 
 276       if ($options['show_custom_field_1'] || $grouping_by_cf_1)
 
 277         array_push($fields, 'null'); // null for cf_1.
 
 278       if ($options['show_start']) {
 
 279         array_push($fields, 'null'); // null for unformatted_start.
 
 280         array_push($fields, 'null'); // null for start.
 
 282       if ($options['show_end'])
 
 283         array_push($fields, 'null'); // null for finish.
 
 284       if ($options['show_duration'])
 
 285         array_push($fields, 'null'); // null for duration.
 
 286       if ($options['show_work_units'])
 
 287         array_push($fields, 'null as units'); // null for work units.
 
 288       // Use the note field to print item name.
 
 289       if ($options['show_note'])
 
 290         array_push($fields, 'ei.name as note');
 
 291       array_push($fields, 'ei.cost as cost');
 
 292       array_push($fields, 'ei.cost as expense');
 
 294       if ($canViewReports && $options['show_paid'])
 
 295         array_push($fields, 'ei.paid');
 
 297       if ($canViewReports && $options['show_ip']) {
 
 298         array_push($fields, 'ei.created');
 
 299         array_push($fields, 'ei.created_ip');
 
 300         array_push($fields, 'ei.modified');
 
 301         array_push($fields, 'ei.modified_ip');
 
 303       // Add invoice name if it is selected.
 
 304       if (($canViewReports || $isClient) && $options['show_invoice'])
 
 305         array_push($fields, 'i.name as invoice');
 
 307       // Prepare sql query part for left joins.
 
 309       if ($canViewReports || $isClient)
 
 310         $left_joins .= " left join tt_users u on (u.id = ei.user_id)";
 
 311       if ($options['show_client'] || $grouping_by_client)
 
 312         $left_joins .= " left join tt_clients c on (c.id = ei.client_id)";
 
 313       if ($options['show_project'] || $grouping_by_project)
 
 314         $left_joins .= " left join tt_projects p on (p.id = ei.project_id)";
 
 315       if (($canViewReports || $isClient) && $options['show_invoice'])
 
 316         $left_joins .= " left join tt_invoices i on (i.id = ei.invoice_id and i.status = 1)";
 
 318       $where = ttReportHelper::getExpenseWhere($options);
 
 320       // Construct sql query for expense items.
 
 321       $sql_for_expense_items = "select ".join(', ', $fields)." from tt_expense_items ei $left_joins $where";
 
 323       // Construct a union.
 
 324       $sql = "($sql) union all ($sql_for_expense_items)";
 
 327     // Determine sort part.
 
 328     $sort_part = ' order by ';
 
 330       $sort_part2 .= ($options['group_by1'] != null && $options['group_by1'] != 'no_grouping') ? ', '.$options['group_by1'] : '';
 
 331       $sort_part2 .= ($options['group_by2'] != null && $options['group_by2'] != 'no_grouping') ? ', '.$options['group_by2'] : '';
 
 332       $sort_part2 .= ($options['group_by3'] != null && $options['group_by3'] != 'no_grouping') ? ', '.$options['group_by3'] : '';
 
 333       if (!$grouping_by_date) $sort_part2 .= ', date';
 
 334       $sort_part .= ltrim($sort_part2, ', '); // Remove leading comma and space.
 
 336       $sort_part .= 'date';
 
 338     if (($canViewReports || $isClient) && $options['users'] && !$grouping_by_user)
 
 339       $sort_part .= ', user, type';
 
 340     if ($options['show_start'])
 
 341       $sort_part .= ', unformatted_start';
 
 342     $sort_part .= ', id';
 
 345     // By now we are ready with sql.
 
 347     // Obtain items for report.
 
 348     $res = $mdb2->query($sql);
 
 349     if (is_a($res, 'PEAR_Error')) die($res->getMessage());
 
 351     while ($val = $res->fetchRow()) {
 
 352       if ($convertTo12Hour) {
 
 353         if($val['start'] != '')
 
 354           $val['start'] = ttTimeHelper::to12HourFormat($val['start']);
 
 355         if($val['finish'] != '')
 
 356           $val['finish'] = ttTimeHelper::to12HourFormat($val['finish']);
 
 358       if (isset($val['cost'])) {
 
 359         if ('.' != $decimalMark)
 
 360           $val['cost'] = str_replace('.', $decimalMark, $val['cost']);
 
 362       if (isset($val['expense'])) {
 
 363         if ('.' != $decimalMark)
 
 364           $val['expense'] = str_replace('.', $decimalMark, $val['expense']);
 
 367       if ($grouping) $val['grouped_by'] = ttReportHelper::makeGroupByKey($options, $val);
 
 368       $val['date'] = ttDateToUserFormat($val['date']);
 
 370       $report_items[] = $val;
 
 373     return $report_items;
 
 376   // putInSession stores tt_log and tt_expense_items ids from a report in user session
 
 377   // as 2 comma-separated lists.
 
 378   static function putInSession($report_items) {
 
 379     unset($_SESSION['report_item_ids']);
 
 380     unset($_SESSION['report_item_expense_ids']);
 
 382     // Iterate through records and build 2 comma-separated lists.
 
 383     foreach($report_items as $item) {
 
 384       if ($item['type'] == 1)
 
 385         $report_item_ids .= ','.$item['id'];
 
 386       else if ($item['type'] == 2)
 
 387          $report_item_expense_ids .= ','.$item['id'];
 
 389     $report_item_ids = trim($report_item_ids, ',');
 
 390     $report_item_expense_ids = trim($report_item_expense_ids, ',');
 
 392     // The lists are reqdy. Put them in session.
 
 393     if ($report_item_ids) $_SESSION['report_item_ids'] = $report_item_ids;
 
 394     if ($report_item_expense_ids) $_SESSION['report_item_expense_ids'] = $report_item_expense_ids;
 
 397   // getFromSession obtains tt_log and tt_expense_items ids stored in user session.
 
 398   static function getFromSession() {
 
 400     $report_item_ids = $_SESSION['report_item_ids'];
 
 401     if ($report_item_ids)
 
 402       $items['report_item_ids'] = explode(',', $report_item_ids);
 
 403     $report_item_expense_ids = $_SESSION['report_item_expense_ids'];
 
 404     if ($report_item_expense_ids)
 
 405       $items['report_item_expense_ids'] = explode(',', $report_item_expense_ids);
 
 409   // getSubtotals calculates report items subtotals when a report is grouped by.
 
 410   // Without expenses, it's a simple select with group by.
 
 411   // With expenses, it becomes a select with group by from a combined set of records obtained with "union all".
 
 412   static function getSubtotals($options) {
 
 414     $mdb2 = getConnection();
 
 416     $concat_part = ttReportHelper::makeConcatPart($options);
 
 417     $work_unit_part = ttReportHelper::makeWorkUnitPart($options);
 
 418     $join_part = ttReportHelper::makeJoinPart($options);
 
 419     $cost_part = ttReportHelper::makeCostPart($options);
 
 420     $where = ttReportHelper::getWhere($options);
 
 421     $group_by_part = ttReportHelper::makeGroupByPart($options);
 
 423     $parts = "$concat_part, sum(time_to_sec(l.duration)) as time, null as expenses".$work_unit_part.$cost_part;
 
 424     $sql = "select $parts from tt_log l $join_part $where $group_by_part";
 
 425     // By now we have sql for time items.
 
 427     // However, when we have expenses, we need to do a union with a separate query for expense items from tt_expense_items table.
 
 428     if ($options['show_cost'] && $user->isPluginEnabled('ex')) { // if ex(penses) plugin is enabled
 
 430       $concat_part = ttReportHelper::makeConcatExpensesPart($options);
 
 431       $join_part = ttReportHelper::makeJoinExpensesPart($options);
 
 432       $where = ttReportHelper::getExpenseWhere($options);
 
 433       $group_by_expenses_part = ttReportHelper::makeGroupByExpensesPart($options);
 
 434       $sql_for_expenses = "select $concat_part, null as time";
 
 435       if ($options['show_work_units']) $sql_for_expenses .= ", null as units";
 
 436       $sql_for_expenses .= ", sum(ei.cost) as cost, sum(ei.cost) as expenses from tt_expense_items ei $join_part $where $group_by_expenses_part";
 
 438       // Create a combined query.
 
 439       $fields = ttReportHelper::makeCombinedSelectPart($options);
 
 440       $combined = "select $fields, sum(time) as time";
 
 441       if ($options['show_work_units']) $combined .= ", sum(units) as units";
 
 442       $combined .= ", sum(cost) as cost, sum(expenses) as expenses from (($sql) union all ($sql_for_expenses)) t group by $fields";
 
 447     $res = $mdb2->query($sql);
 
 448     if (is_a($res, 'PEAR_Error')) die($res->getMessage());
 
 449     while ($val = $res->fetchRow()) {
 
 450       $time = $val['time'] ? sec_to_time_fmt_hm($val['time']) : null;
 
 451       $rowLabel = ttReportHelper::makeGroupByLabel($val['group_field'], $options);
 
 452       if ($options['show_cost']) {
 
 453         $decimalMark = $user->getDecimalMark();
 
 454         if ('.' != $decimalMark) {
 
 455           $val['cost'] = str_replace('.', $decimalMark, $val['cost']);
 
 456           $val['expenses'] = str_replace('.', $decimalMark, $val['expenses']);
 
 458         $subtotals[$val['group_field']] = array('name'=>$rowLabel,'user'=>$val['user'],'project'=>$val['project'],'task'=>$val['task'],'client'=>$val['client'],'cf_1'=>$val['cf_1'],'time'=>$time,'units'=> $val['units'],'cost'=>$val['cost'],'expenses'=>$val['expenses']);
 
 460         $subtotals[$val['group_field']] = array('name'=>$rowLabel,'user'=>$val['user'],'project'=>$val['project'],'task'=>$val['task'],'client'=>$val['client'],'cf_1'=>$val['cf_1'],'time'=>$time, 'units'=> $val['units']);
 
 466   // getTotals calculates total hours and cost for all report items.
 
 467   static function getTotals($options)
 
 470     $mdb2 = getConnection();
 
 472     $trackingMode = $user->getTrackingMode();
 
 473     $decimalMark = $user->getDecimalMark();
 
 474     $where = ttReportHelper::getWhere($options);
 
 477     $time_part = "sum(time_to_sec(l.duration)) as time";
 
 478     if ($options['show_work_units']) {
 
 479       $unitTotalsOnly = $user->getConfigOption('unit_totals_only');
 
 480       $firstUnitThreshold = $user->getConfigInt('1st_unit_threshold', 0);
 
 481       $minutesInUnit = $user->getConfigInt('minutes_in_unit', 15);
 
 482       $units_part = $unitTotalsOnly ? ", null as units" : ", sum(if(l.billable = 0 or time_to_sec(l.duration)/60 < $firstUnitThreshold, 0, ceil(time_to_sec(l.duration)/60/$minutesInUnit))) as units";
 
 484     if ($options['show_cost']) {
 
 485       if (MODE_TIME == $trackingMode)
 
 486         $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";
 
 488         $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";
 
 490       $cost_part = ", null as cost, null as expenses";
 
 492     if ($options['show_cost']) {
 
 493       if (MODE_TIME == $trackingMode) {
 
 494         $left_joins = "left join tt_users u on (l.user_id = u.id)";
 
 496         $left_joins = "left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id)";
 
 499     // Prepare a query for time items.
 
 500     $sql = "select $time_part $units_part $cost_part from tt_log l $left_joins $where";
 
 502     // If we have expenses, query becomes a bit more complex.
 
 503     if ($options['show_cost'] && $user->isPluginEnabled('ex')) {
 
 504       $where = ttReportHelper::getExpenseWhere($options);
 
 505       $sql_for_expenses = "select null as time";
 
 506       if ($options['show_work_units']) $sql_for_expenses .= ", null as units";
 
 507       $sql_for_expenses .= ", sum(cost) as cost, sum(cost) as expenses from tt_expense_items ei $where";
 
 509       // Create a combined query.
 
 510       $combined = "select sum(time) as time";
 
 511       if ($options['show_work_units']) $combined .= ", sum(units) as units";
 
 512       $combined .= ", sum(cost) as cost, sum(expenses) as expenses from (($sql) union all ($sql_for_expenses)) t";
 
 517     $res = $mdb2->query($sql);
 
 518     if (is_a($res, 'PEAR_Error')) die($res->getMessage());
 
 520     $val = $res->fetchRow();
 
 521     $total_time = $val['time'] ? sec_to_time_fmt_hm($val['time']) : null;
 
 522     if ($options['show_cost']) {
 
 523       $total_cost = $val['cost'];
 
 524       if (!$total_cost) $total_cost = '0.00';
 
 525       if ('.' != $decimalMark)
 
 526         $total_cost = str_replace('.', $decimalMark, $total_cost);
 
 527       $total_expenses = $val['expenses'];
 
 528       if (!$total_expenses) $total_expenses = '0.00';
 
 529       if ('.' != $decimalMark)
 
 530         $total_expenses = str_replace('.', $decimalMark, $total_expenses);
 
 533     $dateFormat = $user->getDateFormat();
 
 534     if ($options['period'])
 
 535       $period = new Period($options['period'], new DateAndTime($dateFormat));
 
 537       $period = new Period();
 
 539         new DateAndTime($dateFormat, $options['period_start']),
 
 540         new DateAndTime($dateFormat, $options['period_end']));
 
 543     $totals['start_date'] = $period->getStartDate();
 
 544     $totals['end_date'] = $period->getEndDate();
 
 545     $totals['time'] = $total_time;
 
 546     $totals['units'] = $val['units'];
 
 547     $totals['cost'] = $total_cost;
 
 548     $totals['expenses'] = $total_expenses;
 
 553   // The assignToInvoice assigns a set of records to a specific invoice.
 
 554   static function assignToInvoice($invoice_id, $time_log_ids, $expense_item_ids) {
 
 556     $mdb2 = getConnection();
 
 558     $group_id = $user->getGroup();
 
 559     $org_id = $user->org_id;
 
 562       $sql = "update tt_log set invoice_id = ".$mdb2->quote($invoice_id).
 
 563         " where id in(".join(', ', $time_log_ids).") and group_id = $group_id and org_id = $org_id";
 
 564       $affected = $mdb2->exec($sql);
 
 565       if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
 
 567     if ($expense_item_ids) {
 
 568       $sql = "update tt_expense_items set invoice_id = ".$mdb2->quote($invoice_id).
 
 569         " where id in(".join(', ', $expense_item_ids).") and group_id = $group_id and org_id = $org_id";
 
 570       $affected = $mdb2->exec($sql);
 
 571       if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
 
 575   // The markPaid marks a set of records as either paid or unpaid.
 
 576   static function markPaid($time_log_ids, $expense_item_ids, $paid = true) {
 
 578     $mdb2 = getConnection();
 
 580     $group_id = $user->getGroup();
 
 581     $org_id = $user->org_id;
 
 583     $paid_val = (int) $paid;
 
 585       $sql = "update tt_log set paid = $paid_val".
 
 586         " where id in(".join(', ', $time_log_ids).") and group_id = $group_id and org_id = $org_id";
 
 587       $affected = $mdb2->exec($sql);
 
 588       if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
 
 590     if ($expense_item_ids) {
 
 591       $sql = "update tt_expense_items set paid = $paid_val".
 
 592         " where id in(".join(', ', $expense_item_ids).") and group_id = $group_id and org_id = $org_id";
 
 593       $affected = $mdb2->exec($sql);
 
 594       if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
 
 598   // prepareReportBody - prepares an email body for report.
 
 599   static function prepareReportBody($options, $comment = null)
 
 604     // Determine these once as they are used in multiple places in this function.
 
 605     $canViewReports = $user->can('view_reports') || $user->can('view_all_reports');
 
 606     $isClient = $user->isClient();
 
 608     $items = ttReportHelper::getItems($options);
 
 609     $grouping = ttReportHelper::grouping($options);
 
 611       $subtotals = ttReportHelper::getSubtotals($options);
 
 612     $totals = ttReportHelper::getTotals($options);
 
 614     // Use custom fields plugin if it is enabled.
 
 615     if ($user->isPluginEnabled('cf'))
 
 616       $custom_fields = new CustomFields();
 
 618     // Define some styles to use in email.
 
 619     $style_title = 'text-align: center; font-size: 15pt; font-family: Arial, Helvetica, sans-serif;';
 
 620     $tableHeader = 'font-weight: bold; background-color: #a6ccf7; text-align: left;';
 
 621     $tableHeaderCentered = 'font-weight: bold; background-color: #a6ccf7; text-align: center;';
 
 622     $rowItem = 'background-color: #ffffff;';
 
 623     $rowItemAlt = 'background-color: #f5f5f5;';
 
 624     $rowSubtotal = 'background-color: #e0e0e0;';
 
 625     $cellLeftAligned = 'text-align: left; vertical-align: top;';
 
 626     $cellRightAligned = 'text-align: right; vertical-align: top;';
 
 627     $cellLeftAlignedSubtotal = 'font-weight: bold; text-align: left; vertical-align: top;';
 
 628     $cellRightAlignedSubtotal = 'font-weight: bold; text-align: right; vertical-align: top;';
 
 630     // Start creating email body.
 
 632     $body .= '<head><meta http-equiv="content-type" content="text/html; charset='.CHARSET.'"></head>';
 
 636     $body .= '<p style="'.$style_title.'">'.$i18n->get('form.mail.report_subject').': '.$totals['start_date'].' - '.$totals['end_date'].'</p>';
 
 639     if ($comment) $body .= '<p>'.htmlspecialchars($comment).'</p>';
 
 641     if ($options['show_totals_only']) {
 
 642       // Totals only report. Output subtotals.
 
 643       $group_by_header = ttReportHelper::makeGroupByHeader($options);
 
 645       $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
 
 647       $body .= '<td style="'.$tableHeader.'">'.$group_by_header.'</td>';
 
 648       if ($options['show_duration'])
 
 649         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.duration').'</td>';
 
 650       if ($options['show_work_units'])
 
 651         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.work_units_short').'</td>';
 
 652       if ($options['show_cost'])
 
 653         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.cost').'</td>';
 
 655       foreach($subtotals as $subtotal) {
 
 656         $body .= '<tr style="'.$rowSubtotal.'">';
 
 657         $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($subtotal['name'] ? htmlspecialchars($subtotal['name']) : ' ').'</td>';
 
 658         if ($options['show_duration']) {
 
 659           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
 
 660           if ($subtotal['time'] <> '0:00') $body .= $subtotal['time'];
 
 663         if ($options['show_work_units']) {
 
 664           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
 
 665           $body .= $subtotal['units'];
 
 668         if ($options['show_cost']) {
 
 669           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
 
 670           $body .= ($canViewReports || $isClient) ? $subtotal['cost'] : $subtotal['expenses'];
 
 677       $body .= '<tr><td> </td></tr>';
 
 678       $body .= '<tr style="'.$rowSubtotal.'">';
 
 679       $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.total').'</td>';
 
 680       if ($options['show_duration']) {
 
 681         $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
 
 682         if ($totals['time'] <> '0:00') $body .= $totals['time'];
 
 685       if ($options['show_work_units']) {
 
 686         $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
 
 687         $body .= $totals['units'];
 
 690       if ($options['show_cost']) {
 
 691         $body .= '<td nowrap style="'.$cellRightAlignedSubtotal.'">'.htmlspecialchars($user->currency).' ';
 
 692         $body .= ($canViewReports || $isClient) ? $totals['cost'] : $totals['expenses'];
 
 701       // Print table header.
 
 702       $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
 
 704       $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.date').'</td>';
 
 705       if ($canViewReports || $isClient)
 
 706         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.user').'</td>';
 
 707       if ($options['show_client'])
 
 708         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.client').'</td>';
 
 709       if ($options['show_project'])
 
 710         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.project').'</td>';
 
 711       if ($options['show_task'])
 
 712         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.task').'</td>';
 
 713       if ($options['show_custom_field_1'])
 
 714         $body .= '<td style="'.$tableHeader.'">'.htmlspecialchars($custom_fields->fields[0]['label']).'</td>';
 
 715       if ($options['show_start'])
 
 716         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.start').'</td>';
 
 717       if ($options['show_end'])
 
 718         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.finish').'</td>';
 
 719       if ($options['show_duration'])
 
 720         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.duration').'</td>';
 
 721       if ($options['show_work_units'])
 
 722         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.work_units_short').'</td>';
 
 723       if ($options['show_note'])
 
 724         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.note').'</td>';
 
 725       if ($options['show_cost'])
 
 726         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.cost').'</td>';
 
 727       if ($options['show_paid'])
 
 728         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.paid').'</td>';
 
 729       if ($options['show_ip'])
 
 730         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.ip').'</td>';
 
 731       if ($options['show_invoice'])
 
 732         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.invoice').'</td>';
 
 735       // Initialize variables to print subtotals.
 
 736       if ($items && $grouping) {
 
 737         $print_subtotals = true;
 
 739         $prev_grouped_by = '';
 
 740         $cur_grouped_by = '';
 
 742       // Initialize variables to alternate color of rows for different dates.
 
 745       $row_style = $rowItem;
 
 747       // Print report items.
 
 748       if (is_array($items)) {
 
 749         foreach ($items as $record) {
 
 750           $cur_date = $record['date'];
 
 751           // Print a subtotal row after a block of grouped items.
 
 752           if ($print_subtotals) {
 
 753             $cur_grouped_by = $record['grouped_by'];
 
 754             if ($cur_grouped_by != $prev_grouped_by && !$first_pass) {
 
 755               $body .= '<tr style="'.$rowSubtotal.'">';
 
 756               $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.subtotal').'</td>';
 
 757               $subtotal_name = htmlspecialchars($subtotals[$prev_grouped_by]['name']);
 
 758               if ($canViewReports || $isClient) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['user'].'</td>';
 
 759               if ($options['show_client']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['client'].'</td>';
 
 760               if ($options['show_project']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['project'].'</td>';
 
 761               if ($options['show_task']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['task'].'</td>';
 
 762               if ($options['show_custom_field_1']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['cf_1'].'</td>';
 
 763               if ($options['show_start']) $body .= '<td></td>';
 
 764               if ($options['show_end']) $body .= '<td></td>';
 
 765               if ($options['show_duration']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['time'].'</td>';
 
 766               if ($options['show_work_units']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['units'].'</td>';
 
 767               if ($options['show_note']) $body .= '<td></td>';
 
 768               if ($options['show_cost']) {
 
 769                 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
 
 770                 $body .= ($canViewReports || $isClient) ? $subtotals[$prev_grouped_by]['cost'] : $subtotals[$prev_grouped_by]['expenses'];
 
 773               if ($options['show_paid']) $body .= '<td></td>';
 
 774               if ($options['show_ip']) $body .= '<td></td>';
 
 775               if ($options['show_invoice']) $body .= '<td></td>';
 
 777               $body .= '<tr><td> </td></tr>';
 
 782           // Print a regular row.
 
 783           if ($cur_date != $prev_date)
 
 784             $row_style = ($row_style == $rowItem) ? $rowItemAlt : $rowItem;
 
 785           $body .= '<tr style="'.$row_style.'">';
 
 786           $body .= '<td style="'.$cellLeftAligned.'">'.$record['date'].'</td>';
 
 787           if ($canViewReports || $isClient)
 
 788             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['user']).'</td>';
 
 789           if ($options['show_client'])
 
 790             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['client']).'</td>';
 
 791           if ($options['show_project'])
 
 792             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['project']).'</td>';
 
 793           if ($options['show_task'])
 
 794             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['task']).'</td>';
 
 795           if ($options['show_custom_field_1'])
 
 796             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['cf_1']).'</td>';
 
 797           if ($options['show_start'])
 
 798             $body .= '<td nowrap style="'.$cellRightAligned.'">'.$record['start'].'</td>';
 
 799           if ($options['show_end'])
 
 800             $body .= '<td nowrap style="'.$cellRightAligned.'">'.$record['finish'].'</td>';
 
 801           if ($options['show_duration'])
 
 802             $body .= '<td style="'.$cellRightAligned.'">'.$record['duration'].'</td>';
 
 803           if ($options['show_work_units'])
 
 804             $body .= '<td style="'.$cellRightAligned.'">'.$record['units'].'</td>';
 
 805           if ($options['show_note'])
 
 806             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['note']).'</td>';
 
 807           if ($options['show_cost'])
 
 808             $body .= '<td style="'.$cellRightAligned.'">'.$record['cost'].'</td>';
 
 809           if ($options['show_paid']) {
 
 810             $body .= '<td style="'.$cellRightAligned.'">';
 
 811             $body .= $record['paid'] == 1 ? $i18n->get('label.yes') : $i18n->get('label.no');
 
 814           if ($options['show_ip']) {
 
 815             $body .= '<td style="'.$cellRightAligned.'">';
 
 816             $body .= $record['modified'] ? $record['modified_ip'].' '.$record['modified'] : $record['created_ip'].' '.$record['created'];
 
 819           if ($options['show_invoice'])
 
 820             $body .= '<td style="'.$cellRightAligned.'">'.htmlspecialchars($record['invoice']).'</td>';
 
 823           $prev_date = $record['date'];
 
 824           if ($print_subtotals)
 
 825             $prev_grouped_by = $record['grouped_by'];
 
 829       // Print a terminating subtotal.
 
 830       if ($print_subtotals) {
 
 831         $body .= '<tr style="'.$rowSubtotal.'">';
 
 832         $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.subtotal').'</td>';
 
 833         $subtotal_name = htmlspecialchars($subtotals[$cur_grouped_by]['name']);
 
 834         if ($canViewReports || $isClient) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['user'].'</td>';
 
 835         if ($options['show_client']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['client'].'</td>';
 
 836         if ($options['show_project']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['project'].'</td>';
 
 837         if ($options['show_task']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['task'].'</td>';
 
 838         if ($options['show_custom_field_1']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['cf_1'].'</td>';
 
 839         if ($options['show_start']) $body .= '<td></td>';
 
 840         if ($options['show_end']) $body .= '<td></td>';
 
 841         if ($options['show_duration']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$cur_grouped_by]['time'].'</td>';
 
 842         if ($options['show_work_units']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$cur_grouped_by]['units'].'</td>';
 
 843         if ($options['show_note']) $body .= '<td></td>';
 
 844         if ($options['show_cost']) {
 
 845           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
 
 846           $body .= ($canViewReports || $isClient) ? $subtotals[$cur_grouped_by]['cost'] : $subtotals[$cur_grouped_by]['expenses'];
 
 849         if ($options['show_paid']) $body .= '<td></td>';
 
 850         if ($options['show_ip']) $body .= '<td></td>';
 
 851         if ($options['show_invoice']) $body .= '<td></td>';
 
 856       $body .= '<tr><td> </td></tr>';
 
 857       $body .= '<tr style="'.$rowSubtotal.'">';
 
 858       $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.total').'</td>';
 
 859       if ($canViewReports || $isClient) $body .= '<td></td>';
 
 860       if ($options['show_client']) $body .= '<td></td>';
 
 861       if ($options['show_project']) $body .= '<td></td>';
 
 862       if ($options['show_task']) $body .= '<td></td>';
 
 863       if ($options['show_custom_field_1']) $body .= '<td></td>';
 
 864       if ($options['show_start']) $body .= '<td></td>';
 
 865       if ($options['show_end']) $body .= '<td></td>';
 
 866       if ($options['show_duration']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$totals['time'].'</td>';
 
 867       if ($options['show_work_units']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$totals['units'].'</td>';
 
 868       if ($options['show_note']) $body .= '<td></td>';
 
 869       if ($options['show_cost']) {
 
 870         $body .= '<td nowrap style="'.$cellRightAlignedSubtotal.'">'.htmlspecialchars($user->currency).' ';
 
 871         $body .= ($canViewReports || $isClient) ? $totals['cost'] : $totals['expenses'];
 
 874       if ($options['show_paid']) $body .= '<td></td>';
 
 875       if ($options['show_ip']) $body .= '<td></td>';
 
 876       if ($options['show_invoice']) $body .= '<td></td>';
 
 883     if (!defined('REPORT_FOOTER') || !(REPORT_FOOTER == false))
 
 884       $body .= '<p style="text-align: center;">'.$i18n->get('form.mail.footer').'</p>';
 
 886     // Finish creating email body.
 
 887     $body .= '</body></html>';
 
 892   // checkFavReportCondition - checks whether it is okay to send fav report.
 
 893   static function checkFavReportCondition($options, $condition)
 
 895     $items = ttReportHelper::getItems($options);
 
 897     $condition = trim(str_replace('count', '', $condition));
 
 899     $greater_or_equal = ttStartsWith($condition, '>=');
 
 900     if ($greater_or_equal) $condition = trim(str_replace('>=', '', $condition));
 
 902     $less_or_equal = ttStartsWith($condition, '<=');
 
 903     if ($less_or_equal) $condition = trim(str_replace('<=', '', $condition));
 
 905     $not_equal = ttStartsWith($condition, '<>');
 
 906     if ($not_equal) $condition = trim(str_replace('<>', '', $condition));
 
 908     $greater = ttStartsWith($condition, '>');
 
 909     if ($greater) $condition = trim(str_replace('>', '', $condition));
 
 911     $less = ttStartsWith($condition, '<');
 
 912     if ($less) $condition = trim(str_replace('<', '', $condition));
 
 914     $equal = ttStartsWith($condition, '=');
 
 915     if ($equal) $condition = trim(str_replace('=', '', $condition));
 
 917     $count_required = (int) $condition;
 
 919     if ($greater && count($items) > $count_required) return true;
 
 920     if ($greater_or_equal && count($items) >= $count_required) return true;
 
 921     if ($less && count($items) < $count_required) return true;
 
 922     if ($less_or_equal && count($items) <= $count_required) return true;
 
 923     if ($equal && count($items) == $count_required) return true;
 
 924     if ($not_equal && count($items) <> $count_required) return true;
 
 929   // sendFavReport - sends a favorite report to a specified email, called from cron.php
 
 930   static function sendFavReport($options, $subject, $email, $cc) {
 
 931     // We are called from cron.php, we have no $bean in session.
 
 932     // cron.php sets global $user and $i18n objects to match our favorite report user.
 
 936     // Prepare report body.
 
 937     $body = ttReportHelper::prepareReportBody($options);
 
 939     import('mail.Mailer');
 
 940     $mailer = new Mailer();
 
 941     $mailer->setCharSet(CHARSET);
 
 942     $mailer->setContentType('text/html');
 
 943     $mailer->setSender(SENDER);
 
 945       $mailer->setReceiverCC($cc);
 
 946     if (!empty($user->bcc_email))
 
 947       $mailer->setReceiverBCC($user->bcc_email);
 
 948     $mailer->setReceiver($email);
 
 949     $mailer->setMailMode(MAIL_MODE);
 
 950     if (empty($subject)) $subject = $options['name'];
 
 951     if (!$mailer->send($subject, $body))
 
 957   // getReportOptions - returns an array of report options constructed from session bean.
 
 959   // Note: similarly to ttFavReportHelper::getReportOptions, this function is a part of
 
 960   // refactoring to simplify maintenance of report generating functions, as we currently
 
 961   // have 2 sets: normal reporting (from bean), and fav report emailing (from db fields).
 
 962   // Using options obtained from either db or bean shall allow us to use only one set of functions.
 
 963   static function getReportOptions($bean) {
 
 966     // Prepare an array of report options.
 
 969     // Construct one by one.
 
 970     $options['name'] = null; // No name required.
 
 971     $options['user_id'] = $user->id; // Not sure if we need user_id here. Fav reports use it to recycle $user object in cron.php.
 
 972     $options['client_id'] = $bean->getAttribute('client');
 
 973     $options['cf_1_option_id'] = $bean->getAttribute('option');
 
 974     $options['project_id'] = $bean->getAttribute('project');
 
 975     $options['task_id'] = $bean->getAttribute('task');
 
 976     $options['billable'] = $bean->getAttribute('include_records');
 
 977     $options['invoice'] = $bean->getAttribute('invoice');
 
 978     $options['paid_status'] = $bean->getAttribute('paid_status');
 
 979     if (is_array($bean->getAttribute('users'))) $options['users'] = join(',', $bean->getAttribute('users'));
 
 980     $options['period'] = $bean->getAttribute('period');
 
 981     $options['period_start'] = $bean->getAttribute('start_date');
 
 982     $options['period_end'] = $bean->getAttribute('end_date');
 
 983     $options['show_client'] = $bean->getAttribute('chclient');
 
 984     $options['show_invoice'] = $bean->getAttribute('chinvoice');
 
 985     $options['show_paid'] = $bean->getAttribute('chpaid');
 
 986     $options['show_ip'] = $bean->getAttribute('chip');
 
 987     $options['show_project'] = $bean->getAttribute('chproject');
 
 988     $options['show_start'] = $bean->getAttribute('chstart');
 
 989     $options['show_duration'] = $bean->getAttribute('chduration');
 
 990     $options['show_cost'] = $bean->getAttribute('chcost');
 
 991     $options['show_task'] = $bean->getAttribute('chtask');
 
 992     $options['show_end'] = $bean->getAttribute('chfinish');
 
 993     $options['show_note'] = $bean->getAttribute('chnote');
 
 994     $options['show_custom_field_1'] = $bean->getAttribute('chcf_1');
 
 995     $options['show_work_units'] = $bean->getAttribute('chunits');
 
 996     $options['show_totals_only'] = $bean->getAttribute('chtotalsonly');
 
 997     $options['group_by1'] = $bean->getAttribute('group_by1');
 
 998     $options['group_by2'] = $bean->getAttribute('group_by2');
 
 999     $options['group_by3'] = $bean->getAttribute('group_by3');
 
1003   // verifyBean is a security function to make sure data in bean makes sense for a group.
 
1004   static function verifyBean($bean) {
 
1008     $users_in_bean = $bean->getAttribute('users');
 
1009     if (is_array($users_in_bean)) {
 
1010       $users_in_group = ttGroupHelper::getUsers();
 
1011       foreach ($users_in_group as $user_in_group) {
 
1012         $valid_ids[] = $user_in_group['id'];
 
1014       foreach ($users_in_bean as $user_in_bean) {
 
1015         if (!in_array($user_in_bean, $valid_ids)) {
 
1021     // TODO: add additional checks here. Perhaps do it before saving the bean for consistency.
 
1025   // makeGroupByKey builds a combined group by key from group_by1, group_by2 and group_by3 values
 
1026   // (passed in $options) and a row of data ($row obtained from a db query).
 
1027   static function makeGroupByKey($options, $row) {
 
1028     if ($options['group_by1'] != null && $options['group_by1'] != 'no_grouping') {
 
1029       // We have group_by1.
 
1030       $group_by1 = $options['group_by1'];
 
1031       $group_by1_value = $row[$group_by1];
 
1032       //if ($group_by1 == 'date') $group_by1_value = ttDateToUserFormat($group_by1_value);
 
1033       if (empty($group_by1_value)) $group_by1_value = 'Null'; // To match what comes out of makeConcatPart.
 
1034       $group_by_key .= ' - '.$group_by1_value;
 
1036     if ($options['group_by2'] != null && $options['group_by2'] != 'no_grouping') {
 
1037       // We have group_by2.
 
1038       $group_by2 = $options['group_by2'];
 
1039       $group_by2_value = $row[$group_by2];
 
1040       //if ($group_by2 == 'date') $group_by2_value = ttDateToUserFormat($group_by2_value);
 
1041       if (empty($group_by2_value)) $group_by2_value = 'Null'; // To match what comes out of makeConcatPart.
 
1042       $group_by_key .= ' - '.$group_by2_value;
 
1044     if ($options['group_by3'] != null && $options['group_by3'] != 'no_grouping') {
 
1045       // We have group_by3.
 
1046       $group_by3 = $options['group_by3'];
 
1047       $group_by3_value = $row[$group_by3];
 
1048       //if ($group_by3 == 'date') $group_by3_value = ttDateToUserFormat($group_by3_value);
 
1049       if (empty($group_by3_value)) $group_by3_value = 'Null'; // To match what comes out of makeConcatPart.
 
1050       $group_by_key .= ' - '.$group_by3_value;
 
1052     $group_by_key = trim($group_by_key, ' -');
 
1053     return $group_by_key;
 
1056   // makeGroupByPart builds a combined group by part for sql query for time items using group_by1,
 
1057   // group_by2, and group_by3 values passed in $options.
 
1058   static function makeGroupByPart($options) {
 
1059     if (!ttReportHelper::grouping($options)) return null;
 
1061     $group_by1 = $options['group_by1'];
 
1062     $group_by2 = $options['group_by2'];
 
1063     $group_by3 = $options['group_by3'];
 
1065     switch ($group_by1) {
 
1067         $group_by_parts .= ', l.date';
 
1070         $group_by_parts .= ', u.name';
 
1073         $group_by_parts .= ', c.name';
 
1076         $group_by_parts .= ', p.name';
 
1079         $group_by_parts .= ', t.name';
 
1082         $group_by_parts .= ', cfo.value';
 
1085     switch ($group_by2) {
 
1087         $group_by_parts .= ', l.date';
 
1090         $group_by_parts .= ', u.name';
 
1093         $group_by_parts .= ', c.name';
 
1096         $group_by_parts .= ', p.name';
 
1099         $group_by_parts .= ', t.name';
 
1102         $group_by_parts .= ', cfo.value';
 
1105     switch ($group_by3) {
 
1107         $group_by_parts .= ', l.date';
 
1110         $group_by_parts .= ', u.name';
 
1113         $group_by_parts .= ', c.name';
 
1116         $group_by_parts .= ', p.name';
 
1119         $group_by_parts .= ', t.name';
 
1122         $group_by_parts .= ', cfo.value';
 
1125     // Remove garbage from the beginning.
 
1126     $group_by_parts = ltrim($group_by_parts, ', ');
 
1127     $group_by_part = "group by $group_by_parts";
 
1128     return $group_by_part;
 
1131   // makeGroupByExpensesPart builds a combined group by part for sql query for expense items using
 
1132   // group_by1, group_by2, and group_by3 values passed in $options.
 
1133   static function makeGroupByExpensesPart($options) {
 
1134     $no_grouping = ($options['group_by1'] == null || $options['group_by1'] == 'no_grouping') &&
 
1135       ($options['group_by2'] == null || $options['group_by2'] == 'no_grouping') &&
 
1136       ($options['group_by3'] == null || $options['group_by3'] == 'no_grouping');
 
1137     if ($no_grouping) return null;
 
1139     $group_by1 = $options['group_by1'];
 
1140     $group_by2 = $options['group_by2'];
 
1141     $group_by3 = $options['group_by3'];
 
1143     switch ($group_by1) {
 
1145         $group_by_parts .= ', ei.date';
 
1148         $group_by_parts .= ', u.name';
 
1151         $group_by_parts .= ', c.name';
 
1154         $group_by_parts .= ', p.name';
 
1157     switch ($group_by2) {
 
1159         $group_by_parts .= ', ei.date';
 
1162         $group_by_parts .= ', u.name';
 
1165         $group_by_parts .= ', c.name';
 
1168         $group_by_parts .= ', p.name';
 
1171     switch ($group_by3) {
 
1173         $group_by_parts .= ', ei.date';
 
1176         $group_by_parts .= ', u.name';
 
1179         $group_by_parts .= ', c.name';
 
1182         $group_by_parts .= ', p.name';
 
1185     // Remove garbage from the beginning.
 
1186     $group_by_parts = ltrim($group_by_parts, ', ');
 
1187     if ($group_by_parts)
 
1188       $group_by_part = "group by $group_by_parts";
 
1189     return $group_by_part;
 
1192   // makeConcatPart builds a concatenation part for getSubtotals query (for time items).
 
1193   static function makeConcatPart($options) {
 
1194     $group_by1 = $options['group_by1'];
 
1195     $group_by2 = $options['group_by2'];
 
1196     $group_by3 = $options['group_by3'];
 
1198     switch ($group_by1) {
 
1200         $what_to_concat .= ", ' - ', l.date";
 
1203         $what_to_concat .= ", ' - ', u.name";
 
1204         $fields_part .= ', u.name as user';
 
1207         $what_to_concat .= ", ' - ', coalesce(c.name, 'Null')";
 
1208         $fields_part .= ', c.name as client';
 
1211         $what_to_concat .= ", ' - ', coalesce(p.name, 'Null')";
 
1212         $fields_part .= ', p.name as project';
 
1215         $what_to_concat .= ", ' - ', coalesce(t.name, 'Null')";
 
1216         $fields_part .= ', t.name as task';
 
1219         $what_to_concat .= ", ' - ', coalesce(cfo.value, 'Null')";
 
1220         $fields_part .= ', cfo.value as cf_1';
 
1223     switch ($group_by2) {
 
1225         $what_to_concat .= ", ' - ', l.date";
 
1228         $what_to_concat .= ", ' - ', u.name";
 
1229         $fields_part .= ', u.name as user';
 
1232         $what_to_concat .= ", ' - ', coalesce(c.name, 'Null')";
 
1233         $fields_part .= ', c.name as client';
 
1236         $what_to_concat .= ", ' - ', coalesce(p.name, 'Null')";
 
1237         $fields_part .= ', p.name as project';
 
1240         $what_to_concat .= ", ' - ', coalesce(t.name, 'Null')";
 
1241         $fields_part .= ', t.name as task';
 
1244         $what_to_concat .= ", ' - ', coalesce(cfo.value, 'Null')";
 
1245         $fields_part .= ', cfo.value as cf_1';
 
1248     switch ($group_by3) {
 
1250         $what_to_concat .= ", ' - ', l.date";
 
1253         $what_to_concat .= ", ' - ', u.name";
 
1254         $fields_part .= ', u.name as user';
 
1257         $what_to_concat .= ", ' - ', coalesce(c.name, 'Null')";
 
1258         $fields_part .= ', c.name as client';
 
1261         $what_to_concat .= ", ' - ', coalesce(p.name, 'Null')";
 
1262         $fields_part .= ', p.name as project';
 
1265         $what_to_concat .= ", ' - ', coalesce(t.name, 'Null')";
 
1266         $fields_part .= ', t.name as task';
 
1269         $what_to_concat .= ", ' - ', coalesce(cfo.value, 'Null')";
 
1270         $fields_part .= ', cfo.value as cf_1';
 
1273     // Remove garbage from both ends.
 
1274     $what_to_concat = trim($what_to_concat, "', -");
 
1275     $concat_part = "concat($what_to_concat) as group_field";
 
1276     $concat_part = trim($concat_part, ' -');
 
1277     return "$concat_part $fields_part";
 
1280   // makeConcatPart builds a concatenation part for getSubtotals query (for expense items).
 
1281   static function makeConcatExpensesPart($options) {
 
1282     $group_by1 = $options['group_by1'];
 
1283     $group_by2 = $options['group_by2'];
 
1284     $group_by3 = $options['group_by3'];
 
1286     switch ($group_by1) {
 
1288         $what_to_concat .= ", ' - ', ei.date";
 
1291         $what_to_concat .= ", ' - ', u.name";
 
1292         $fields_part .= ', u.name as user';
 
1295         $what_to_concat .= ", ' - ', coalesce(c.name, 'Null')";
 
1296         $fields_part .= ', c.name as client';
 
1299         $what_to_concat .= ", ' - ', coalesce(p.name, 'Null')";
 
1300         $fields_part .= ', p.name as project';
 
1304         $what_to_concat .= ", ' - ', 'Null'";
 
1305         $fields_part .= ', null as task';
 
1309         $what_to_concat .= ", ' - ', 'Null'";
 
1310         $fields_part .= ', null as cf_1';
 
1313     switch ($group_by2) {
 
1315         $what_to_concat .= ", ' - ', ei.date";
 
1318         $what_to_concat .= ", ' - ', u.name";
 
1319         $fields_part .= ', u.name as user';
 
1322         $what_to_concat .= ", ' - ', coalesce(c.name, 'Null')";
 
1323         $fields_part .= ', c.name as client';
 
1326         $what_to_concat .= ", ' - ', coalesce(p.name, 'Null')";
 
1327         $fields_part .= ', p.name as project';
 
1331         $what_to_concat .= ", ' - ', 'Null'";
 
1332         $fields_part .= ', null as task';
 
1336         $what_to_concat .= ", ' - ', 'Null'";
 
1337         $fields_part .= ', null as cf_1';
 
1340     switch ($group_by3) {
 
1342         $what_to_concat .= ", ' - ', ei.date";
 
1345         $what_to_concat .= ", ' - ', u.name";
 
1346         $fields_part .= ', u.name as user';
 
1349         $what_to_concat .= ", ' - ', coalesce(c.name, 'Null')";
 
1350         $fields_part .= ', c.name as client';
 
1353         $what_to_concat .= ", ' - ', coalesce(p.name, 'Null')";
 
1354         $fields_part .= ', p.name as project';
 
1358         $what_to_concat .= ", ' - ', 'Null'";
 
1359         $fields_part .= ', null as task';
 
1363         $what_to_concat .= ", ' - ', 'Null'";
 
1364         $fields_part .= ', null as cf_1';
 
1367     // Remove garbage from the beginning.
 
1368     if ($what_to_concat)
 
1369         $what_to_concat = substr($what_to_concat, 8);
 
1370     $concat_part = "concat($what_to_concat) as group_field";
 
1371     return "$concat_part $fields_part";
 
1374   // makeCombinedSelectPart builds a list of fields for a combined select on a union for getSubtotals.
 
1375   // This is used when we include expenses.
 
1376   static function makeCombinedSelectPart($options) {
 
1377     $group_by1 = $options['group_by1'];
 
1378     $group_by2 = $options['group_by2'];
 
1379     $group_by3 = $options['group_by3'];
 
1381     $fields = "group_field";
 
1383     switch ($group_by1) {
 
1385         $fields .= ', user';
 
1388         $fields_part .= ', client';
 
1391         $fields .= ', project';
 
1395         $fields .= ', task';
 
1399         $fields .= ', cf_1';
 
1402     switch ($group_by2) {
 
1404         $fields .= ', user';
 
1407         $fields_part .= ', client';
 
1410         $fields .= ', project';
 
1414         $fields .= ', task';
 
1418         $fields .= ', cf_1';
 
1421     switch ($group_by3) {
 
1423         $fields .= ', user';
 
1426         $fields_part .= ', client';
 
1429         $fields .= ', project';
 
1433         $fields .= ', task';
 
1437         $fields .= ', cf_1';
 
1443   // makeJoinPart builds a left join part for getSubtotals query (for time items).
 
1444   static function makeJoinPart($options) {
 
1447     $trackingMode = $user->getTrackingMode();
 
1448     if (ttReportHelper::groupingBy('user', $options) || MODE_TIME == $trackingMode) {
 
1449       $join .= ' left join tt_users u on (l.user_id = u.id)';
 
1451     if (ttReportHelper::groupingBy('client', $options)) {
 
1452       $join .= ' left join tt_clients c on (l.client_id = c.id)';
 
1454     if (ttReportHelper::groupingBy('project', $options)) {
 
1455       $join .= ' left join tt_projects p on (l.project_id = p.id)';
 
1457     if (ttReportHelper::groupingBy('task', $options)) {
 
1458       $join .= ' left join tt_tasks t on (l.task_id = t.id)';
 
1460     if (ttReportHelper::groupingBy('cf_1', $options)) {
 
1461       $custom_fields = new CustomFields();
 
1462       if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_TEXT)
 
1463         $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)';
 
1464       elseif ($custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN)
 
1465         $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)';
 
1467     if ($options['show_cost'] && $trackingMode != MODE_TIME) {
 
1468       $join .= ' left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id)';
 
1473   // makeWorkUnitPart builds an sql part for work units for time items.
 
1474   static function makeWorkUnitPart($options) {
 
1477     $workUnits = $options['show_work_units'];
 
1479       $unitTotalsOnly = $user->getConfigOption('unit_totals_only');
 
1480       $firstUnitThreshold = $user->getConfigInt('1st_unit_threshold', 0);
 
1481       $minutesInUnit = $user->getConfigInt('minutes_in_unit', 15);
 
1482       if ($unitTotalsOnly)
 
1483         $work_unit_part = ", if (sum(l.billable * time_to_sec(l.duration)/60) < $firstUnitThreshold, 0, ceil(sum(l.billable * time_to_sec(l.duration)/60/$minutesInUnit))) as units";
 
1485         $work_unit_part = ", sum(if(l.billable = 0 or time_to_sec(l.duration)/60 < $firstUnitThreshold, 0, ceil(time_to_sec(l.duration)/60/$minutesInUnit))) as units";
 
1487     return $work_unit_part;
 
1490   // makeCostPart builds a cost part for time items.
 
1491   static function makeCostPart($options) {
 
1494     if ($options['show_cost']) {
 
1495       if (MODE_TIME == $user->getTrackingMode())
 
1496         $cost_part = ", sum(cast(l.billable * coalesce(u.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10, 2))) as cost";
 
1498         $cost_part .= ", sum(cast(l.billable * coalesce(upb.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10,2))) as cost";
 
1503   // makeJoinExpensesPart builds a left join part for getSubtotals query for expense items.
 
1504   static function makeJoinExpensesPart($options) {
 
1505     if (ttReportHelper::groupingBy('user', $options)) {
 
1506       $join .= ' left join tt_users u on (ei.user_id = u.id)';
 
1508     if (ttReportHelper::groupingBy('client', $options)) {
 
1509       $join .= ' left join tt_clients c on (ei.client_id = c.id)';
 
1511     if (ttReportHelper::groupingBy('project', $options)) {
 
1512       $join .= ' left join tt_projects p on (ei.project_id = p.id)';
 
1517   // grouping determines if we are grouping the report by either group_by1,
 
1518   // group_by2, or group_by3 values passed in $options.
 
1519   static function grouping($options) {
 
1520     $grouping = ($options['group_by1'] != null && $options['group_by1'] != 'no_grouping') ||
 
1521       ($options['group_by2'] != null && $options['group_by2'] != 'no_grouping') ||
 
1522       ($options['group_by3'] != null && $options['group_by3'] != 'no_grouping');
 
1526   // groupingBy determines if we are grouping a report by a value of $what
 
1527   // ('date', 'user', 'project', etc.) by checking group_by1, group_by2,
 
1528   // and group_by3 values passed in $options.
 
1529   static function groupingBy($what, $options) {
 
1530     $grouping = ($options['group_by1'] == $what) || ($options['group_by2'] == $what) || ($options['group_by3'] == $what);
 
1534   // makeGroupByHeader builds a column header for a totals-only report using group_by1,
 
1535   // group_by2, and group_by3 values passed in $options.
 
1536   static function makeGroupByHeader($options) {
 
1538     global $custom_fields;
 
1540     $no_grouping = ($options['group_by1'] == null || $options['group_by1'] == 'no_grouping') &&
 
1541       ($options['group_by2'] == null || $options['group_by2'] == 'no_grouping') &&
 
1542       ($options['group_by3'] == null || $options['group_by3'] == 'no_grouping');
 
1543     if ($no_grouping) return null;
 
1545     if ($options['group_by1'] != null && $options['group_by1'] != 'no_grouping') {
 
1546       // We have group_by1.
 
1547       $group_by1 = $options['group_by1'];
 
1548       if ('cf_1' == $group_by1)
 
1549         $group_by_header .= ' - '.$custom_fields->fields[0]['label'];
 
1551         $key = 'label.'.$group_by1;
 
1552         $group_by_header .= ' - '.$i18n->get($key);
 
1555     if ($options['group_by2'] != null && $options['group_by2'] != 'no_grouping') {
 
1556       // We have group_by2.
 
1557       $group_by2 = $options['group_by2'];
 
1558       if ('cf_1' == $group_by2)
 
1559         $group_by_header .= ' - '.$custom_fields->fields[0]['label'];
 
1561         $key = 'label.'.$group_by2;
 
1562         $group_by_header .= ' - '.$i18n->get($key);
 
1565     if ($options['group_by3'] != null && $options['group_by3'] != 'no_grouping') {
 
1566       // We have group_by3.
 
1567       $group_by3 = $options['group_by3'];
 
1568       if ('cf_1' == $group_by3)
 
1569         $group_by_header .= ' - '.$custom_fields->fields[0]['label'];
 
1571         $key = 'label.'.$group_by3;
 
1572         $group_by_header .= ' - '.$i18n->get($key);
 
1575     $group_by_header = ltrim($group_by_header, ' -');
 
1576     return $group_by_header;
 
1579   // makeGroupByXmlTag creates an xml tag for a totals only report using group_by1,
 
1580   // group_by2, and group_by3 values passed in $options.
 
1581   static function makeGroupByXmlTag($options) {
 
1582     if ($options['group_by1'] != null && $options['group_by1'] != 'no_grouping') {
 
1583       // We have group_by1.
 
1584       $tag .= '_'.$options['group_by1'];
 
1586     if ($options['group_by2'] != null && $options['group_by2'] != 'no_grouping') {
 
1587       // We have group_by2.
 
1588       $tag .= '_'.$options['group_by2'];
 
1590     if ($options['group_by3'] != null && $options['group_by3'] != 'no_grouping') {
 
1591       // We have group_by3.
 
1592       $tag .= '_'.$options['group_by3'];
 
1594     $tag = ltrim($tag, '_');
 
1598   // makeGroupByLabel builds a label for one row in a "Totals only" report of grouped by items.
 
1599   // It does one thing: if we are grouping by date, the date format is converted for user.
 
1600   static function makeGroupByLabel($key, $options) {
 
1601     if (!ttReportHelper::groupingBy('date', $options))
 
1602       return $key; // No need to format.
 
1605     if ($user->getDateFormat() == DB_DATEFORMAT)
 
1606       return $key; // No need to format.
 
1609     if (preg_match('/\d\d\d\d-\d\d-\d\d/', $key, $matches)) {
 
1610       // Replace the first found match of a date in DB_DATEFORMAT.
 
1611       // This is not entirely clean but better than nothing for a label in a row.
 
1612       $userDate = ttDateToUserFormat($matches[0]);
 
1613       $label = str_replace($matches[0], $userDate, $key);