Some progress with writing new export.
[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('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 // ttOrgImportHelper - 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 ttOrgImportHelper {
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   var $org_id         = null;    // Organization id (same as top group_id).
54   var $current_parent_group_id = null; // Current parent group id as we parse the file.
55                                        // Set when we create a new group.
56
57   // Constructor.
58   function __construct(&$errors) {
59     $this->errors = &$errors;
60   }
61
62   // startElement - callback handler for opening tag of an XML element.
63   // In this function we assign passed in attributes to currentElement.
64   function startElement($parser, $name, $attrs) {
65     if ($name == 'GROUP'
66       || $name == 'USER') {
67       $this->currentElement = $attrs;
68     }
69     $this->currentTag = $name;
70
71     if (!$this->firstPass && $this->canImport) {
72       $mdb2 = getConnection();
73
74       // We are in second pass through the XML file and can import data.
75       if ($name == 'GROUP') {
76         // Create a new group.
77         $group_id = $this->createGroup(array(
78           'parent_id' => $this->current_parent_group_id,
79           'org_id' => $this->org_id,
80           'name' => $this->currentElement['NAME'],
81           'currency' => $this->currentElement['CURRENCY'],
82           'lang' => $this->currentElement['LANG']));
83         // We only have 3 properties in export at the moment, while work is ongoing...
84
85         // Special handling for top group.
86         if (!$this->org_id) {
87           $this->org_id = $group_id;
88           $sql = "update tt_groups set org_id = $group_id where org_id is NULL and id = $group_id";
89           $affected = $mdb2->exec($sql);
90           // TODO: design a better error handling approach for the entire import process.
91         }
92         // Set current parent group.
93         $this->current_parent_group_id = $group_id;
94       }
95     }
96   }
97
98   // endElement - callback handler for the closing tag of an XML element.
99   // When we are here, currentElement is an array of the element attributes (as set in startElement).
100   // Here we do the actual import of data into the database.
101   function endElement($parser, $name) {
102     // During first pass we only check user logins.
103     if ($this->firstPass) {
104       if ($name == 'USER' && $this->canImport) {
105         if ('' != $this->currentElement['STATUS'] && ttUserHelper::getUserByLogin($this->currentElement['LOGIN'])) {
106           // We have a login collision, cannot import any data.
107           $this->canImport = false;
108         }
109       }
110       $this->currentTag = '';
111     }
112
113     // During second pass we import data.
114     if (!$this->firstPass && $this->canImport) {
115       // Nothing is done here, see startElement for second pass.
116     }
117   }
118
119   // dataElement - callback handler for text data fragments. It builds up currentElement array with text pieces from XML.
120   function dataElement($parser, $data) {
121     if ($this->currentTag == 'NAME'
122       || $this->currentTag == 'DESCRIPTION'
123       || $this->currentTag == 'LABEL'
124       || $this->currentTag == 'VALUE'
125       || $this->currentTag == 'COMMENT'
126       || $this->currentTag == 'ADDRESS'
127       || $this->currentTag == 'ALLOW_IP'
128       || $this->currentTag == 'PASSWORD_COMPLEXITY') {
129       if (isset($this->currentElement[$this->currentTag]))
130         $this->currentElement[$this->currentTag] .= trim($data);
131       else
132         $this->currentElement[$this->currentTag] = trim($data);
133     }
134   }
135
136   // importXml - uncompresses the file, reads and parses its content. During parsing,
137   // startElement, endElement, and dataElement functions are called as many times as necessary.
138   // Actual import occurs in the endElement handler.
139   function importXml() {
140     global $i18n;
141
142     // Do we have a compressed file?
143     $compressed = false;
144     $file_ext = substr($_FILES['xmlfile']['name'], strrpos($_FILES['xmlfile']['name'], '.') + 1);
145     if (in_array($file_ext, array('bz','tbz','bz2','tbz2'))) {
146       $compressed = true;
147     }
148
149     // Create a temporary file.
150     $dirName = dirname(TEMPLATE_DIR . '_c/.');
151     $filename = tempnam($dirName, 'import_');
152
153     // If the file is compressed - uncompress it.
154     if ($compressed) {
155       if (!$this->uncompress($_FILES['xmlfile']['tmp_name'], $filename)) {
156         $this->errors->add($i18n->get('error.sys'));
157         return;
158       }
159       unlink($_FILES['xmlfile']['tmp_name']);
160     } else {
161       if (!move_uploaded_file($_FILES['xmlfile']['tmp_name'], $filename)) {
162         $this->errors->add($i18n->get('error.upload'));
163         return;
164       }
165     }
166
167     // Initialize XML parser.
168     $parser = xml_parser_create();
169     xml_set_object($parser, $this);
170     xml_set_element_handler($parser, 'startElement', 'endElement');
171     xml_set_character_data_handler($parser, 'dataElement');
172
173     // We need to parse the file 2 times:
174     //   1) First pass: determine if import is possible - there must be no login collisions.
175     //   2) Second pass: if we can import, then do import in a second pass.
176     // This is different from earlier approach for single group import, where we could
177     // do both things in one pass because user info was in the beginning of XML file.
178     // Now, with subgroups, users can be located anywhere in the file.
179
180     // Read and parse the content of the file. During parsing, startElement, endElement, and dataElement functions are called.
181     $file = fopen($filename, 'r');
182     while ($data = fread($file, 4096)) {
183       if (!xml_parse($parser, $data, feof($file))) {
184         $this->errors->add(sprintf("XML error: %s at line %d",
185           xml_error_string(xml_get_error_code($parser)),
186           xml_get_current_line_number($parser)));
187       }
188       if (!$this->canImport) {
189         $this->errors->add($i18n->get('error.user_exists'));
190         break;
191       }
192     }
193     $this->firstPass = false; // We are done with 1st pass.
194     xml_parser_free($parser);
195     if ($file) fclose($file);
196     if (!$this->canImport) {
197       unlink($filename);
198       return;
199     }
200
201     // Now we can do a second pass, where real work is done.
202     $parser = xml_parser_create();
203     xml_set_object($parser, $this);
204     xml_set_element_handler($parser, 'startElement', 'endElement');
205     xml_set_character_data_handler($parser, 'dataElement');
206
207     // Read and parse the content of the file. During parsing, startElement, endElement, and dataElement functions are called.
208     $file = fopen($filename, 'r');
209     while ($data = fread($file, 4096)) {
210       if (!xml_parse($parser, $data, feof($file))) {
211         $this->errors->add(sprintf("XML error: %s at line %d",
212           xml_error_string(xml_get_error_code($parser)),
213           xml_get_current_line_number($parser)));
214       }
215     }
216     xml_parser_free($parser);
217     if ($file) fclose($file);
218     unlink($filename);
219   }
220
221   // uncompress - uncompresses the content of the $in file into the $out file.
222   function uncompress($in, $out) {
223     // Do we have the uncompress function?
224     if (!function_exists('bzopen'))
225       return false;
226
227     // Initial checks of file names and permissions.
228     if (!file_exists($in) || !is_readable ($in))
229       return false;
230     if ((!file_exists($out) && !is_writable(dirname($out))) || (file_exists($out) && !is_writable($out)))
231       return false;
232
233     if (!$out_file = fopen($out, 'wb'))
234       return false;
235     if (!$in_file = bzopen ($in, 'r'))
236       return false;
237
238     while (!feof($in_file)) {
239       $buffer = bzread($in_file, 4096);
240       fwrite($out_file, $buffer, 4096);
241     }
242     bzclose($in_file);
243     fclose ($out_file);
244     return true;
245   }
246
247   // createGroup function creates a new group.
248   private function createGroup($fields) {
249
250     global $user;
251     $mdb2 = getConnection();
252
253     $columns = '(parent_id, org_id, name, currency, lang)';
254
255 //    $columns = '(name, currency, decimal_mark, lang, date_format, time_format, week_start, tracking_mode'.
256 //      ', project_required, task_required, record_type, bcc_email, allow_ip, password_complexity, plugins'.
257 //      ', lock_spec, workday_minutes, config, created, created_ip, created_by)';
258
259     $values = ' values (';
260     $values .= $mdb2->quote($fields['parent_id']);
261     $values .= ', '.$mdb2->quote($fields['org_id']);
262     $values .= ', '.$mdb2->quote(trim($fields['name']));
263     $values .= ', '.$mdb2->quote(trim($fields['currency']));
264     //$values .= ', '.$mdb2->quote($fields['decimal_mark']);
265     $values .= ', '.$mdb2->quote($fields['lang']);
266 /*
267     $values .= ', '.$mdb2->quote($fields['date_format']);
268     $values .= ', '.$mdb2->quote($fields['time_format']);
269     $values .= ', '.(int)$fields['week_start'];
270     $values .= ', '.(int)$fields['tracking_mode'];
271     $values .= ', '.(int)$fields['project_required'];
272     $values .= ', '.(int)$fields['task_required'];
273     $values .= ', '.(int)$fields['record_type'];
274     $values .= ', '.$mdb2->quote($fields['bcc_email']);
275     $values .= ', '.$mdb2->quote($fields['allow_ip']);
276     $values .= ', '.$mdb2->quote($fields['password_complexity']);
277     $values .= ', '.$mdb2->quote($fields['plugins']);
278     $values .= ', '.$mdb2->quote($fields['lock_spec']);
279     $values .= ', '.(int)$fields['workday_minutes'];
280     $values .= ', '.$mdb2->quote($fields['config']);
281     $values .= ', now(), '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', '.$mdb2->quote($user->id); */
282     $values .= ')';
283
284     $sql = 'insert into tt_groups '.$columns.$values;
285     $affected = $mdb2->exec($sql);
286     if (is_a($affected, 'PEAR_Error')) return false;
287
288     $group_id = $mdb2->lastInsertID('tt_groups', 'id');
289     return $group_id;
290   }
291 }