More work on new import. Implemented 2-pass approach.
[timetracker.git] / WEB-INF / lib / ttImportHelper2.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('ttTeamHelper');
30 import('ttUserHelper');
31 import('ttProjectHelper');
32 import('ttTaskHelper');
33 import('ttInvoiceHelper');
34 import('ttTimeHelper');
35 import('ttClientHelper');
36 import('ttCustomFieldHelper');
37 import('ttFavReportHelper');
38 import('ttExpenseHelper');
39 import('ttRoleHelper');
40
41 // ttImportHelper2 - this class is a future replacement for ttImportHelper.
42 // Currently, it is work in progress.
43 // When done, it should handle import of complex groups consisting of other groups.
44 class ttImportHelper2 {
45   var $errors         = null;    // Errors go here. Set in constructor by reference.
46
47   var $currentElement = array(); // Current element of the XML file we are parsing.
48   var $currentTag     = '';      // XML tag of the current element.
49
50   var $canImport      = true;    // False if we cannot import data due to a login collision.
51   var $firstPass      = true;    // True during first pass through the file.
52
53   // Constructor.
54   function ttImportHelper2(&$errors) {
55     $this->errors = &$errors;
56   }
57
58   // startElement - callback handler for opening tag of an XML element.
59   // In this function we assign passed in attributes to currentElement.
60   function startElement($parser, $name, $attrs) {
61     if ($name == 'GROUP'
62       || $name == 'USER') {
63       $this->currentElement = $attrs;
64     }
65     $this->currentTag = $name;
66   }
67
68   // endElement - callback handler for the closing tag of an XML element.
69   // When we are here, currentElement is an array of the element attributes (as set in startElement).
70   // Here we do the actual import of data into the database.
71   function endElement($parser, $name) {
72     // During first pass we only check user logins.
73     if ($this->firstPass) {
74       if ($name == 'USER' && $this->canImport) {
75         if ('' != $this->currentElement['STATUS'] && ttUserHelper::getUserByLogin($this->currentElement['LOGIN'])) {
76           // We have a login collision, cannot import any data.
77           $this->canImport = false;
78         }
79       }
80       $this->currentTag = '';
81     }
82
83     // During second pass we import data.
84     if (!$this->firstPass && $this->canImport) {
85       // TODO: write code here.
86     }
87   }
88
89   // dataElement - callback handler for text data fragments. It builds up currentElement array with text pieces from XML.
90   function dataElement($parser, $data) {
91     if ($this->currentTag == 'NAME'
92       || $this->currentTag == 'DESCRIPTION'
93       || $this->currentTag == 'LABEL'
94       || $this->currentTag == 'VALUE'
95       || $this->currentTag == 'COMMENT'
96       || $this->currentTag == 'ADDRESS'
97       || $this->currentTag == 'ALLOW_IP'
98       || $this->currentTag == 'PASSWORD_COMPLEXITY') {
99       if (isset($this->currentElement[$this->currentTag]))
100         $this->currentElement[$this->currentTag] .= trim($data);
101       else
102         $this->currentElement[$this->currentTag] = trim($data);
103     }
104   }
105
106   // importXml - uncompresses the file, reads and parses its content. During parsing,
107   // startElement, endElement, and dataElement functions are called as many times as necessary.
108   // Actual import occurs in the endElement handler.
109   function importXml() {
110     global $i18n;
111
112     // Do we have a compressed file?
113     $compressed = false;
114     $file_ext = substr($_FILES['xmlfile']['name'], strrpos($_FILES['xmlfile']['name'], '.') + 1);
115     if (in_array($file_ext, array('bz','tbz','bz2','tbz2'))) {
116       $compressed = true;
117     }
118
119     // Create a temporary file.
120     $dirName = dirname(TEMPLATE_DIR . '_c/.');
121     $filename = tempnam($dirName, 'import_');
122
123     // If the file is compressed - uncompress it.
124     if ($compressed) {
125       if (!$this->uncompress($_FILES['xmlfile']['tmp_name'], $filename)) {
126         $this->errors->add($i18n->get('error.sys'));
127         return;
128       }
129       unlink($_FILES['xmlfile']['tmp_name']);
130     } else {
131       if (!move_uploaded_file($_FILES['xmlfile']['tmp_name'], $filename)) {
132         $this->errors->add($i18n->get('error.upload'));
133         return;
134       }
135     }
136
137     // Initialize XML parser.
138     $parser = xml_parser_create();
139     xml_set_object($parser, $this);
140     xml_set_element_handler($parser, 'startElement', 'endElement');
141     xml_set_character_data_handler($parser, 'dataElement');
142
143     // We need to parse the file 2 times:
144     //   1) First pass: determine if import is possible - there must be no login collisions.
145     //   2) Second pass: if we can import, then do import in a second pass.
146     // This is different from earlier approach for single group import, where we could
147     // do both things in one pass because user info was in the beginning of XML file.
148     // Now, with subgroups, users can be located anywhere in the file.
149
150     // Read and parse the content of the file. During parsing, startElement, endElement, and dataElement functions are called.
151     $file = fopen($filename, 'r');
152     while ($data = fread($file, 4096)) {
153       if (!xml_parse($parser, $data, feof($file))) {
154         $this->errors->add(sprintf("XML error: %s at line %d",
155           xml_error_string(xml_get_error_code($parser)),
156           xml_get_current_line_number($parser)));
157       }
158       if (!$this->canImport) {
159         $this->errors->add($i18n->get('error.user_exists'));
160         break;
161       }
162     }
163     $this->firstPass = false; // We are done with 1st pass.
164     xml_parser_free($parser);
165     if ($file) fclose($file);
166     if (!$this->canImport) {
167       unlink($filename);
168       return;
169     }
170
171     // Now we can do a second pass, where real work is done.
172     $parser = xml_parser_create();
173     xml_set_object($parser, $this);
174     xml_set_element_handler($parser, 'startElement', 'endElement');
175     xml_set_character_data_handler($parser, 'dataElement');
176
177     // Read and parse the content of the file. During parsing, startElement, endElement, and dataElement functions are called.
178     $file = fopen($filename, 'r');
179     while ($data = fread($file, 4096)) {
180       if (!xml_parse($parser, $data, feof($file))) {
181         $this->errors->add(sprintf("XML error: %s at line %d",
182           xml_error_string(xml_get_error_code($parser)),
183           xml_get_current_line_number($parser)));
184       }
185     }
186     xml_parser_free($parser);
187     if ($file) fclose($file);
188     unlink($filename);
189   }
190
191   // uncompress - uncompresses the content of the $in file into the $out file.
192   function uncompress($in, $out) {
193     // Do we have the uncompress function?
194     if (!function_exists('bzopen'))
195       return false;
196
197     // Initial checks of file names and permissions.
198     if (!file_exists($in) || !is_readable ($in))
199       return false;
200     if ((!file_exists($out) && !is_writable(dirname($out))) || (file_exists($out) && !is_writable($out)))
201       return false;
202
203     if (!$out_file = fopen($out, 'wb'))
204       return false;
205     if (!$in_file = bzopen ($in, 'r'))
206       return false;
207
208     while (!feof($in_file)) {
209       $buffer = bzread($in_file, 4096);
210       fwrite($out_file, $buffer, 4096);
211     }
212     bzclose($in_file);
213     fclose ($out_file);
214     return true;
215   }
216 }