Refactored import a bit by writing a function to insert projects with binds.
[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         $fav_report_id = ttFavReportHelper::insertReport(array(
466           'name' => $attrs['NAME'],
467           'user_id' => $this->currentGroupUserMap[$attrs['USER_ID']],
468           'client' => $this->currentGroupClientMap[$attrs['CLIENT_ID']],
469           'option' => $this->currentGroupCustomFieldOptionMap[$attrs['CF_1_OPTION_ID']],
470           'project' => $this->currentGroupProjectMap[$attrs['PROJECT_ID']],
471           'task' => $this->currentGroupTaskMap[$attrs['TASK_ID']],
472           'billable' => $attrs['BILLABLE'],
473           'users' => $user_list,
474           'period' => $attrs['PERIOD'],
475           'from' => $attrs['PERIOD_START'],
476           'to' => $attrs['PERIOD_END'],
477           'chclient' => (int) $attrs['SHOW_CLIENT'],
478           'chinvoice' => (int) $attrs['SHOW_INVOICE'],
479           'chpaid' => (int) $attrs['SHOW_PAID'],
480           'chip' => (int) $attrs['SHOW_IP'],
481           'chproject' => (int) $attrs['SHOW_PROJECT'],
482           'chstart' => (int) $attrs['SHOW_START'],
483           'chduration' => (int) $attrs['SHOW_DURATION'],
484           'chcost' => (int) $attrs['SHOW_COST'],
485           'chtask' => (int) $attrs['SHOW_TASK'],
486           'chfinish' => (int) $attrs['SHOW_END'],
487           'chnote' => (int) $attrs['SHOW_NOTE'],
488           'chcf_1' => (int) $attrs['SHOW_CUSTOM_FIELD_1'],
489           'chunits' => (int) $attrs['SHOW_WORK_UNITS'],
490           'group_by1' => $attrs['GROUP_BY1'],
491           'group_by2' => $attrs['GROUP_BY2'],
492           'group_by3' => $attrs['GROUP_BY3'],
493           'chtotalsonly' => (int) $attrs['SHOW_TOTALS_ONLY']));
494          if (!$fav_report_id) $this->errors->add($i18n->get('error.db'));
495          return;
496       }
497     }
498   }
499
500   // importXml - uncompresses the file, reads and parses its content. During parsing,
501   // startElement, endElement, and dataElement functions are called as many times as necessary.
502   // Actual import occurs in the endElement handler.
503   function importXml() {
504     global $i18n;
505
506     // Do we have a compressed file?
507     $compressed = false;
508     $file_ext = substr($_FILES['xmlfile']['name'], strrpos($_FILES['xmlfile']['name'], '.') + 1);
509     if (in_array($file_ext, array('bz','tbz','bz2','tbz2'))) {
510       $compressed = true;
511     }
512
513     // Create a temporary file.
514     $dirName = dirname(TEMPLATE_DIR . '_c/.');
515     $filename = tempnam($dirName, 'import_');
516
517     // If the file is compressed - uncompress it.
518     if ($compressed) {
519       if (!$this->uncompress($_FILES['xmlfile']['tmp_name'], $filename)) {
520         $this->errors->add($i18n->get('error.sys'));
521         return;
522       }
523       unlink($_FILES['xmlfile']['tmp_name']);
524     } else {
525       if (!move_uploaded_file($_FILES['xmlfile']['tmp_name'], $filename)) {
526         $this->errors->add($i18n->get('error.upload'));
527         return;
528       }
529     }
530
531     // Initialize XML parser.
532     $parser = xml_parser_create();
533     xml_set_object($parser, $this);
534     xml_set_element_handler($parser, 'startElement', false);
535
536     // We need to parse the file 2 times:
537     //   1) First pass: determine if import is possible.
538     //   2) Second pass: import data, one tag at a time.
539
540     // Read and parse the content of the file. During parsing, startElement is called back for each tag.
541     $file = fopen($filename, 'r');
542     while (($data = fread($file, 4096)) && $this->errors->no()) {
543       if (!xml_parse($parser, $data, feof($file))) {
544         $this->errors->add(sprintf($i18n->get('error.xml'),
545           xml_get_current_line_number($parser),
546           xml_error_string(xml_get_error_code($parser))));
547       }
548     }
549     if ($this->conflicting_logins) {
550       $this->canImport = false;
551       $this->errors->add($i18n->get('error.user_exists'));
552       $this->errors->add(sprintf($i18n->get('error.cannot_import'), $this->conflicting_logins));
553     }
554
555     $this->firstPass = false; // We are done with 1st pass.
556     xml_parser_free($parser);
557     if ($file) fclose($file);
558     if (!$this->canImport) {
559       unlink($filename);
560       return;
561     }
562     if ($this->errors->yes()) return; // Exit if we have errors.
563
564     // Now we can do a second pass, where real work is done.
565     $parser = xml_parser_create();
566     xml_set_object($parser, $this);
567     xml_set_element_handler($parser, 'startElement', false);
568
569     // Read and parse the content of the file. During parsing, startElement is called back for each tag.
570     $file = fopen($filename, 'r');
571     while (($data = fread($file, 4096)) && $this->errors->no()) {
572       if (!xml_parse($parser, $data, feof($file))) {
573         $this->errors->add(sprintf($i18n->get('error.xml'),
574           xml_get_current_line_number($parser),
575           xml_error_string(xml_get_error_code($parser))));
576       }
577     }
578     xml_parser_free($parser);
579     if ($file) fclose($file);
580     unlink($filename);
581   }
582
583   // uncompress - uncompresses the content of the $in file into the $out file.
584   function uncompress($in, $out) {
585     // Do we have the uncompress function?
586     if (!function_exists('bzopen'))
587       return false;
588
589     // Initial checks of file names and permissions.
590     if (!file_exists($in) || !is_readable ($in))
591       return false;
592     if ((!file_exists($out) && !is_writable(dirname($out))) || (file_exists($out) && !is_writable($out)))
593       return false;
594
595     if (!$out_file = fopen($out, 'wb'))
596       return false;
597     if (!$in_file = bzopen ($in, 'r'))
598       return false;
599
600     while (!feof($in_file)) {
601       $buffer = bzread($in_file, 4096);
602       fwrite($out_file, $buffer, 4096);
603     }
604     bzclose($in_file);
605     fclose ($out_file);
606     return true;
607   }
608
609   // createGroup function creates a new group.
610   private function createGroup($fields) {
611     global $user;
612     global $i18n;
613     $mdb2 = getConnection();
614
615     $columns = '(parent_id, org_id, name, currency, decimal_mark, lang, date_format, time_format'.
616       ', week_start, tracking_mode, project_required, task_required, record_type, bcc_email'.
617       ', allow_ip, password_complexity, plugins, lock_spec'.
618       ', workday_minutes, config, created, created_ip, created_by)';
619
620     $values = ' values (';
621     $values .= $mdb2->quote($fields['parent_id']);
622     $values .= ', '.$mdb2->quote($fields['org_id']);
623     $values .= ', '.$mdb2->quote(trim($fields['name']));
624     $values .= ', '.$mdb2->quote(trim($fields['currency']));
625     $values .= ', '.$mdb2->quote($fields['decimal_mark']);
626     $values .= ', '.$mdb2->quote($fields['lang']);
627     $values .= ', '.$mdb2->quote($fields['date_format']);
628     $values .= ', '.$mdb2->quote($fields['time_format']);
629     $values .= ', '.(int)$fields['week_start'];
630     $values .= ', '.(int)$fields['tracking_mode'];
631     $values .= ', '.(int)$fields['project_required'];
632     $values .= ', '.(int)$fields['task_required'];
633     $values .= ', '.(int)$fields['record_type'];
634     $values .= ', '.$mdb2->quote($fields['bcc_email']);
635     $values .= ', '.$mdb2->quote($fields['allow_ip']);
636     $values .= ', '.$mdb2->quote($fields['password_complexity']);
637     $values .= ', '.$mdb2->quote($fields['plugins']);
638     $values .= ', '.$mdb2->quote($fields['lock_spec']);
639     $values .= ', '.(int)$fields['workday_minutes'];
640     $values .= ', '.$mdb2->quote($fields['config']);
641     $values .= ', now(), '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', '.$mdb2->quote($user->id);
642     $values .= ')';
643
644     $sql = 'insert into tt_groups '.$columns.$values;
645     $affected = $mdb2->exec($sql);
646     if (is_a($affected, 'PEAR_Error')) {
647       $this->errors->add($i18n->get('error.db'));
648       return false;
649     }
650
651     $group_id = $mdb2->lastInsertID('tt_groups', 'id');
652     return $group_id;
653   }
654
655   // insertMonthlyQuota - a helper function to insert a monthly quota.
656   private function insertMonthlyQuota($fields) {
657     $mdb2 = getConnection();
658     $group_id = (int) $fields['group_id'];
659     $org_id = (int) $fields['org_id'];
660     $year = (int) $fields['year'];
661     $month = (int) $fields['month'];
662     $minutes = (int) $fields['minutes'];
663
664     $sql = "INSERT INTO tt_monthly_quotas (group_id, org_id, year, month, minutes)".
665       " values ($group_id, $org_id, $year, $month, $minutes)";
666     $affected = $mdb2->exec($sql);
667     return (!is_a($affected, 'PEAR_Error'));
668   }
669
670   // insertPredefinedExpense - a helper function to insert a predefined expense.
671   private function insertPredefinedExpense($fields) {
672     $mdb2 = getConnection();
673     $group_id = (int) $fields['group_id'];
674     $org_id = (int) $fields['org_id'];
675     $name = $mdb2->quote($fields['name']);
676     $cost = $mdb2->quote($fields['cost']);
677
678     $sql = "INSERT INTO tt_predefined_expenses (group_id, org_id, name, cost)".
679       " values ($group_id, $org_id, $name, $cost)";
680     $affected = $mdb2->exec($sql);
681     return (!is_a($affected, 'PEAR_Error'));
682   }
683
684   // insertExpense - a helper function to insert an expense item.
685   private function insertExpense($fields) {
686     global $user;
687     $mdb2 = getConnection();
688
689     $group_id = (int) $fields['group_id'];
690     $org_id = (int) $fields['org_id'];
691     $date = $fields['date'];
692     $user_id = (int) $fields['user_id'];
693     $client_id = $fields['client_id'];
694     $project_id = $fields['project_id'];
695     $name = $fields['name'];
696     $cost = str_replace(',', '.', $fields['cost']);
697     $invoice_id = $fields['invoice_id'];
698     $status = $fields['status'];
699     $paid = (int) $fields['paid'];
700     $created = ', now(), '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', '.$mdb2->quote($user->id);
701
702     $sql = "insert into tt_expense_items".
703       " (date, user_id, group_id, org_id, client_id, project_id, name, cost, invoice_id, paid, created, created_ip, created_by, status)".
704       " values (".$mdb2->quote($date).", $user_id, $group_id, $org_id, ".$mdb2->quote($client_id).", ".$mdb2->quote($project_id).
705       ", ".$mdb2->quote($name).", ".$mdb2->quote($cost).", ".$mdb2->quote($invoice_id).", $paid $created, ".$mdb2->quote($status).")";
706     $affected = $mdb2->exec($sql);
707     return (!is_a($affected, 'PEAR_Error'));
708   }
709
710   // insertProject - a helper function to insert a project as well as project to task binds.
711   private function insertProject($fields)
712   {
713     $mdb2 = getConnection();
714
715     $group_id = (int) $fields['group_id'];
716     $org_id = (int) $fields['org_id'];
717
718     $name = $fields['name'];
719     $description = $fields['description'];
720     $tasks = $fields['tasks'];
721     $comma_separated = implode(',', $tasks); // This is a comma-separated list of associated task ids.
722     $status = $fields['status'];
723
724     $sql = "insert into tt_projects (group_id, org_id, name, description, tasks, status)
725       values ($group_id, $org_id, ".$mdb2->quote($name).", ".$mdb2->quote($description).", ".$mdb2->quote($comma_separated).", ".$mdb2->quote($status).")";
726     $affected = $mdb2->exec($sql);
727     if (is_a($affected, 'PEAR_Error'))
728       return false;
729
730     $last_id = 0;
731     $sql = "select last_insert_id() as last_insert_id";
732     $res = $mdb2->query($sql);
733     $val = $res->fetchRow();
734     $last_id = $val['last_insert_id'];
735
736     // Insert binds into tt_project_task_binds table.
737     if (is_array($tasks)) {
738       foreach ($tasks as $task_id) {
739         $sql = "insert into tt_project_task_binds (project_id, task_id, group_id, org_id)".
740           " values($last_id, $task_id, $group_id, $org_id)";
741         $affected = $mdb2->exec($sql);
742         if (is_a($affected, 'PEAR_Error'))
743           return false;
744       }
745     }
746
747     return $last_id;
748   }
749 }