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