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