Improved new import with integrating clients.
[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
35 // ttOrgImportHelper - this class is a future replacement for ttImportHelper.
36 // Currently, it is work in progress.
37 // When done, it should handle import of complex groups consisting of other groups.
38 class ttOrgImportHelper {
39   var $errors               = null; // Errors go here. Set in constructor by reference.
40   var $conflicting_entities = null; // A comma-separated list of entity names we cannot import.
41   var $canImport      = true;    // False if we cannot import data due to a conflict such as login collision.
42   var $firstPass      = true;    // True during first pass through the file.
43   var $org_id         = null;    // Organization id (same as top group_id).
44   var $current_group_id        = null; // Current group id during parsing.
45   var $current_parent_group_id = null; // Current parent group id during parsing.
46                                        // Set when we create a new group.
47   // Entities for current group. -- Looks like they are not needed as we insert right away...
48   // var $currentGroupRoles = array(); // Array of arrays of role properties.
49   // var $currentGroupUsers = array(); // Array of arrays of user properties.
50
51   // Entity maps for current group. They map XML ids with database ids.
52   var $currentGroupRoleMap    = array();
53   var $currentGroupTaskMap    = array();
54   var $currentGroupProjectMap = array();
55   var $currentGroupClientMap  = array();
56
57   // Constructor.
58   function __construct(&$errors) {
59     $this->errors = &$errors;
60   }
61
62   // startElement - callback handler for opening tag of an XML element in the file.
63   function startElement($parser, $name, $attrs) {
64     global $i18n;
65
66     // First pass. We only check user logins for potential collisions with existing.
67     if ($this->firstPass) {
68       if ($name == 'USER' && $this->canImport) {
69         $login = $attrs['LOGIN'];
70         if ('' != $attrs['STATUS'] && ttUserHelper::getUserByLogin($login)) {
71           // We have a login collision. Append colliding login to a list of things we cannot import.
72           $this->conflicting_entities .= ($this->conflicting_entities ? ", $login" : $login);
73         }
74       }
75     }
76
77     // Second pass processing. We import data here, one tag at a time.
78     if (!$this->firstPass && $this->canImport && $this->errors->no()) {
79       $mdb2 = getConnection();
80
81       // We are in second pass and can import data.
82       if ($name == 'GROUP') {
83         // Create a new group.
84         $this->current_group_id = $this->createGroup(array(
85           'parent_id' => $this->current_parent_group_id,
86           'org_id' => $this->org_id,
87           'name' => $attrs['NAME'],
88           'currency' => $attrs['CURRENCY'],
89           'lang' => $attrs['LANG']));
90         // We only have 3 properties at the moment, while work is ongoing...
91
92         // Special handling for top group.
93         if (!$this->org_id && $this->current_group_id) {
94           $this->org_id = $this->current_group_id;
95           $sql = "update tt_groups set org_id = $this->current_group_id where org_id is NULL and id = $this->current_group_id";
96           $affected = $mdb2->exec($sql);
97         }
98         // Set parent group to create subgroups with this group as parent at next entry here.
99         $this->current_parent_group_id = $this->current_group_id;
100       }
101
102       if ($name == 'ROLES') {
103         // If we get here, we have to recycle $currentGroupRoleMap.
104         unset($this->currentGroupRoleMap);
105         $this->currentGroupRoleMap = array();
106         // Role map is reconstructed after processing <role> elements in XML. See below.
107       }
108
109       if ($name == 'ROLE') {
110         // We get here when processing <role> tags for the current group.
111         $role_id = ttRoleHelper::insert(array(
112               'group_id' => $this->current_group_id,
113               'org_id' => $this->org_id,
114               'name' => $attrs['NAME'],
115               'description' => $attrs['DESCRIPTION'],
116               'rank' => $attrs['RANK'],
117               'rights' => $attrs['RIGHTS'],
118               'status' => $attrs['STATUS']));
119         if ($role_id) {
120           // Add a mapping.
121           $this->currentGroupRoleMap[$attrs['ID']] = $role_id;
122         } else $this->errors->add($i18n->get('error.db'));
123       }
124
125       if ($name == 'TASKS') {
126         // If we get here, we have to recycle $currentGroupTaskMap.
127         unset($this->currentGroupTaskMap);
128         $this->currentGroupTaskMap = array();
129         // Task map is reconstructed after processing <task> elements in XML. See below.
130       }
131
132       if ($name == 'TASK') {
133         // We get here when processing <task> tags for the current group.
134         $task_id = ttTaskHelper::insert(array(
135           'group_id' => $this->current_group_id,
136           'org_id' => $this->org_id,
137           'name' => $attrs['NAME'],
138           'description' => $attrs['DESCRIPTION'],
139           'status' => $attrs['STATUS']));
140         if ($task_id) {
141           // Add a mapping.
142           $this->currentGroupTaskMap[$attrs['ID']] = $task_id;
143         } else $this->errors->add($i18n->get('error.db'));
144       }
145
146       if ($name == 'PROJECTS') {
147         // If we get here, we have to recycle $currentGroupProjectMap.
148         unset($this->currentGroupProjectMap);
149         $this->currentGroupProjectMap = array();
150         // Project map is reconstructed after processing <project> elements in XML. See below.
151       }
152
153       if ($name == 'PROJECT') {
154         // We get here when processing <project> tags for the current group.
155
156         // Prepare a list of task ids.
157         $tasks = explode(',', $attrs['TASKS']);
158         foreach ($tasks as $id)
159           $mapped_tasks[] = $this->currentGroupTaskMap[$id];
160
161         $project_id = ttProjectHelper::insert(array(
162           'group_id' => $this->current_group_id,
163           'org_id' => $this->org_id,
164           'name' => $attrs['NAME'],
165           'description' => $attrs['DESCRIPTION'],
166           'tasks' => $mapped_tasks,
167           'status' => $attrs['STATUS']));
168         if ($project_id) {
169           // Add a mapping.
170           $this->currentGroupProjectMap[$attrs['ID']] = $project_id;
171         } else $this->errors->add($i18n->get('error.db'));
172       }
173
174       if ($name == 'CLIENTS') {
175         // If we get here, we have to recycle $currentGroupClientMap.
176         unset($this->currentGroupClientMap);
177         $this->currentGroupClientMap = array();
178         // Client map is reconstructed after processing <client> elements in XML. See below.
179       }
180
181       if ($name == 'CLIENT') {
182         // We get here when processing <client> tags for the current group.
183
184         // Prepare a list of project ids.
185         $projects = explode(',', $attrs['PROJECTS']);
186         foreach ($projects as $id)
187           $mapped_projects[] = $this->currentGroupProjectMap[$id];
188
189         $client_id = ttClientHelper::insert(array(
190           'group_id' => $this->current_group_id,
191           'org_id' => $this->org_id,
192           'name' => $attrs['NAME'],
193           'address' => $attrs['ADDRESS'],
194           'tax' => $attrs['TAX'],
195           'projects' => $mapped_projects,
196           'status' => $attrs['STATUS']));
197         if ($client_id) {
198           // Add a mapping.
199           $this->currentGroupClientMap[$attrs['ID']] = $client_id;
200         } else $this->errors->add($i18n->get('error.db'));
201       }
202     }
203   }
204
205   // importXml - uncompresses the file, reads and parses its content. During parsing,
206   // startElement, endElement, and dataElement functions are called as many times as necessary.
207   // Actual import occurs in the endElement handler.
208   function importXml() {
209     global $i18n;
210
211     // Do we have a compressed file?
212     $compressed = false;
213     $file_ext = substr($_FILES['xmlfile']['name'], strrpos($_FILES['xmlfile']['name'], '.') + 1);
214     if (in_array($file_ext, array('bz','tbz','bz2','tbz2'))) {
215       $compressed = true;
216     }
217
218     // Create a temporary file.
219     $dirName = dirname(TEMPLATE_DIR . '_c/.');
220     $filename = tempnam($dirName, 'import_');
221
222     // If the file is compressed - uncompress it.
223     if ($compressed) {
224       if (!$this->uncompress($_FILES['xmlfile']['tmp_name'], $filename)) {
225         $this->errors->add($i18n->get('error.sys'));
226         return;
227       }
228       unlink($_FILES['xmlfile']['tmp_name']);
229     } else {
230       if (!move_uploaded_file($_FILES['xmlfile']['tmp_name'], $filename)) {
231         $this->errors->add($i18n->get('error.upload'));
232         return;
233       }
234     }
235
236     // Initialize XML parser.
237     $parser = xml_parser_create();
238     xml_set_object($parser, $this);
239     xml_set_element_handler($parser, 'startElement', false);
240
241     // We need to parse the file 2 times:
242     //   1) First pass: determine if import is possible - there must be no login collisions.
243     //   2) Second pass: if we can import, then do import in a second pass.
244     // This is different from earlier approach for single group import, where we could
245     // do both things in one pass because user info was in the beginning of XML file.
246     // Now, with subgroups, users can be located anywhere in the file.
247
248     // Read and parse the content of the file. During parsing, startElement, endElement, and dataElement functions are called.
249     $file = fopen($filename, 'r');
250     while ($data = fread($file, 4096)) {
251       if (!xml_parse($parser, $data, feof($file))) {
252         $this->errors->add(sprintf($i18n->get('error.xml'),
253           xml_get_current_line_number($parser),
254           xml_error_string(xml_get_error_code($parser))));
255       }
256     }
257     if ($this->conflicting_entities) {
258       $this->canImport = false;
259       $this->errors->add($i18n->get('error.user_exists'));
260       $this->errors->add(sprintf($i18n->get('error.cannot_import'), $this->conflicting_entities));
261     }
262
263     $this->firstPass = false; // We are done with 1st pass.
264     xml_parser_free($parser);
265     if ($file) fclose($file);
266     if (!$this->canImport) {
267       unlink($filename);
268       return;
269     }
270     if ($this->errors->yes()) return; // Exit if we have errors.
271
272     // Now we can do a second pass, where real work is done.
273     $parser = xml_parser_create();
274     xml_set_object($parser, $this);
275     xml_set_element_handler($parser, 'startElement', false);
276
277     // Read and parse the content of the file. During parsing, startElement, endElement, and dataElement functions are called.
278     $file = fopen($filename, 'r');
279     while ($data = fread($file, 4096)) {
280       if (!xml_parse($parser, $data, feof($file))) {
281         $this->errors->add(sprintf($i18n->get('error.xml'),
282           xml_get_current_line_number($parser),
283           xml_error_string(xml_get_error_code($parser))));
284       }
285     }
286     xml_parser_free($parser);
287     if ($file) fclose($file);
288     unlink($filename);
289   }
290
291   // uncompress - uncompresses the content of the $in file into the $out file.
292   function uncompress($in, $out) {
293     // Do we have the uncompress function?
294     if (!function_exists('bzopen'))
295       return false;
296
297     // Initial checks of file names and permissions.
298     if (!file_exists($in) || !is_readable ($in))
299       return false;
300     if ((!file_exists($out) && !is_writable(dirname($out))) || (file_exists($out) && !is_writable($out)))
301       return false;
302
303     if (!$out_file = fopen($out, 'wb'))
304       return false;
305     if (!$in_file = bzopen ($in, 'r'))
306       return false;
307
308     while (!feof($in_file)) {
309       $buffer = bzread($in_file, 4096);
310       fwrite($out_file, $buffer, 4096);
311     }
312     bzclose($in_file);
313     fclose ($out_file);
314     return true;
315   }
316
317   // createGroup function creates a new group.
318   private function createGroup($fields) {
319
320     global $i18n;
321     $mdb2 = getConnection();
322
323     $columns = '(parent_id, org_id, name, currency, lang)';
324
325 //    $columns = '(name, currency, decimal_mark, lang, date_format, time_format, week_start, tracking_mode'.
326 //      ', project_required, task_required, record_type, bcc_email, allow_ip, password_complexity, plugins'.
327 //      ', lock_spec, workday_minutes, config, created, created_ip, created_by)';
328
329     $values = ' values (';
330     $values .= $mdb2->quote($fields['parent_id']);
331     $values .= ', '.$mdb2->quote($fields['org_id']);
332     $values .= ', '.$mdb2->quote(trim($fields['name']));
333     $values .= ', '.$mdb2->quote(trim($fields['currency']));
334     //$values .= ', '.$mdb2->quote($fields['decimal_mark']);
335     $values .= ', '.$mdb2->quote($fields['lang']);
336 /*
337     $values .= ', '.$mdb2->quote($fields['date_format']);
338     $values .= ', '.$mdb2->quote($fields['time_format']);
339     $values .= ', '.(int)$fields['week_start'];
340     $values .= ', '.(int)$fields['tracking_mode'];
341     $values .= ', '.(int)$fields['project_required'];
342     $values .= ', '.(int)$fields['task_required'];
343     $values .= ', '.(int)$fields['record_type'];
344     $values .= ', '.$mdb2->quote($fields['bcc_email']);
345     $values .= ', '.$mdb2->quote($fields['allow_ip']);
346     $values .= ', '.$mdb2->quote($fields['password_complexity']);
347     $values .= ', '.$mdb2->quote($fields['plugins']);
348     $values .= ', '.$mdb2->quote($fields['lock_spec']);
349     $values .= ', '.(int)$fields['workday_minutes'];
350     $values .= ', '.$mdb2->quote($fields['config']);
351     $values .= ', now(), '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', '.$mdb2->quote($user->id); */
352     $values .= ')';
353
354     $sql = 'insert into tt_groups '.$columns.$values;
355     $affected = $mdb2->exec($sql);
356     if (is_a($affected, 'PEAR_Error')) {
357       $this->errors->add($i18n->get('error.db'));
358       return false;
359     }
360
361     $group_id = $mdb2->lastInsertID('tt_groups', 'id');
362     return $group_id;
363   }
364 }