Populated group_id and org_id in tt_fav_reports table.
[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('ttClientHelper');
33 import('ttInvoiceHelper');
34 import('ttTimeHelper');
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         if ($attrs['TASKS']) {
203           $tasks = explode(',', $attrs['TASKS']);
204           foreach ($tasks as $id)
205             $mapped_tasks[] = $this->currentGroupTaskMap[$id];
206         }
207
208         $project_id = $this->insertProject(array(
209           'group_id' => $this->current_group_id,
210           'org_id' => $this->org_id,
211           'name' => $attrs['NAME'],
212           'description' => $attrs['DESCRIPTION'],
213           'tasks' => $mapped_tasks,
214           'status' => $attrs['STATUS']));
215         if ($project_id) {
216           // Add a mapping.
217           $this->currentGroupProjectMap[$attrs['ID']] = $project_id;
218         } else $this->errors->add($i18n->get('error.db'));
219         return;
220       }
221
222       if ($name == 'CLIENTS') {
223         // If we get here, we have to recycle $currentGroupClientMap.
224         unset($this->currentGroupClientMap);
225         $this->currentGroupClientMap = array();
226         // Client map is reconstructed after processing <client> elements in XML. See below.
227         return;
228       }
229
230       if ($name == 'CLIENT') {
231         // We get here when processing <client> tags for the current group.
232
233         // Prepare a list of project ids.
234         if ($attrs['PROJECTS']) {
235           $projects = explode(',', $attrs['PROJECTS']);
236           foreach ($projects as $id)
237             $mapped_projects[] = $this->currentGroupProjectMap[$id];
238         }
239
240         $client_id = ttClientHelper::insert(array(
241           'group_id' => $this->current_group_id,
242           'org_id' => $this->org_id,
243           'name' => $attrs['NAME'],
244           'address' => $attrs['ADDRESS'],
245           'tax' => $attrs['TAX'],
246           'projects' => $mapped_projects,
247           'status' => $attrs['STATUS']));
248         if ($client_id) {
249           // Add a mapping.
250           $this->currentGroupClientMap[$attrs['ID']] = $client_id;
251         } else $this->errors->add($i18n->get('error.db'));
252         return;
253       }
254
255       if ($name == 'USERS') {
256         // If we get here, we have to recycle $currentGroupUserMap.
257         unset($this->currentGroupUserMap);
258         $this->currentGroupUserMap = array();
259         // User map is reconstructed after processing <user> elements in XML. See below.
260         return;
261       }
262
263       if ($name == 'USER') {
264         // We get here when processing <user> tags for the current group.
265
266         $role_id = $attrs['ROLE_ID'] === '0' ? $this->top_role_id :  $this->currentGroupRoleMap[$attrs['ROLE_ID']]; // 0 (not null) means top manager role.
267
268         $user_id = ttUserHelper::insert(array(
269           'group_id' => $this->current_group_id,
270           'org_id' => $this->org_id,
271           'role_id' => $role_id,
272           'client_id' => $this->currentGroupClientMap[$attrs['CLIENT_ID']],
273           'name' => $attrs['NAME'],
274           'login' => $attrs['LOGIN'],
275           'password' => $attrs['PASSWORD'],
276           'rate' => $attrs['RATE'],
277           'email' => $attrs['EMAIL'],
278           'status' => $attrs['STATUS']), false);
279         if ($user_id) {
280           // Add a mapping.
281           $this->currentGroupUserMap[$attrs['ID']] = $user_id;
282         } else $this->errors->add($i18n->get('error.db'));
283         return;
284       }
285
286       if ($name == 'USER_PROJECT_BIND') {
287         if (!ttUserHelper::insertBind(array(
288           'user_id' => $this->currentGroupUserMap[$attrs['USER_ID']],
289           'project_id' => $this->currentGroupProjectMap[$attrs['PROJECT_ID']],
290           'group_id' => $this->current_group_id,
291           'org_id' => $this->org_id,
292           'rate' => $attrs['RATE'],
293           'status' => $attrs['STATUS']))) {
294           $this->errors->add($i18n->get('error.db'));
295         }
296         return;
297       }
298
299       if ($name == 'INVOICES') {
300         // If we get here, we have to recycle $currentGroupInvoiceMap.
301         unset($this->currentGroupInvoiceMap);
302         $this->currentGroupInvoiceMap = array();
303         // Invoice map is reconstructed after processing <invoice> elements in XML. See below.
304         return;
305       }
306
307       if ($name == 'INVOICE') {
308         // We get here when processing <invoice> tags for the current group.
309         $invoice_id = ttInvoiceHelper::insert(array(
310           'group_id' => $this->current_group_id,
311           'org_id' => $this->org_id,
312           'name' => $attrs['NAME'],
313           'date' => $attrs['DATE'],
314           'client_id' => $this->currentGroupClientMap[$attrs['CLIENT_ID']],
315           'status' => $attrs['STATUS']));
316         if ($invoice_id) {
317           // Add a mapping.
318           $this->currentGroupInvoiceMap[$attrs['ID']] = $invoice_id;
319         } else $this->errors->add($i18n->get('error.db'));
320         return;
321       }
322
323       if ($name == 'LOG') {
324         // If we get here, we have to recycle $currentGroupLogMap.
325         unset($this->currentGroupLogMap);
326         $this->currentGroupLogMap = array();
327         // Log map is reconstructed after processing <log_item> elements in XML. See below.
328         return;
329       }
330
331       if ($name == 'LOG_ITEM') {
332         // We get here when processing <log_item> tags for the current group.
333         $log_item_id = ttTimeHelper::insert(array(
334           'user_id' => $this->currentGroupUserMap[$attrs['USER_ID']],
335           'group_id' => $this->current_group_id,
336           'org_id' => $this->org_id,
337           'date' => $attrs['DATE'],
338           'start' => $attrs['START'],
339           'finish' => $attrs['FINISH'],
340           'duration' => $attrs['DURATION'],
341           'client' => $this->currentGroupClientMap[$attrs['CLIENT_ID']],
342           'project' => $this->currentGroupProjectMap[$attrs['PROJECT_ID']],
343           'task' => $this->currentGroupTaskMap[$attrs['TASK_ID']],
344           'invoice' => $this->currentGroupInvoiceMap[$attrs['INVOICE_ID']],
345           'note' => (isset($attrs['COMMENT']) ? $attrs['COMMENT'] : ''),
346           'billable' => $attrs['BILLABLE'],
347           'paid' => $attrs['PAID'],
348           'status' => $attrs['STATUS']));
349         if ($log_item_id) {
350           // Add a mapping.
351           $this->currentGroupLogMap[$attrs['ID']] = $log_item_id;
352         } else $this->errors->add($i18n->get('error.db'));
353         return;
354       }
355
356       if ($name == 'CUSTOM_FIELDS') {
357         // If we get here, we have to recycle $currentGroupCustomFieldMap.
358         unset($this->currentGroupCustomFieldMap);
359         $this->currentGroupCustomFieldMap = array();
360         // Custom field map is reconstructed after processing <custom_field> elements in XML. See below.
361         return;
362       }
363
364       if ($name == 'CUSTOM_FIELD') {
365         // We get here when processing <custom_field> tags for the current group.
366         $custom_field_id = ttCustomFieldHelper::insertField(array(
367           'group_id' => $this->current_group_id,
368           // 'org_id' => $this->org_id, TODO: add this when org_id field is added to the table.
369           'type' => $attrs['TYPE'],
370           'label' => $attrs['LABEL'],
371           'required' => $attrs['REQUIRED'],
372           'status' => $attrs['STATUS']));
373         if ($custom_field_id) {
374           // Add a mapping.
375           $this->currentGroupCustomFieldMap[$attrs['ID']] = $custom_field_id;
376         } else $this->errors->add($i18n->get('error.db'));
377         return;
378       }
379
380       if ($name == 'CUSTOM_FIELD_OPTIONS') {
381         // If we get here, we have to recycle $currentGroupCustomFieldOptionMap.
382         unset($this->currentGroupCustomFieldOptionMap);
383         $this->currentGroupCustomFieldOptionMap = array();
384         // Custom field option map is reconstructed after processing <custom_field_option> elements in XML. See below.
385         return;
386       }
387
388       if ($name == 'CUSTOM_FIELD_OPTION') {
389         // We get here when processing <custom_field_option> tags for the current group.
390         $custom_field_option_id = ttCustomFieldHelper::insertOption(array(
391           // 'group_id' => $this->current_group_id, TODO: add this when group_id field is added to the table.
392           // 'org_id' => $this->org_id, TODO: add this when org_id field is added to the table.
393           'field_id' => $this->currentGroupCustomFieldMap[$attrs['FIELD_ID']],
394           'value' => $attrs['VALUE']));
395         if ($custom_field_option_id) {
396           // Add a mapping.
397           $this->currentGroupCustomFieldOptionMap[$attrs['ID']] = $custom_field_option_id;
398         } else $this->errors->add($i18n->get('error.db'));
399         return;
400       }
401
402       if ($name == 'CUSTOM_FIELD_LOG_ENTRY') {
403         // We get here when processing <custom_field_log_entry> tags for the current group.
404         if (!ttCustomFieldHelper::insertLogEntry(array(
405           // 'group_id' => $this->current_group_id, TODO: add this when group_id field is added to the table.
406           // 'org_id' => $this->org_id, TODO: add this when org_id field is added to the table.
407           'log_id' => $this->currentGroupLogMap[$attrs['LOG_ID']],
408           'field_id' => $this->currentGroupCustomFieldMap[$attrs['FIELD_ID']],
409           'option_id' => $this->currentGroupCustomFieldOptionMap[$attrs['OPTION_ID']],
410           'value' => $attrs['VALUE'],
411           'status' => $attrs['STATUS']))) {
412           $this->errors->add($i18n->get('error.db'));
413         }
414         return;
415       }
416
417       if ($name == 'EXPENSE_ITEM') {
418         // We get here when processing <expense_item> tags for the current group.
419         $expense_item_id = $this->insertExpense(array(
420           'date' => $attrs['DATE'],
421           'user_id' => $this->currentGroupUserMap[$attrs['USER_ID']],
422           'group_id' => $this->current_group_id,
423           'org_id' => $this->org_id,
424           'client_id' => $this->currentGroupClientMap[$attrs['CLIENT_ID']],
425           'project_id' => $this->currentGroupProjectMap[$attrs['PROJECT_ID']],
426           'name' => $attrs['NAME'],
427           'cost' => $attrs['COST'],
428           'invoice_id' => $this->currentGroupInvoiceMap[$attrs['INVOICE_ID']],
429           'paid' => $attrs['PAID'],
430           'status' => $attrs['STATUS']));
431         if (!$expense_item_id) $this->errors->add($i18n->get('error.db'));
432         return;
433       }
434
435       if ($name == 'PREDEFINED_EXPENSE') {
436         if (!$this->insertPredefinedExpense(array(
437           'group_id' => $this->current_group_id,
438           'org_id' => $this->org_id,
439           'name' => $attrs['NAME'],
440           'cost' => $attrs['COST']))) {
441           $this->errors->add($i18n->get('error.db'));
442         }
443         return;
444       }
445
446       if ($name == 'MONTHLY_QUOTA') {
447         if (!$this->insertMonthlyQuota(array(
448           'group_id' => $this->current_group_id,
449           'org_id' => $this->org_id,
450           'year' => $attrs['YEAR'],
451           'month' => $attrs['MONTH'],
452           'minutes' => $attrs['MINUTES']))) {
453           $this->errors->add($i18n->get('error.db'));
454         }
455         return;
456       }
457
458       if ($name == 'FAV_REPORT') {
459         $user_list = '';
460         if (strlen($attrs['USERS']) > 0) {
461           $arr = explode(',', $attrs['USERS']);
462           foreach ($arr as $v)
463             $user_list .= (strlen($user_list) == 0 ? '' : ',').$this->currentGroupUserMap[$v];
464         }
465         if (!$this->insertFavReport(array(
466           'name' => $attrs['NAME'],
467           'user_id' => $this->currentGroupUserMap[$attrs['USER_ID']],
468           'group_id' => $this->current_group_id,
469           'org_id' => $this->org_id,
470           'client' => $this->currentGroupClientMap[$attrs['CLIENT_ID']],
471           'option' => $this->currentGroupCustomFieldOptionMap[$attrs['CF_1_OPTION_ID']],
472           'project' => $this->currentGroupProjectMap[$attrs['PROJECT_ID']],
473           'task' => $this->currentGroupTaskMap[$attrs['TASK_ID']],
474           'billable' => $attrs['BILLABLE'],
475           'users' => $user_list,
476           'period' => $attrs['PERIOD'],
477           'from' => $attrs['PERIOD_START'],
478           'to' => $attrs['PERIOD_END'],
479           'chclient' => (int) $attrs['SHOW_CLIENT'],
480           'chinvoice' => (int) $attrs['SHOW_INVOICE'],
481           'chpaid' => (int) $attrs['SHOW_PAID'],
482           'chip' => (int) $attrs['SHOW_IP'],
483           'chproject' => (int) $attrs['SHOW_PROJECT'],
484           'chstart' => (int) $attrs['SHOW_START'],
485           'chduration' => (int) $attrs['SHOW_DURATION'],
486           'chcost' => (int) $attrs['SHOW_COST'],
487           'chtask' => (int) $attrs['SHOW_TASK'],
488           'chfinish' => (int) $attrs['SHOW_END'],
489           'chnote' => (int) $attrs['SHOW_NOTE'],
490           'chcf_1' => (int) $attrs['SHOW_CUSTOM_FIELD_1'],
491           'chunits' => (int) $attrs['SHOW_WORK_UNITS'],
492           'group_by1' => $attrs['GROUP_BY1'],
493           'group_by2' => $attrs['GROUP_BY2'],
494           'group_by3' => $attrs['GROUP_BY3'],
495           'chtotalsonly' => (int) $attrs['SHOW_TOTALS_ONLY']))) {
496            $this->errors->add($i18n->get('error.db'));
497          }
498          return;
499       }
500     }
501   }
502
503   // importXml - uncompresses the file, reads and parses its content. During parsing,
504   // startElement, endElement, and dataElement functions are called as many times as necessary.
505   // Actual import occurs in the endElement handler.
506   function importXml() {
507     global $i18n;
508
509     // Do we have a compressed file?
510     $compressed = false;
511     $file_ext = substr($_FILES['xmlfile']['name'], strrpos($_FILES['xmlfile']['name'], '.') + 1);
512     if (in_array($file_ext, array('bz','tbz','bz2','tbz2'))) {
513       $compressed = true;
514     }
515
516     // Create a temporary file.
517     $dirName = dirname(TEMPLATE_DIR . '_c/.');
518     $filename = tempnam($dirName, 'import_');
519
520     // If the file is compressed - uncompress it.
521     if ($compressed) {
522       if (!$this->uncompress($_FILES['xmlfile']['tmp_name'], $filename)) {
523         $this->errors->add($i18n->get('error.sys'));
524         return;
525       }
526       unlink($_FILES['xmlfile']['tmp_name']);
527     } else {
528       if (!move_uploaded_file($_FILES['xmlfile']['tmp_name'], $filename)) {
529         $this->errors->add($i18n->get('error.upload'));
530         return;
531       }
532     }
533
534     // Initialize XML parser.
535     $parser = xml_parser_create();
536     xml_set_object($parser, $this);
537     xml_set_element_handler($parser, 'startElement', false);
538
539     // We need to parse the file 2 times:
540     //   1) First pass: determine if import is possible.
541     //   2) Second pass: import data, one tag at a time.
542
543     // Read and parse the content of the file. During parsing, startElement is called back for each tag.
544     $file = fopen($filename, 'r');
545     while (($data = fread($file, 4096)) && $this->errors->no()) {
546       if (!xml_parse($parser, $data, feof($file))) {
547         $this->errors->add(sprintf($i18n->get('error.xml'),
548           xml_get_current_line_number($parser),
549           xml_error_string(xml_get_error_code($parser))));
550       }
551     }
552     if ($this->conflicting_logins) {
553       $this->canImport = false;
554       $this->errors->add($i18n->get('error.user_exists'));
555       $this->errors->add(sprintf($i18n->get('error.cannot_import'), $this->conflicting_logins));
556     }
557
558     $this->firstPass = false; // We are done with 1st pass.
559     xml_parser_free($parser);
560     if ($file) fclose($file);
561     if (!$this->canImport) {
562       unlink($filename);
563       return;
564     }
565     if ($this->errors->yes()) return; // Exit if we have errors.
566
567     // Now we can do a second pass, where real work is done.
568     $parser = xml_parser_create();
569     xml_set_object($parser, $this);
570     xml_set_element_handler($parser, 'startElement', false);
571
572     // Read and parse the content of the file. During parsing, startElement is called back for each tag.
573     $file = fopen($filename, 'r');
574     while (($data = fread($file, 4096)) && $this->errors->no()) {
575       if (!xml_parse($parser, $data, feof($file))) {
576         $this->errors->add(sprintf($i18n->get('error.xml'),
577           xml_get_current_line_number($parser),
578           xml_error_string(xml_get_error_code($parser))));
579       }
580     }
581     xml_parser_free($parser);
582     if ($file) fclose($file);
583     unlink($filename);
584   }
585
586   // uncompress - uncompresses the content of the $in file into the $out file.
587   function uncompress($in, $out) {
588     // Do we have the uncompress function?
589     if (!function_exists('bzopen'))
590       return false;
591
592     // Initial checks of file names and permissions.
593     if (!file_exists($in) || !is_readable ($in))
594       return false;
595     if ((!file_exists($out) && !is_writable(dirname($out))) || (file_exists($out) && !is_writable($out)))
596       return false;
597
598     if (!$out_file = fopen($out, 'wb'))
599       return false;
600     if (!$in_file = bzopen ($in, 'r'))
601       return false;
602
603     while (!feof($in_file)) {
604       $buffer = bzread($in_file, 4096);
605       fwrite($out_file, $buffer, 4096);
606     }
607     bzclose($in_file);
608     fclose ($out_file);
609     return true;
610   }
611
612   // createGroup function creates a new group.
613   private function createGroup($fields) {
614     global $user;
615     global $i18n;
616     $mdb2 = getConnection();
617
618     $columns = '(parent_id, org_id, name, currency, decimal_mark, lang, date_format, time_format'.
619       ', week_start, tracking_mode, project_required, task_required, record_type, bcc_email'.
620       ', allow_ip, password_complexity, plugins, lock_spec'.
621       ', workday_minutes, config, created, created_ip, created_by)';
622
623     $values = ' values (';
624     $values .= $mdb2->quote($fields['parent_id']);
625     $values .= ', '.$mdb2->quote($fields['org_id']);
626     $values .= ', '.$mdb2->quote(trim($fields['name']));
627     $values .= ', '.$mdb2->quote(trim($fields['currency']));
628     $values .= ', '.$mdb2->quote($fields['decimal_mark']);
629     $values .= ', '.$mdb2->quote($fields['lang']);
630     $values .= ', '.$mdb2->quote($fields['date_format']);
631     $values .= ', '.$mdb2->quote($fields['time_format']);
632     $values .= ', '.(int)$fields['week_start'];
633     $values .= ', '.(int)$fields['tracking_mode'];
634     $values .= ', '.(int)$fields['project_required'];
635     $values .= ', '.(int)$fields['task_required'];
636     $values .= ', '.(int)$fields['record_type'];
637     $values .= ', '.$mdb2->quote($fields['bcc_email']);
638     $values .= ', '.$mdb2->quote($fields['allow_ip']);
639     $values .= ', '.$mdb2->quote($fields['password_complexity']);
640     $values .= ', '.$mdb2->quote($fields['plugins']);
641     $values .= ', '.$mdb2->quote($fields['lock_spec']);
642     $values .= ', '.(int)$fields['workday_minutes'];
643     $values .= ', '.$mdb2->quote($fields['config']);
644     $values .= ', now(), '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', '.$mdb2->quote($user->id);
645     $values .= ')';
646
647     $sql = 'insert into tt_groups '.$columns.$values;
648     $affected = $mdb2->exec($sql);
649     if (is_a($affected, 'PEAR_Error')) {
650       $this->errors->add($i18n->get('error.db'));
651       return false;
652     }
653
654     $group_id = $mdb2->lastInsertID('tt_groups', 'id');
655     return $group_id;
656   }
657
658   // insertMonthlyQuota - a helper function to insert a monthly quota.
659   private function insertMonthlyQuota($fields) {
660     $mdb2 = getConnection();
661     $group_id = (int) $fields['group_id'];
662     $org_id = (int) $fields['org_id'];
663     $year = (int) $fields['year'];
664     $month = (int) $fields['month'];
665     $minutes = (int) $fields['minutes'];
666
667     $sql = "INSERT INTO tt_monthly_quotas (group_id, org_id, year, month, minutes)".
668       " values ($group_id, $org_id, $year, $month, $minutes)";
669     $affected = $mdb2->exec($sql);
670     return (!is_a($affected, 'PEAR_Error'));
671   }
672
673   // insertPredefinedExpense - a helper function to insert a predefined expense.
674   private function insertPredefinedExpense($fields) {
675     $mdb2 = getConnection();
676     $group_id = (int) $fields['group_id'];
677     $org_id = (int) $fields['org_id'];
678     $name = $mdb2->quote($fields['name']);
679     $cost = $mdb2->quote($fields['cost']);
680
681     $sql = "INSERT INTO tt_predefined_expenses (group_id, org_id, name, cost)".
682       " values ($group_id, $org_id, $name, $cost)";
683     $affected = $mdb2->exec($sql);
684     return (!is_a($affected, 'PEAR_Error'));
685   }
686
687   // insertExpense - a helper function to insert an expense item.
688   private function insertExpense($fields) {
689     global $user;
690     $mdb2 = getConnection();
691
692     $group_id = (int) $fields['group_id'];
693     $org_id = (int) $fields['org_id'];
694     $date = $fields['date'];
695     $user_id = (int) $fields['user_id'];
696     $client_id = $fields['client_id'];
697     $project_id = $fields['project_id'];
698     $name = $fields['name'];
699     $cost = str_replace(',', '.', $fields['cost']);
700     $invoice_id = $fields['invoice_id'];
701     $status = $fields['status'];
702     $paid = (int) $fields['paid'];
703     $created = ', now(), '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', '.$mdb2->quote($user->id);
704
705     $sql = "insert into tt_expense_items".
706       " (date, user_id, group_id, org_id, client_id, project_id, name, cost, invoice_id, paid, created, created_ip, created_by, status)".
707       " values (".$mdb2->quote($date).", $user_id, $group_id, $org_id, ".$mdb2->quote($client_id).", ".$mdb2->quote($project_id).
708       ", ".$mdb2->quote($name).", ".$mdb2->quote($cost).", ".$mdb2->quote($invoice_id).", $paid $created, ".$mdb2->quote($status).")";
709     $affected = $mdb2->exec($sql);
710     return (!is_a($affected, 'PEAR_Error'));
711   }
712
713   // insertProject - a helper function to insert a project as well as project to task binds.
714   private function insertProject($fields)
715   {
716     $mdb2 = getConnection();
717
718     $group_id = (int) $fields['group_id'];
719     $org_id = (int) $fields['org_id'];
720
721     $name = $fields['name'];
722     $description = $fields['description'];
723     $tasks = $fields['tasks'];
724     $comma_separated = implode(',', $tasks); // This is a comma-separated list of associated task ids.
725     $status = $fields['status'];
726
727     $sql = "insert into tt_projects (group_id, org_id, name, description, tasks, status)
728       values ($group_id, $org_id, ".$mdb2->quote($name).", ".$mdb2->quote($description).", ".$mdb2->quote($comma_separated).", ".$mdb2->quote($status).")";
729     $affected = $mdb2->exec($sql);
730     if (is_a($affected, 'PEAR_Error'))
731       return false;
732
733     $last_id = 0;
734     $sql = "select last_insert_id() as last_insert_id";
735     $res = $mdb2->query($sql);
736     $val = $res->fetchRow();
737     $last_id = $val['last_insert_id'];
738
739     // Insert binds into tt_project_task_binds table.
740     if (is_array($tasks)) {
741       foreach ($tasks as $task_id) {
742         $sql = "insert into tt_project_task_binds (project_id, task_id, group_id, org_id)".
743           " values($last_id, $task_id, $group_id, $org_id)";
744         $affected = $mdb2->exec($sql);
745         if (is_a($affected, 'PEAR_Error'))
746           return false;
747       }
748     }
749
750     return $last_id;
751   }
752
753   // insertFavReport - inserts a favorite report in database.
754   private function insertFavReport($fields) {
755     $mdb2 = getConnection();
756
757     $group_id = (int) $fields['group_id'];
758     $org_id = (int) $fields['org_id'];
759
760     $sql = "insert into tt_fav_reports".
761       " (name, user_id, group_id, org_id, client_id, cf_1_option_id, project_id, task_id,".
762       " billable, invoice, paid_status, users, period, period_start, period_end,".
763       " show_client, show_invoice, show_paid, show_ip,".
764       " show_project, show_start, show_duration, show_cost,".
765       " show_task, show_end, show_note, show_custom_field_1, show_work_units,".
766       " group_by1, group_by2, group_by3, show_totals_only)".
767       " values(".
768       $mdb2->quote($fields['name']).", ".$fields['user_id'].", $group_id, $org_id, ".
769       $mdb2->quote($fields['client']).", ".$mdb2->quote($fields['option']).", ".
770       $mdb2->quote($fields['project']).", ".$mdb2->quote($fields['task']).", ".
771       $mdb2->quote($fields['billable']).", ".$mdb2->quote($fields['invoice']).", ".
772       $mdb2->quote($fields['paid_status']).", ".
773       $mdb2->quote($fields['users']).", ".$mdb2->quote($fields['period']).", ".
774       $mdb2->quote($fields['from']).", ".$mdb2->quote($fields['to']).", ".
775       $fields['chclient'].", ".$fields['chinvoice'].", ".$fields['chpaid'].", ".$fields['chip'].", ".
776       $fields['chproject'].", ".$fields['chstart'].", ".$fields['chduration'].", ".$fields['chcost'].", ".
777       $fields['chtask'].", ".$fields['chfinish'].", ".$fields['chnote'].", ".$fields['chcf_1'].", ".$fields['chunits'].", ".
778       $mdb2->quote($fields['group_by1']).", ".$mdb2->quote($fields['group_by2']).", ".
779       $mdb2->quote($fields['group_by3']).", ".$fields['chtotalsonly'].")";
780     $affected = $mdb2->exec($sql);
781     return (!is_a($affected, 'PEAR_Error'));
782   }
783 }