Added fav reports to new export-import.
[timetracker.git] / WEB-INF / lib / ttOrgImportHelper.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('ttUserHelper');
30 import('ttRoleHelper');
31 import('ttTaskHelper');
32 import('ttProjectHelper');
33 import('ttClientHelper');
34 import('ttInvoiceHelper');
35 import('ttCustomFieldHelper');
36 import('ttExpenseHelper');
37 import('ttFavReportHelper');
38
39 // ttOrgImportHelper - this class is a future replacement for ttImportHelper.
40 // Currently, it is work in progress.
41 // When done, it should handle import of complex groups consisting of other groups.
42 class ttOrgImportHelper {
43   var $errors               = null; // Errors go here. Set in constructor by reference.
44   var $conflicting_entities = null; // A comma-separated list of entity names we cannot import.
45   var $canImport      = true;    // False if we cannot import data due to a conflict such as login collision.
46   var $firstPass      = true;    // True during first pass through the file.
47   var $org_id         = null;    // Organization id (same as top group_id).
48   var $current_group_id        = null; // Current group id during parsing.
49   var $current_parent_group_id = null; // Current parent group id during parsing.
50                                        // Set when we create a new group.
51   var $top_role_id    = 0;       // Top role id.
52
53   // Entity maps for current group. They map XML ids with database ids.
54   var $currentGroupRoleMap    = array();
55   var $currentGroupTaskMap    = array();
56   var $currentGroupProjectMap = array();
57   var $currentGroupClientMap  = array();
58   var $currentGroupUserMap    = array();
59   var $currentGroupInvoiceMap = array();
60   var $currentGroupLogMap     = array();
61   var $currentGroupCustomFieldMap = array();
62   var $currentGroupCustomFieldOptionMap = array();
63
64   // Constructor.
65   function __construct(&$errors) {
66     $this->errors = &$errors;
67     $this->top_role_id = ttRoleHelper::getRoleByRank(512, 0);
68   }
69
70   // startElement - callback handler for opening tag of an XML element in the file.
71   function startElement($parser, $name, $attrs) {
72     global $i18n;
73
74     // First pass. We only check user logins for potential collisions with existing.
75     if ($this->firstPass) {
76       if ($name == 'USER' && $this->canImport) {
77         $login = $attrs['LOGIN'];
78         if ('' != $attrs['STATUS'] && ttUserHelper::getUserByLogin($login)) {
79           // We have a login collision. Append colliding login to a list of things we cannot import.
80           $this->conflicting_entities .= ($this->conflicting_entities ? ", $login" : $login);
81         }
82       }
83     }
84
85     // Second pass processing. We import data here, one tag at a time.
86     if (!$this->firstPass && $this->canImport && $this->errors->no()) {
87       $mdb2 = getConnection();
88
89       // We are in second pass and can import data.
90       if ($name == 'GROUP') {
91         // Create a new group.
92         $this->current_group_id = $this->createGroup(array(
93           'parent_id' => $this->current_parent_group_id,
94           'org_id' => $this->org_id,
95           'name' => $attrs['NAME'],
96           'currency' => $attrs['CURRENCY'],
97           'decimal_mark' => $attrs['DECIMAL_MARK'],
98           'lang' => $attrs['LANG'],
99           'date_format' => $attrs['DATE_FORMAT'],
100           'time_format' => $attrs['TIME_FORMAT'],
101           'week_start' => $attrs['WEEK_START'],
102           'tracking_mode' => $attrs['TRACKING_MODE'],
103           'project_required' => $attrs['PROJECT_REQUIRED'],
104           'task_required' => $attrs['TASK_REQUIRED'],
105           'record_type' => $attrs['RECORD_TYPE'],
106           'bcc_email' => $attrs['BCC_EMAIL'],
107           'allow_ip' => $attrs['ALLOW_IP'],
108           'password_complexity' => $attrs['PASSWORD_COMPLEXITY'],
109           'plugins' => $attrs['PLUGINS'],
110           'lock_spec' => $attrs['LOCK_SPEC'],
111           'workday_minutes' => $attrs['WORKDAY_MINUTES'],
112           'custom_logo' => $attrs['CUSTOM_LOGO'],
113           'config' => $attrs['CONFIG']));
114
115         // Special handling for top group.
116         if (!$this->org_id && $this->current_group_id) {
117           $this->org_id = $this->current_group_id;
118           $sql = "update tt_groups set org_id = $this->current_group_id where org_id is NULL and id = $this->current_group_id";
119           $affected = $mdb2->exec($sql);
120         }
121         // Set parent group to create subgroups with this group as parent at next entry here.
122         $this->current_parent_group_id = $this->current_group_id;
123       }
124
125       if ($name == 'ROLES') {
126         // If we get here, we have to recycle $currentGroupRoleMap.
127         unset($this->currentGroupRoleMap);
128         $this->currentGroupRoleMap = array();
129         // Role map is reconstructed after processing <role> elements in XML. See below.
130       }
131
132       if ($name == 'ROLE') {
133         // We get here when processing <role> tags for the current group.
134         $role_id = ttRoleHelper::insert(array(
135               'group_id' => $this->current_group_id,
136               'org_id' => $this->org_id,
137               'name' => $attrs['NAME'],
138               'description' => $attrs['DESCRIPTION'],
139               'rank' => $attrs['RANK'],
140               'rights' => $attrs['RIGHTS'],
141               'status' => $attrs['STATUS']));
142         if ($role_id) {
143           // Add a mapping.
144           $this->currentGroupRoleMap[$attrs['ID']] = $role_id;
145         } else $this->errors->add($i18n->get('error.db'));
146       }
147
148       if ($name == 'TASKS') {
149         // If we get here, we have to recycle $currentGroupTaskMap.
150         unset($this->currentGroupTaskMap);
151         $this->currentGroupTaskMap = array();
152         // Task map is reconstructed after processing <task> elements in XML. See below.
153       }
154
155       if ($name == 'TASK') {
156         // We get here when processing <task> tags for the current group.
157         $task_id = ttTaskHelper::insert(array(
158           'group_id' => $this->current_group_id,
159           'org_id' => $this->org_id,
160           'name' => $attrs['NAME'],
161           'description' => $attrs['DESCRIPTION'],
162           'status' => $attrs['STATUS']));
163         if ($task_id) {
164           // Add a mapping.
165           $this->currentGroupTaskMap[$attrs['ID']] = $task_id;
166         } else $this->errors->add($i18n->get('error.db'));
167       }
168
169       if ($name == 'PROJECTS') {
170         // If we get here, we have to recycle $currentGroupProjectMap.
171         unset($this->currentGroupProjectMap);
172         $this->currentGroupProjectMap = array();
173         // Project map is reconstructed after processing <project> elements in XML. See below.
174       }
175
176       if ($name == 'PROJECT') {
177         // We get here when processing <project> tags for the current group.
178
179         // Prepare a list of task ids.
180         $tasks = explode(',', $attrs['TASKS']);
181         foreach ($tasks as $id)
182           $mapped_tasks[] = $this->currentGroupTaskMap[$id];
183
184         $project_id = ttProjectHelper::insert(array(
185           'group_id' => $this->current_group_id,
186           'org_id' => $this->org_id,
187           'name' => $attrs['NAME'],
188           'description' => $attrs['DESCRIPTION'],
189           'tasks' => $mapped_tasks,
190           'status' => $attrs['STATUS']));
191         if ($project_id) {
192           // Add a mapping.
193           $this->currentGroupProjectMap[$attrs['ID']] = $project_id;
194         } else $this->errors->add($i18n->get('error.db'));
195       }
196
197       if ($name == 'CLIENTS') {
198         // If we get here, we have to recycle $currentGroupClientMap.
199         unset($this->currentGroupClientMap);
200         $this->currentGroupClientMap = array();
201         // Client map is reconstructed after processing <client> elements in XML. See below.
202       }
203
204       if ($name == 'CLIENT') {
205         // We get here when processing <client> tags for the current group.
206
207         // Prepare a list of project ids.
208         $projects = explode(',', $attrs['PROJECTS']);
209         foreach ($projects as $id)
210           $mapped_projects[] = $this->currentGroupProjectMap[$id];
211
212         $client_id = ttClientHelper::insert(array(
213           'group_id' => $this->current_group_id,
214           'org_id' => $this->org_id,
215           'name' => $attrs['NAME'],
216           'address' => $attrs['ADDRESS'],
217           'tax' => $attrs['TAX'],
218           'projects' => $mapped_projects,
219           'status' => $attrs['STATUS']));
220         if ($client_id) {
221           // Add a mapping.
222           $this->currentGroupClientMap[$attrs['ID']] = $client_id;
223         } else $this->errors->add($i18n->get('error.db'));
224       }
225
226       if ($name == 'USERS') {
227         // If we get here, we have to recycle $currentGroupUserMap.
228         unset($this->currentGroupUserMap);
229         $this->currentGroupUserMap = array();
230         // User map is reconstructed after processing <user> elements in XML. See below.
231       }
232
233       if ($name == 'USER') {
234         // We get here when processing <user> tags for the current group.
235
236         $role_id = $attrs['ROLE_ID'] === '0' ? $this->top_role_id :  $this->currentGroupRoleMap[$attrs['ROLE_ID']]; // 0 (not null) means top manager role.
237
238         $user_id = ttUserHelper::insert(array(
239           'group_id' => $this->current_group_id,
240           'org_id' => $this->org_id,
241           'role_id' => $role_id,
242           'client_id' => $this->currentGroupClientMap[$attrs['CLIENT_ID']],
243           'name' => $attrs['NAME'],
244           'login' => $attrs['LOGIN'],
245           'password' => $attrs['PASSWORD'],
246           'rate' => $attrs['RATE'],
247           'email' => $attrs['EMAIL'],
248           'status' => $attrs['STATUS']), false);
249         if ($user_id) {
250           // Add a mapping.
251           $this->currentGroupUserMap[$attrs['ID']] = $user_id;
252         } else $this->errors->add($i18n->get('error.db'));
253       }
254
255       if ($name == 'USER_PROJECT_BIND') {
256         if (!ttUserHelper::insertBind(array(
257           'user_id' => $this->currentGroupUserMap[$attrs['USER_ID']],
258           'project_id' => $this->currentGroupProjectMap[$attrs['PROJECT_ID']],
259           'group_id' => $this->current_group_id,
260           'org_id' => $this->org_id,
261           'rate' => $attrs['RATE'],
262           'status' => $attrs['STATUS']))) {
263           $this->errors->add($i18n->get('error.db'));
264         }
265       }
266
267       if ($name == 'INVOICES') {
268         // If we get here, we have to recycle $currentGroupInvoiceMap.
269         unset($this->currentGroupInvoiceMap);
270         $this->currentGroupInvoiceMap = array();
271         // Invoice map is reconstructed after processing <invoice> elements in XML. See below.
272       }
273
274       if ($name == 'INVOICE') {
275         // We get here when processing <invoice> tags for the current group.
276         $invoice_id = ttInvoiceHelper::insert(array(
277           'group_id' => $this->current_group_id,
278           'org_id' => $this->org_id,
279           'name' => $attrs['NAME'],
280           'date' => $attrs['DATE'],
281           'client_id' => $this->currentGroupClientMap[$attrs['CLIENT_ID']],
282           'status' => $attrs['STATUS']));
283         if ($invoice_id) {
284           // Add a mapping.
285           $this->currentGroupInvoiceMap[$attrs['ID']] = $invoice_id;
286         } else $this->errors->add($i18n->get('error.db'));
287       }
288
289       if ($name == 'LOG') {
290         // If we get here, we have to recycle $currentGroupLogMap.
291         unset($this->currentGroupLogMap);
292         $this->currentGroupLogMap = array();
293         // Log map is reconstructed after processing <log_item> elements in XML. See below.
294       }
295
296       if ($name == 'LOG_ITEM') {
297         // We get here when processing <log_item> tags for the current group.
298         $log_item_id = ttTimeHelper::insert(array(
299           'user_id' => $this->currentGroupUserMap[$attrs['USER_ID']],
300           'group_id' => $this->current_group_id,
301           'org_id' => $this->org_id,
302           'date' => $attrs['DATE'],
303           'start' => $attrs['START'],
304           'finish' => $attrs['FINISH'],
305           'duration' => $attrs['DURATION'],
306           'client' => $this->currentGroupClientMap[$attrs['CLIENT_ID']],
307           'project' => $this->currentGroupProjectMap[$attrs['PROJECT_ID']],
308           'task' => $this->currentGroupTaskMap[$attrs['TASK_ID']],
309           'invoice' => $this->currentGroupInvoiceMap[$attrs['INVOICE_ID']],
310           'note' => (isset($attrs['COMMENT']) ? $attrs['COMMENT'] : ''),
311           'billable' => $attrs['BILLABLE'],
312           'paid' => $attrs['PAID'],
313           'status' => $attrs['STATUS']));
314         if ($log_item_id) {
315           // Add a mapping.
316           $this->currentGroupLogMap[$attrs['ID']] = $log_item_id;
317         } else $this->errors->add($i18n->get('error.db'));
318       }
319
320       if ($name == 'CUSTOM_FIELDS') {
321         // If we get here, we have to recycle $currentGroupCustomFieldMap.
322         unset($this->currentGroupCustomFieldMap);
323         $this->currentGroupCustomFieldMap = array();
324         // Custom field map is reconstructed after processing <custom_field> elements in XML. See below.
325       }
326
327       if ($name == 'CUSTOM_FIELD') {
328         // We get here when processing <custom_field> tags for the current group.
329         $custom_field_id = ttCustomFieldHelper::insertField(array(
330           'group_id' => $this->current_group_id,
331           // 'org_id' => $this->org_id, TODO: add this when org_id field is added to the table.
332           'type' => $attrs['TYPE'],
333           'label' => $attrs['LABEL'],
334           'required' => $attrs['REQUIRED'],
335           'status' => $attrs['STATUS']));
336         if ($custom_field_id) {
337           // Add a mapping.
338           $this->currentGroupCustomFieldMap[$attrs['ID']] = $custom_field_id;
339         } else $this->errors->add($i18n->get('error.db'));
340       }
341
342       if ($name == 'CUSTOM_FIELD_OPTIONS') {
343         // If we get here, we have to recycle $currentGroupCustomFieldOptionMap.
344         unset($this->currentGroupCustomFieldOptionMap);
345         $this->currentGroupCustomFieldOptionMap = array();
346         // Custom field option map is reconstructed after processing <custom_field_option> elements in XML. See below.
347       }
348
349       if ($name == 'CUSTOM_FIELD_OPTION') {
350         // We get here when processing <custom_field_option> tags for the current group.
351         $custom_field_option_id = ttCustomFieldHelper::insertOption(array(
352           // 'group_id' => $this->current_group_id, TODO: add this when group_id field is added to the table.
353           // 'org_id' => $this->org_id, TODO: add this when org_id field is added to the table.
354           'field_id' => $this->currentGroupCustomFieldMap[$attrs['FIELD_ID']],
355           'value' => $attrs['VALUE']));
356         if ($custom_field_option_id) {
357           // Add a mapping.
358           $this->currentGroupCustomFieldOptionMap[$attrs['ID']] = $custom_field_option_id;
359         } else $this->errors->add($i18n->get('error.db'));
360       }
361
362       if ($name == 'CUSTOM_FIELD_LOG_ENTRY') {
363         // We get here when processing <custom_field_log_entry> tags for the current group.
364         if (!ttCustomFieldHelper::insertLogEntry(array(
365           // 'group_id' => $this->current_group_id, TODO: add this when group_id field is added to the table.
366           // 'org_id' => $this->org_id, TODO: add this when org_id field is added to the table.
367           'log_id' => $this->currentGroupLogMap[$attrs['LOG_ID']],
368           'field_id' => $this->currentGroupCustomFieldMap[$attrs['FIELD_ID']],
369           'option_id' => $this->currentGroupCustomFieldOptionMap[$attrs['OPTION_ID']],
370           'value' => $attrs['VALUE'],
371           'status' => $attrs['STATUS']))) {
372           $this->errors->add($i18n->get('error.db'));
373         }
374       }
375
376       if ($name == 'EXPENSE_ITEM') {
377         // We get here when processing <expense_item> tags for the current group.
378         $expense_item_id = ttExpenseHelper::insert(array(
379           'date' => $attrs['DATE'],
380           'user_id' => $this->currentGroupUserMap[$attrs['USER_ID']],
381           'group_id' => $this->current_group_id,
382           // 'org_id' => $this->org_id, TODO: add this when org_id field is added to the table.
383           'client_id' => $this->currentGroupClientMap[$attrs['CLIENT_ID']],
384           'project_id' => $this->currentGroupProjectMap[$attrs['PROJECT_ID']],
385           'name' => $attrs['NAME'],
386           'cost' => $attrs['COST'],
387           'invoice_id' => $this->currentGroupInvoiceMap[$attrs['INVOICE_ID']],
388           'paid' => $attrs['PAID'],
389           'status' => $attrs['STATUS']));
390         if (!$expense_item_id) $this->errors->add($i18n->get('error.db'));
391       }
392
393       if ($name == 'MONTHLY_QUOTA') {
394         if (!$this->insertMonthlyQuota($this->current_group_id,
395           // 'org_id' => $this->org_id, TODO: add this when org_id field is added to the table.
396           $attrs['YEAR'],
397           $attrs['MONTH'],
398           $attrs['MINUTES'])) {
399           $this->errors->add($i18n->get('error.db'));
400         }
401       }
402
403       if ($name == 'FAV_REPORT') {
404         $user_list = '';
405         if (strlen($attrs['USERS']) > 0) {
406           $arr = explode(',', $attrs['USERS']);
407           foreach ($arr as $v)
408             $user_list .= (strlen($user_list) == 0 ? '' : ',').$this->currentGroupUserMap[$v];
409         }
410         $fav_report_id = ttFavReportHelper::insertReport(array(
411           'name' => $attrs['NAME'],
412           'user_id' => $this->currentGroupUserMap[$attrs['USER_ID']],
413           'client' => $this->currentGroupClientMap[$attrs['CLIENT_ID']],
414           'option' => $this->currentGroupCustomFieldOptionMap[$attrs['CF_1_OPTION_ID']],
415           'project' => $this->currentGroupProjectMap[$attrs['PROJECT_ID']],
416           'task' => $this->currentGroupTaskMap[$attrs['TASK_ID']],
417           'billable' => $attrs['BILLABLE'],
418           'users' => $user_list,
419           'period' => $attrs['PERIOD'],
420           'from' => $attrs['PERIOD_START'],
421           'to' => $attrs['PERIOD_END'],
422           'chclient' => (int) $attrs['SHOW_CLIENT'],
423           'chinvoice' => (int) $attrs['SHOW_INVOICE'],
424           'chpaid' => (int) $attrs['SHOW_PAID'],
425           'chip' => (int) $attrs['SHOW_IP'],
426           'chproject' => (int) $attrs['SHOW_PROJECT'],
427           'chstart' => (int) $attrs['SHOW_START'],
428           'chduration' => (int) $attrs['SHOW_DURATION'],
429           'chcost' => (int) $attrs['SHOW_COST'],
430           'chtask' => (int) $attrs['SHOW_TASK'],
431           'chfinish' => (int) $attrs['SHOW_END'],
432           'chnote' => (int) $attrs['SHOW_NOTE'],
433           'chcf_1' => (int) $attrs['SHOW_CUSTOM_FIELD_1'],
434           'chunits' => (int) $attrs['SHOW_WORK_UNITS'],
435           'group_by1' => $attrs['GROUP_BY1'],
436           'group_by2' => $attrs['GROUP_BY2'],
437           'group_by3' => $attrs['GROUP_BY3'],
438           'chtotalsonly' => (int) $attrs['SHOW_TOTALS_ONLY']));
439          if (!$fav_report_id) $this->errors->add($i18n->get('error.db'));
440       }
441     }
442   }
443
444   // importXml - uncompresses the file, reads and parses its content. During parsing,
445   // startElement, endElement, and dataElement functions are called as many times as necessary.
446   // Actual import occurs in the endElement handler.
447   function importXml() {
448     global $i18n;
449
450     // Do we have a compressed file?
451     $compressed = false;
452     $file_ext = substr($_FILES['xmlfile']['name'], strrpos($_FILES['xmlfile']['name'], '.') + 1);
453     if (in_array($file_ext, array('bz','tbz','bz2','tbz2'))) {
454       $compressed = true;
455     }
456
457     // Create a temporary file.
458     $dirName = dirname(TEMPLATE_DIR . '_c/.');
459     $filename = tempnam($dirName, 'import_');
460
461     // If the file is compressed - uncompress it.
462     if ($compressed) {
463       if (!$this->uncompress($_FILES['xmlfile']['tmp_name'], $filename)) {
464         $this->errors->add($i18n->get('error.sys'));
465         return;
466       }
467       unlink($_FILES['xmlfile']['tmp_name']);
468     } else {
469       if (!move_uploaded_file($_FILES['xmlfile']['tmp_name'], $filename)) {
470         $this->errors->add($i18n->get('error.upload'));
471         return;
472       }
473     }
474
475     // Initialize XML parser.
476     $parser = xml_parser_create();
477     xml_set_object($parser, $this);
478     xml_set_element_handler($parser, 'startElement', false);
479
480     // We need to parse the file 2 times:
481     //   1) First pass: determine if import is possible - there must be no login collisions.
482     //   2) Second pass: if we can import, then do import in a second pass.
483     // This is different from earlier approach for single group import, where we could
484     // do both things in one pass because user info was in the beginning of XML file.
485     // Now, with subgroups, users can be located anywhere in the file.
486
487     // Read and parse the content of the file. During parsing, startElement, endElement, and dataElement functions are called.
488     $file = fopen($filename, 'r');
489     while ($data = fread($file, 4096)) {
490       if (!xml_parse($parser, $data, feof($file))) {
491         $this->errors->add(sprintf($i18n->get('error.xml'),
492           xml_get_current_line_number($parser),
493           xml_error_string(xml_get_error_code($parser))));
494       }
495     }
496     if ($this->conflicting_entities) {
497       $this->canImport = false;
498       $this->errors->add($i18n->get('error.user_exists'));
499       $this->errors->add(sprintf($i18n->get('error.cannot_import'), $this->conflicting_entities));
500     }
501
502     $this->firstPass = false; // We are done with 1st pass.
503     xml_parser_free($parser);
504     if ($file) fclose($file);
505     if (!$this->canImport) {
506       unlink($filename);
507       return;
508     }
509     if ($this->errors->yes()) return; // Exit if we have errors.
510
511     // Now we can do a second pass, where real work is done.
512     $parser = xml_parser_create();
513     xml_set_object($parser, $this);
514     xml_set_element_handler($parser, 'startElement', false);
515
516     // Read and parse the content of the file. During parsing, startElement, endElement, and dataElement functions are called.
517     $file = fopen($filename, 'r');
518     while ($data = fread($file, 4096)) {
519       if (!xml_parse($parser, $data, feof($file))) {
520         $this->errors->add(sprintf($i18n->get('error.xml'),
521           xml_get_current_line_number($parser),
522           xml_error_string(xml_get_error_code($parser))));
523       }
524     }
525     xml_parser_free($parser);
526     if ($file) fclose($file);
527     unlink($filename);
528   }
529
530   // uncompress - uncompresses the content of the $in file into the $out file.
531   function uncompress($in, $out) {
532     // Do we have the uncompress function?
533     if (!function_exists('bzopen'))
534       return false;
535
536     // Initial checks of file names and permissions.
537     if (!file_exists($in) || !is_readable ($in))
538       return false;
539     if ((!file_exists($out) && !is_writable(dirname($out))) || (file_exists($out) && !is_writable($out)))
540       return false;
541
542     if (!$out_file = fopen($out, 'wb'))
543       return false;
544     if (!$in_file = bzopen ($in, 'r'))
545       return false;
546
547     while (!feof($in_file)) {
548       $buffer = bzread($in_file, 4096);
549       fwrite($out_file, $buffer, 4096);
550     }
551     bzclose($in_file);
552     fclose ($out_file);
553     return true;
554   }
555
556   // createGroup function creates a new group.
557   private function createGroup($fields) {
558     global $user;
559     global $i18n;
560     $mdb2 = getConnection();
561
562     $columns = '(parent_id, org_id, name, currency, decimal_mark, lang, date_format, time_format'.
563       ', week_start, tracking_mode, project_required, task_required, record_type, bcc_email'.
564       ', allow_ip, password_complexity, plugins, lock_spec'.
565       ', workday_minutes, config, created, created_ip, created_by)';
566
567     $values = ' values (';
568     $values .= $mdb2->quote($fields['parent_id']);
569     $values .= ', '.$mdb2->quote($fields['org_id']);
570     $values .= ', '.$mdb2->quote(trim($fields['name']));
571     $values .= ', '.$mdb2->quote(trim($fields['currency']));
572     $values .= ', '.$mdb2->quote($fields['decimal_mark']);
573     $values .= ', '.$mdb2->quote($fields['lang']);
574     $values .= ', '.$mdb2->quote($fields['date_format']);
575     $values .= ', '.$mdb2->quote($fields['time_format']);
576     $values .= ', '.(int)$fields['week_start'];
577     $values .= ', '.(int)$fields['tracking_mode'];
578     $values .= ', '.(int)$fields['project_required'];
579     $values .= ', '.(int)$fields['task_required'];
580     $values .= ', '.(int)$fields['record_type'];
581     $values .= ', '.$mdb2->quote($fields['bcc_email']);
582     $values .= ', '.$mdb2->quote($fields['allow_ip']);
583     $values .= ', '.$mdb2->quote($fields['password_complexity']);
584     $values .= ', '.$mdb2->quote($fields['plugins']);
585     $values .= ', '.$mdb2->quote($fields['lock_spec']);
586     $values .= ', '.(int)$fields['workday_minutes'];
587     $values .= ', '.$mdb2->quote($fields['config']);
588     $values .= ', now(), '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', '.$mdb2->quote($user->id);
589     $values .= ')';
590
591     $sql = 'insert into tt_groups '.$columns.$values;
592     $affected = $mdb2->exec($sql);
593     if (is_a($affected, 'PEAR_Error')) {
594       $this->errors->add($i18n->get('error.db'));
595       return false;
596     }
597
598     $group_id = $mdb2->lastInsertID('tt_groups', 'id');
599     return $group_id;
600   }
601
602   // insertMonthlyQuota - a helper function to insert a monthly quota.
603   private function insertMonthlyQuota($group_id, $year, $month, $minutes) {
604     $mdb2 = getConnection();
605     $sql = "INSERT INTO tt_monthly_quotas (group_id, year, month, minutes) values ($group_id, $year, $month, $minutes)";
606     $affected = $mdb2->exec($sql);
607     return (!is_a($affected, 'PEAR_Error'));
608   }
609 }