Security fix for invoice view.
[timetracker.git] / WEB-INF / lib / ttInvoiceHelper.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
32 // Class ttInvoiceHelper is used for help with invoices.
33 class ttInvoiceHelper {
34
35   // insert - inserts an invoice in database.
36   static function insert($fields)
37   {
38     $mdb2 = getConnection();
39
40     $team_id = (int) $fields['team_id'];
41     $name = $fields['name'];
42     if (!$name) return false;
43
44     $client_id = (int) $fields['client_id'];
45     $date = $fields['date'];
46     if (array_key_exists('status', $fields)) { // Key exists and may be NULL during migration of data.
47       $status_f = ', status';
48       $status_v = ', '.$mdb2->quote($fields['status']);
49     }
50
51     // Insert a new invoice record.
52     $sql = "insert into tt_invoices (team_id, name, date, client_id $status_f)
53       values($team_id, ".$mdb2->quote($name).", ".$mdb2->quote($date).", $client_id $status_v)"; 
54     $affected = $mdb2->exec($sql);
55
56     if (is_a($affected, 'PEAR_Error')) return false;
57
58     $last_id = 0;
59     $sql = "select last_insert_id() as last_insert_id";
60     $res = $mdb2->query($sql);
61     $val = $res->fetchRow();
62     $last_id = $val['last_insert_id'];
63
64     return $last_id;
65   }
66
67   // getInvoice - obtains invoice data from the database.
68   static function getInvoice($invoice_id) {
69     global $user;
70     $mdb2 = getConnection();
71
72     if ($user->isClient()) $client_part = " and client_id = $user->client_id";
73
74     $sql = "select * from tt_invoices where id = $invoice_id and team_id = $user->team_id $client_part and status = 1";
75     $res = $mdb2->query($sql);
76     if (!is_a($res, 'PEAR_Error')) {
77       if ($val = $res->fetchRow())
78         return $val;
79     }
80     return false;
81   }
82
83   // The getInvoiceByName looks up an invoice by name.
84   static function getInvoiceByName($invoice_name) {
85
86     $mdb2 = getConnection();
87     global $user;
88
89     $sql = "select id from tt_invoices where team_id = $user->team_id and name = ".$mdb2->quote($invoice_name)." and status = 1";
90     $res = $mdb2->query($sql);
91     if (!is_a($res, 'PEAR_Error')) {
92       $val = $res->fetchRow();
93       if ($val['id']) {
94         return $val;
95       }
96     }
97     return false;
98   }
99
100   // The isPaid determines if an invoice is paid by looking at the paid status of its items.
101   // If any non-paid item is found, the entire invoice is considered not paid.
102   // Therefore, the paid status of the invoice is a calculated value.
103   // This is because we maintain the paid status on individual item level.
104   static function isPaid($invoice_id) {
105
106     $mdb2 = getConnection();
107     global $user;
108
109     $sql = "select count(*) as count from tt_log where invoice_id = $invoice_id and status = 1 and paid < 1";
110     $res = $mdb2->query($sql);
111     if (!is_a($res, 'PEAR_Error')) {
112       $val = $res->fetchRow();
113       if ($val['count'] > 0)
114         return false; // A non-paid time item exists.
115     }
116     $sql = "select count(*) as count from tt_expense_items where invoice_id = $invoice_id and status = 1 and paid < 1";
117     $res = $mdb2->query($sql);
118     if (!is_a($res, 'PEAR_Error')) {
119       $val = $res->fetchRow();
120       if ($val['count'] > 0)
121         return false; // A non-paid expense item exists.
122       else
123         return true; // All time and expense items in invoice are paid.
124     }
125     return false;
126   }
127
128   // markPaid marks invoice items as paid.
129   static function markPaid($invoice_id, $mark_paid = true) {
130
131     global $user;
132     $mdb2 = getConnection();
133
134     $paid_status = $mark_paid ? 1 : 0;
135     $sql = "update tt_log set paid = $paid_status where invoice_id = $invoice_id and status = 1";
136     $affected = $mdb2->exec($sql);
137     if (is_a($affected, 'PEAR_Error')) return false;
138
139     $sql = "update tt_expense_items set paid = $paid_status where invoice_id = $invoice_id and status = 1";
140     $affected = $mdb2->exec($sql);
141     if (is_a($affected, 'PEAR_Error')) return false;
142
143     return true;
144   }
145
146   // The getInvoiceItems retrieves tt_log items associated with the invoice. 
147   static function getInvoiceItems($invoice_id) {
148     global $user;
149     $mdb2 = getConnection();
150
151     // At this time only detailed invoice is supported.
152     // It is anticipated to support "totals only" option later on.
153
154     // Our query is different depending on tracking mode.
155     if (MODE_TIME == $user->tracking_mode) {
156       // In "time only" tracking mode there is a single user rate.
157       $sql = "select l.date as date, 1 as type, u.name as user_name, p.name as project_name,
158       t.name as task_name, l.comment as note,
159       time_format(l.duration, '%k:%i') as duration,
160       cast(l.billable * u.rate * time_to_sec(l.duration)/3600 as decimal(10, 2)) as cost,
161       l.paid as paid from tt_log l
162       inner join tt_users u on (l.user_id = u.id)
163       left join tt_projects p on (p.id = l.project_id)
164       left join tt_tasks t on (t.id = l.task_id)
165       where l.status = 1 and l.billable = 1 and l.invoice_id = $invoice_id order by l.date, u.name";
166     } else {
167       $sql = "select l.date as date, 1 as type, u.name as user_name, p.name as project_name,
168         t.name as task_name, l.comment as note,
169         time_format(l.duration, '%k:%i') as duration,
170         cast(l.billable * coalesce(upb.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10, 2)) as cost,
171         l.paid as paid from tt_log l
172         inner join tt_users u on (l.user_id = u.id)
173         left join tt_projects p on (p.id = l.project_id)
174         left join tt_tasks t on (t.id = l.task_id)
175         left join tt_user_project_binds upb on (upb.user_id = l.user_id and upb.project_id = l.project_id)
176         where l.status = 1 and l.billable = 1 and l.invoice_id = $invoice_id order by l.date, u.name";
177     }
178
179     // If we have expenses, we need to do a union with a separate query for expense items from tt_expense_items table.
180     if ($user->isPluginEnabled('ex')) {
181       $sql_for_expense_items = "select ei.date as date, 2 as type, u.name as user_name, p.name as project_name,
182         null as task_name, ei.name as note,
183         null as duration, ei.cost as cost,
184         ei.paid as paid from tt_expense_items ei
185         inner join tt_users u on (ei.user_id = u.id)
186         left join tt_projects p on (p.id = ei.project_id)
187         where ei.invoice_id = $invoice_id and ei.status = 1";
188
189       // Construct a union.
190       $sql = "($sql) union all ($sql_for_expense_items)";
191
192       $sort_part = " order by date, user_name, type";
193       $sql .= $sort_part;
194     }
195
196     $res = $mdb2->query($sql);
197     if (!is_a($res, 'PEAR_Error')) {
198       $dt = new DateAndTime(DB_DATEFORMAT);
199       while ($val = $res->fetchRow()) {
200         $dt->parseVal($val['date']);
201         $val['date'] = $dt->toString($user->date_format);
202         $result[] = $val;
203       }
204     }
205     return $result;
206   }
207
208   // delete - deletes the invoice data from the database.
209   static function delete($invoice_id, $delete_invoice_items) {
210     global $user;
211     $mdb2 = getConnection();
212
213     // Handle custom field log records.
214     if ($delete_invoice_items) {
215       $sql = "update tt_custom_field_log set status = NULL where log_id in (select id from tt_log where invoice_id = $invoice_id and status = 1)";
216       $affected = $mdb2->exec($sql);
217       if (is_a($affected, 'PEAR_Error')) return false;
218     }
219
220     // Handle time records.
221     if ($delete_invoice_items)
222       $sql = "update tt_log set status = NULL where invoice_id = $invoice_id";
223     else
224       $sql = "update tt_log set invoice_id = NULL where invoice_id = $invoice_id";
225     $affected = $mdb2->exec($sql);
226     if (is_a($affected, 'PEAR_Error')) return false;
227
228     // Handle expense items.
229     if ($delete_invoice_items)
230       $sql = "update tt_expense_items set status = NULL where invoice_id = $invoice_id";
231     else
232       $sql = "update tt_expense_items set invoice_id = NULL where invoice_id = $invoice_id";
233     $affected = $mdb2->exec($sql);
234     if (is_a($affected, 'PEAR_Error')) return false;
235
236     $sql = "update tt_invoices set status = NULL where id = $invoice_id and team_id = $user->team_id";
237     $affected = $mdb2->exec($sql);
238     return (!is_a($affected, 'PEAR_Error'));
239   }
240
241   // The invoiceableItemsExist determines whether invoiceable records exist in the specified period.
242   static function invoiceableItemsExist($fields) {
243
244     $mdb2 = getConnection();
245     global $user;
246
247     $client_id = (int) $fields['client_id'];
248
249     $start_date = new DateAndTime($user->date_format, $fields['start_date']);
250     $start = $start_date->toString(DB_DATEFORMAT);
251
252     $end_date = new DateAndTime($user->date_format, $fields['end_date']);
253     $end = $end_date->toString(DB_DATEFORMAT);
254
255     if (isset($fields['project_id'])) $project_id = (int) $fields['project_id'];
256
257     // Our query is different depending on tracking mode.
258     if (MODE_TIME == $user->tracking_mode) {
259       // In "time only" tracking mode there is a single user rate.
260       $sql = "select count(*) as num from tt_log l, tt_users u
261         where l.status = 1 and l.client_id = $client_id and l.invoice_id is NULL
262         and l.date >= ".$mdb2->quote($start)." and l.date <= ".$mdb2->quote($end)."
263         and l.user_id = u.id
264         and l.billable = 1"; // l.billable * u.rate * time_to_sec(l.duration)/3600 > 0 // See explanation below.
265     } else {
266       // sql part for project id.
267       if ($project_id) $project_part = " and l.project_id = $project_id";
268
269       // When we have projects, rates are defined for each project in tt_user_project_binds table.
270       $sql = "select count(*) as num from tt_log l, tt_user_project_binds upb
271         where l.status = 1 and l.client_id = $client_id $project_part and l.invoice_id is NULL
272         and l.date >= ".$mdb2->quote($start)." and l.date <= ".$mdb2->quote($end)."
273         and upb.user_id = l.user_id and upb.project_id = l.project_id
274         and l.billable = 1"; // l.billable * upb.rate * time_to_sec(l.duration)/3600 > 0
275         // Users with a lot of clients and projects (Jaro) may forget to set user rates properly.
276         // Specifically, user rate may be set to 0 on a project, by mistake. This leads to error.no_invoiceable_items
277         // and increased support cost. Commenting out allows us to include 0 cost items in invoices so that
278         // the problem becomes obvious.
279
280         // TODO: If the above turns out useful, rework the query to simplify it by removing left join.
281     }
282     $res = $mdb2->query($sql);
283     if (!is_a($res, 'PEAR_Error')) {
284       $val = $res->fetchRow();
285       if ($val['num']) {
286         return true;
287       }
288     }
289
290     // sql part for project id.
291     if ($project_id) $project_part = " and ei.project_id = $project_id";
292
293     $sql = "select count(*) as num from tt_expense_items ei
294       where ei.client_id = $client_id $project_part and ei.invoice_id is NULL
295       and ei.date >= ".$mdb2->quote($start)." and ei.date <= ".$mdb2->quote($end)."
296       and ei.cost <> 0 and ei.status = 1";
297     $res = $mdb2->query($sql);
298     if (!is_a($res, 'PEAR_Error')) {
299       $val = $res->fetchRow();
300       if ($val['num']) {
301         return true;
302       }
303     }
304
305     return false;
306   }
307
308   // createInvoice - marks items for invoice as belonging to it (with its reference number).
309   static function createInvoice($fields) {
310
311     $mdb2 = getConnection();
312     global $user;
313
314     $name = $fields['name'];
315     if (!$name) return false;
316
317     $client_id = (int) $fields['client_id'];
318
319     $invoice_date = new DateAndTime($user->date_format, $fields['date']);
320     $date = $invoice_date->toString(DB_DATEFORMAT);
321
322     $start_date = new DateAndTime($user->date_format, $fields['start_date']);
323     $start = $start_date->toString(DB_DATEFORMAT);
324
325     $end_date = new DateAndTime($user->date_format, $fields['end_date']);
326     $end = $end_date->toString(DB_DATEFORMAT);
327
328     if (isset($fields['project_id'])) $project_id = (int) $fields['project_id'];
329
330     // Create a new invoice record.
331     $sql = "insert into tt_invoices (team_id, name, date, client_id)
332       values($user->team_id, ".$mdb2->quote($name).", ".$mdb2->quote($date).", $client_id)";
333     $affected = $mdb2->exec($sql);
334     if (is_a($affected, 'PEAR_Error')) return false;
335
336     // Mark associated invoice items with invoice id.
337     $last_id = 0;
338     $sql = "select last_insert_id() as last_insert_id";
339     $res = $mdb2->query($sql);
340     $val = $res->fetchRow();
341     $last_id = $val['last_insert_id'];
342
343     // Our update sql is different depending on tracking mode.
344     if (MODE_TIME == $user->tracking_mode) {
345       // In "time only" tracking mode there is a single user rate.
346       $sql = "update tt_log l
347         left join tt_users u on (u.id = l.user_id)
348         set l.invoice_id = $last_id
349         where l.status = 1 and l.client_id = $client_id and l.invoice_id is NULL
350         and l.date >= ".$mdb2->quote($start)." and l.date <= ".$mdb2->quote($end)."
351         and l.billable = 1"; // l.billable * u.rate * time_to_sec(l.duration)/3600 > 0"; // See explanation below.
352     } else {
353        // sql part for project id.
354       if ($project_id) $project_part = " and l.project_id = $project_id";
355
356       // When we have projects, rates are defined for each project in tt_user_project_binds.
357       $sql = "update tt_log l
358         left join tt_user_project_binds upb on (upb.user_id = l.user_id and upb.project_id = l.project_id)
359         set l.invoice_id = $last_id
360         where l.status = 1 and l.client_id = $client_id $project_part and l.invoice_id is NULL
361         and l.date >= ".$mdb2->quote($start)." and l.date <= ".$mdb2->quote($end)."
362         and l.billable = 1"; //  l.billable * upb.rate * time_to_sec(l.duration)/3600 > 0";
363         // Users with a lot of clients and projects (Jaro) may forget to set user rates properly.
364         // Specifically, user rate may be set to 0 on a project, by mistake. This leads to error.no_invoiceable_items
365         // and increased support cost. Commenting out allows us to include 0 cost items in invoices so that
366         // the problem becomes obvious.
367
368         // TODO: If the above turns out useful, rework the query to simplify it by removing left join.
369     }
370     $affected = $mdb2->exec($sql);
371     if (is_a($affected, 'PEAR_Error'))
372       return false;
373
374     // sql part for project id.
375     if ($project_id) $project_part = " and project_id = $project_id";
376
377     $sql = "update tt_expense_items set invoice_id = $last_id where client_id = $client_id $project_part and invoice_id is NULL
378       and date >= ".$mdb2->quote($start)." and date <= ".$mdb2->quote($end)." and cost <> 0 and status = 1";
379     $affected = $mdb2->exec($sql);
380     return (!is_a($affected, 'PEAR_Error'));
381   }
382
383   // prepareInvoiceBody - prepares an email body for invoice.
384   static function prepareInvoiceBody($invoice_id, $comment)
385   {
386     global $user;
387     global $i18n;
388
389     $invoice = ttInvoiceHelper::getInvoice($invoice_id);
390     $client = ttClientHelper::getClient($invoice['client_id'], true);
391     $invoice_items = ttInvoiceHelper::getInvoiceItems($invoice_id);
392
393     $tax_percent = $client['tax'];
394
395     $subtotal = 0;
396     $tax = 0;
397     foreach($invoice_items as $item)
398       $subtotal += $item['cost'];
399     if ($tax_percent) {
400       $tax_expenses = $user->isPluginEnabled('et');
401       foreach($invoice_items as $item) {
402         if ($item['type'] == 2 && !$tax_expenses)
403           continue;
404         $tax += round($item['cost'] * $tax_percent / 100, 2);
405       }
406     }
407     $total = $subtotal + $tax;
408
409     $subtotal = htmlspecialchars($user->currency).' '.str_replace('.', $user->decimal_mark, sprintf('%8.2f', round($subtotal, 2)));
410     if ($tax) $tax = htmlspecialchars($user->currency).' '.str_replace('.', $user->decimal_mark, sprintf('%8.2f', round($tax, 2)));
411     $total = htmlspecialchars($user->currency).' '.str_replace('.', $user->decimal_mark, sprintf('%8.2f', round($total, 2)));
412
413     if ('.' != $user->decimal_mark) {
414       foreach ($invoice_items as &$item) {
415         $item['cost'] = str_replace('.', $user->decimal_mark, $item['cost']);
416       }
417       unset($item); // Unset the reference. If we don't, the foreach loop below modifies the array while printing.
418                     // See http://stackoverflow.com/questions/8220399/php-foreach-pass-by-reference-last-element-duplicating-bug
419     }
420
421     // Define some styles to use in email.
422     $style_title = 'text-align: center; font-size: 15pt; font-family: Arial, Helvetica, sans-serif;';
423     $style_tableHeader = 'font-weight: bold; background-color: #a6ccf7; text-align: left;';
424     $style_tableHeaderCentered = 'font-weight: bold; background-color: #a6ccf7; text-align: center;';
425
426     // Start creating email body.
427     $body = '<html>';
428     $body .= '<head><meta http-equiv="content-type" content="text/html; charset='.CHARSET.'"></head>';
429     $body .= '<body>';
430
431     // Output title.
432     $body .= '<p style="'.$style_title.'">'.$i18n->getKey('title.invoice').' '.htmlspecialchars($invoice['name']).'</p>';
433
434     // Output comment.
435     if($comment) $body .= '<p>'.htmlspecialchars($comment).'</p>';
436
437     // Output invoice info.
438     $body .= '<table>';
439     $body .= '<tr><td><b>'.$i18n->getKey('label.date').':</b> '.$invoice['date'].'</td></tr>';
440     $body .= '<tr><td><b>'.$i18n->getKey('label.client').':</b> '.htmlspecialchars($client['name']).'</td></tr>';
441     $body .= '<tr><td><b>'.$i18n->getKey('label.client_address').':</b> '.htmlspecialchars($client['address']).'</td></tr>';
442     $body .= '</table>';
443
444     $body .= '<p></p>';
445
446     // Output invoice items.
447     $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
448     $body .= '<tr>';
449     $body .= '<td style="'.$style_tableHeader.'">'.$i18n->getKey('label.date').'</td>';
450     $body .= '<td style="'.$style_tableHeader.'">'.$i18n->getKey('form.invoice.person').'</td>';
451     if (MODE_PROJECTS == $user->tracking_mode || MODE_PROJECTS_AND_TASKS == $user->tracking_mode)
452       $body .= '<td style="'.$style_tableHeader.'">'.$i18n->getKey('label.project').'</td>';
453     if (MODE_PROJECTS_AND_TASKS == $user->tracking_mode)
454       $body .= '<td style="'.$style_tableHeader.'">'.$i18n->getKey('label.task').'</td>';
455     $body .= '<td style="'.$style_tableHeader.'">'.$i18n->getKey('label.note').'</td>';
456     $body .= '<td style="'.$style_tableHeaderCentered.'" width="5%">'.$i18n->getKey('label.duration').'</td>';
457     $body .= '<td style="'.$style_tableHeaderCentered.'" width="5%">'.$i18n->getKey('label.cost').'</td>';
458     $body .= '</tr>';
459     foreach ($invoice_items as $item) {
460       $body .= '<tr>';
461       $body .= '<td>'.$item['date'].'</td>';
462       $body .= '<td>'.htmlspecialchars($item['user_name']).'</td>';
463       if (MODE_PROJECTS == $user->tracking_mode || MODE_PROJECTS_AND_TASKS == $user->tracking_mode)
464         $body .= '<td>'.htmlspecialchars($item['project_name']).'</td>';
465       if (MODE_PROJECTS_AND_TASKS == $user->tracking_mode)
466         $body .= '<td>'.htmlspecialchars($item['task_name']).'</td>';
467       $body .= '<td>'.htmlspecialchars($item['note']).'</td>';
468       $body .= '<td align="right">'.$item['duration'].'</td>';
469       $body .= '<td align="right">'.$item['cost'].'</td>';
470       $body .= '</tr>';
471     }
472     // Output summary.
473     $colspan = 4;
474     if (MODE_PROJECTS == $user->tracking_mode)
475       $colspan++;
476     elseif (MODE_PROJECTS_AND_TASKS == $user->tracking_mode)
477       $colspan += 2;
478     $body .= '<tr><td>&nbsp;</td></tr>';
479     if ($tax) {
480       $body .= '<tr><td colspan="'.$colspan.'" align="right"><b>'.$i18n->getKey('label.subtotal').':</b></td><td nowrap align="right">'.$subtotal.'</td></tr>';
481       $body .= '<tr><td colspan="'.$colspan.'" align="right"><b>'.$i18n->getKey('label.tax').':</b></td><td nowrap align="right">'.$tax.'</td></tr>';
482     }
483     $body .= '<tr><td colspan="'.$colspan.'" align="right"><b>'.$i18n->getKey('label.total').':</b></td><td nowrap align="right">'.$total.'</td></tr>';
484     $body .= '</table>';
485
486     // Output footer.
487     if (!defined('REPORT_FOOTER') || !(REPORT_FOOTER == false))
488       $body .= '<p style="text-align: center;">'.$i18n->getKey('form.mail.footer').'</p>';
489
490     // Finish creating email body.
491     $body .= '</body></html>';
492
493     return $body;
494   }
495 }