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