Improved new export-import by including all group attributes.
[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   var $top_role_id    = 0;       // Top role id.
48
49   // Entity maps for current group. They map XML ids with database ids.
50   var $currentGroupRoleMap    = array();
51   var $currentGroupTaskMap    = array();
52   var $currentGroupProjectMap = array();
53   var $currentGroupClientMap  = array();
54   var $currentGroupUserMap    = array();
55
56   // Constructor.
57   function __construct(&$errors) {
58     $this->errors = &$errors;
59     $this->top_role_id = ttRoleHelper::getRoleByRank(512, 0);
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           'decimal_mark' => $attrs['DECIMAL_MARK'],
90           'lang' => $attrs['LANG'],
91           'date_format' => $attrs['DATE_FORMAT'],
92           'time_format' => $attrs['TIME_FORMAT'],
93           'week_start' => $attrs['WEEK_START'],
94           'tracking_mode' => $attrs['TRACKING_MODE'],
95           'project_required' => $attrs['PROJECT_REQUIRED'],
96           'task_required' => $attrs['TASK_REQUIRED'],
97           'record_type' => $attrs['RECORD_TYPE'],
98           'bcc_email' => $attrs['BCC_EMAIL'],
99           'allow_ip' => $attrs['ALLOW_IP'],
100           'password_complexity' => $attrs['PASSWORD_COMPLEXITY'],
101           'plugins' => $attrs['PLUGINS'],
102           'lock_spec' => $attrs['LOCK_SPEC'],
103           'workday_minutes' => $attrs['WORKDAY_MINUTES'],
104           'custom_logo' => $attrs['CUSTOM_LOGO'],
105           'config' => $attrs['CONFIG']));
106
107         // Special handling for top group.
108         if (!$this->org_id && $this->current_group_id) {
109           $this->org_id = $this->current_group_id;
110           $sql = "update tt_groups set org_id = $this->current_group_id where org_id is NULL and id = $this->current_group_id";
111           $affected = $mdb2->exec($sql);
112         }
113         // Set parent group to create subgroups with this group as parent at next entry here.
114         $this->current_parent_group_id = $this->current_group_id;
115       }
116
117       if ($name == 'ROLES') {
118         // If we get here, we have to recycle $currentGroupRoleMap.
119         unset($this->currentGroupRoleMap);
120         $this->currentGroupRoleMap = array();
121         // Role map is reconstructed after processing <role> elements in XML. See below.
122       }
123
124       if ($name == 'ROLE') {
125         // We get here when processing <role> tags for the current group.
126         $role_id = ttRoleHelper::insert(array(
127               'group_id' => $this->current_group_id,
128               'org_id' => $this->org_id,
129               'name' => $attrs['NAME'],
130               'description' => $attrs['DESCRIPTION'],
131               'rank' => $attrs['RANK'],
132               'rights' => $attrs['RIGHTS'],
133               'status' => $attrs['STATUS']));
134         if ($role_id) {
135           // Add a mapping.
136           $this->currentGroupRoleMap[$attrs['ID']] = $role_id;
137         } else $this->errors->add($i18n->get('error.db'));
138       }
139
140       if ($name == 'TASKS') {
141         // If we get here, we have to recycle $currentGroupTaskMap.
142         unset($this->currentGroupTaskMap);
143         $this->currentGroupTaskMap = array();
144         // Task map is reconstructed after processing <task> elements in XML. See below.
145       }
146
147       if ($name == 'TASK') {
148         // We get here when processing <task> tags for the current group.
149         $task_id = ttTaskHelper::insert(array(
150           'group_id' => $this->current_group_id,
151           'org_id' => $this->org_id,
152           'name' => $attrs['NAME'],
153           'description' => $attrs['DESCRIPTION'],
154           'status' => $attrs['STATUS']));
155         if ($task_id) {
156           // Add a mapping.
157           $this->currentGroupTaskMap[$attrs['ID']] = $task_id;
158         } else $this->errors->add($i18n->get('error.db'));
159       }
160
161       if ($name == 'PROJECTS') {
162         // If we get here, we have to recycle $currentGroupProjectMap.
163         unset($this->currentGroupProjectMap);
164         $this->currentGroupProjectMap = array();
165         // Project map is reconstructed after processing <project> elements in XML. See below.
166       }
167
168       if ($name == 'PROJECT') {
169         // We get here when processing <project> tags for the current group.
170
171         // Prepare a list of task ids.
172         $tasks = explode(',', $attrs['TASKS']);
173         foreach ($tasks as $id)
174           $mapped_tasks[] = $this->currentGroupTaskMap[$id];
175
176         $project_id = ttProjectHelper::insert(array(
177           'group_id' => $this->current_group_id,
178           'org_id' => $this->org_id,
179           'name' => $attrs['NAME'],
180           'description' => $attrs['DESCRIPTION'],
181           'tasks' => $mapped_tasks,
182           'status' => $attrs['STATUS']));
183         if ($project_id) {
184           // Add a mapping.
185           $this->currentGroupProjectMap[$attrs['ID']] = $project_id;
186         } else $this->errors->add($i18n->get('error.db'));
187       }
188
189       if ($name == 'CLIENTS') {
190         // If we get here, we have to recycle $currentGroupClientMap.
191         unset($this->currentGroupClientMap);
192         $this->currentGroupClientMap = array();
193         // Client map is reconstructed after processing <client> elements in XML. See below.
194       }
195
196       if ($name == 'CLIENT') {
197         // We get here when processing <client> tags for the current group.
198
199         // Prepare a list of project ids.
200         $projects = explode(',', $attrs['PROJECTS']);
201         foreach ($projects as $id)
202           $mapped_projects[] = $this->currentGroupProjectMap[$id];
203
204         $client_id = ttClientHelper::insert(array(
205           'group_id' => $this->current_group_id,
206           'org_id' => $this->org_id,
207           'name' => $attrs['NAME'],
208           'address' => $attrs['ADDRESS'],
209           'tax' => $attrs['TAX'],
210           'projects' => $mapped_projects,
211           'status' => $attrs['STATUS']));
212         if ($client_id) {
213           // Add a mapping.
214           $this->currentGroupClientMap[$attrs['ID']] = $client_id;
215         } else $this->errors->add($i18n->get('error.db'));
216       }
217
218       if ($name == 'USERS') {
219         // If we get here, we have to recycle $currentGroupUserMap.
220         unset($this->currentGroupUserMap);
221         $this->currentGroupUserMap = array();
222         // User map is reconstructed after processing <user> elements in XML. See below.
223       }
224
225       if ($name == 'USER') {
226         // We get here when processing <user> tags for the current group.
227
228         $role_id = $attrs['ROLE_ID'] === '0' ? $this->top_role_id :  $this->currentGroupRoleMap[$attrs['ROLE_ID']]; // 0 (not null) means top manager role.
229
230         $user_id = ttUserHelper::insert(array(
231           'group_id' => $this->current_group_id,
232           'org_id' => $this->org_id,
233           'role_id' => $role_id,
234           'client_id' => $this->currentGroupClientMap[$attrs['CLIENT_ID']],
235           'name' => $attrs['NAME'],
236           'login' => $attrs['LOGIN'],
237           'password' => $attrs['PASSWORD'],
238           'rate' => $attrs['RATE'],
239           'email' => $attrs['EMAIL'],
240           'status' => $attrs['STATUS']), false);
241         // TODO: what about created_by and other audit info?
242         if ($user_id) {
243           // Add a mapping.
244           $this->currentGroupUserMap[$attrs['ID']] = $user_id;
245         } else $this->errors->add($i18n->get('error.db'));
246       }
247     }
248   }
249
250   // importXml - uncompresses the file, reads and parses its content. During parsing,
251   // startElement, endElement, and dataElement functions are called as many times as necessary.
252   // Actual import occurs in the endElement handler.
253   function importXml() {
254     global $i18n;
255
256     // Do we have a compressed file?
257     $compressed = false;
258     $file_ext = substr($_FILES['xmlfile']['name'], strrpos($_FILES['xmlfile']['name'], '.') + 1);
259     if (in_array($file_ext, array('bz','tbz','bz2','tbz2'))) {
260       $compressed = true;
261     }
262
263     // Create a temporary file.
264     $dirName = dirname(TEMPLATE_DIR . '_c/.');
265     $filename = tempnam($dirName, 'import_');
266
267     // If the file is compressed - uncompress it.
268     if ($compressed) {
269       if (!$this->uncompress($_FILES['xmlfile']['tmp_name'], $filename)) {
270         $this->errors->add($i18n->get('error.sys'));
271         return;
272       }
273       unlink($_FILES['xmlfile']['tmp_name']);
274     } else {
275       if (!move_uploaded_file($_FILES['xmlfile']['tmp_name'], $filename)) {
276         $this->errors->add($i18n->get('error.upload'));
277         return;
278       }
279     }
280
281     // Initialize XML parser.
282     $parser = xml_parser_create();
283     xml_set_object($parser, $this);
284     xml_set_element_handler($parser, 'startElement', false);
285
286     // We need to parse the file 2 times:
287     //   1) First pass: determine if import is possible - there must be no login collisions.
288     //   2) Second pass: if we can import, then do import in a second pass.
289     // This is different from earlier approach for single group import, where we could
290     // do both things in one pass because user info was in the beginning of XML file.
291     // Now, with subgroups, users can be located anywhere in the file.
292
293     // Read and parse the content of the file. During parsing, startElement, endElement, and dataElement functions are called.
294     $file = fopen($filename, 'r');
295     while ($data = fread($file, 4096)) {
296       if (!xml_parse($parser, $data, feof($file))) {
297         $this->errors->add(sprintf($i18n->get('error.xml'),
298           xml_get_current_line_number($parser),
299           xml_error_string(xml_get_error_code($parser))));
300       }
301     }
302     if ($this->conflicting_entities) {
303       $this->canImport = false;
304       $this->errors->add($i18n->get('error.user_exists'));
305       $this->errors->add(sprintf($i18n->get('error.cannot_import'), $this->conflicting_entities));
306     }
307
308     $this->firstPass = false; // We are done with 1st pass.
309     xml_parser_free($parser);
310     if ($file) fclose($file);
311     if (!$this->canImport) {
312       unlink($filename);
313       return;
314     }
315     if ($this->errors->yes()) return; // Exit if we have errors.
316
317     // Now we can do a second pass, where real work is done.
318     $parser = xml_parser_create();
319     xml_set_object($parser, $this);
320     xml_set_element_handler($parser, 'startElement', false);
321
322     // Read and parse the content of the file. During parsing, startElement, endElement, and dataElement functions are called.
323     $file = fopen($filename, 'r');
324     while ($data = fread($file, 4096)) {
325       if (!xml_parse($parser, $data, feof($file))) {
326         $this->errors->add(sprintf($i18n->get('error.xml'),
327           xml_get_current_line_number($parser),
328           xml_error_string(xml_get_error_code($parser))));
329       }
330     }
331     xml_parser_free($parser);
332     if ($file) fclose($file);
333     unlink($filename);
334   }
335
336   // uncompress - uncompresses the content of the $in file into the $out file.
337   function uncompress($in, $out) {
338     // Do we have the uncompress function?
339     if (!function_exists('bzopen'))
340       return false;
341
342     // Initial checks of file names and permissions.
343     if (!file_exists($in) || !is_readable ($in))
344       return false;
345     if ((!file_exists($out) && !is_writable(dirname($out))) || (file_exists($out) && !is_writable($out)))
346       return false;
347
348     if (!$out_file = fopen($out, 'wb'))
349       return false;
350     if (!$in_file = bzopen ($in, 'r'))
351       return false;
352
353     while (!feof($in_file)) {
354       $buffer = bzread($in_file, 4096);
355       fwrite($out_file, $buffer, 4096);
356     }
357     bzclose($in_file);
358     fclose ($out_file);
359     return true;
360   }
361
362   // createGroup function creates a new group.
363   private function createGroup($fields) {
364     global $user;
365     global $i18n;
366     $mdb2 = getConnection();
367
368     $columns = '(parent_id, org_id, name, currency, decimal_mark, lang, date_format, time_format'.
369       ', week_start, tracking_mode, project_required, task_required, record_type, bcc_email'.
370       ', allow_ip, password_complexity, plugins, lock_spec'.
371       ', workday_minutes, config, created, created_ip, created_by)';
372
373     $values = ' values (';
374     $values .= $mdb2->quote($fields['parent_id']);
375     $values .= ', '.$mdb2->quote($fields['org_id']);
376     $values .= ', '.$mdb2->quote(trim($fields['name']));
377     $values .= ', '.$mdb2->quote(trim($fields['currency']));
378     $values .= ', '.$mdb2->quote($fields['decimal_mark']);
379     $values .= ', '.$mdb2->quote($fields['lang']);
380     $values .= ', '.$mdb2->quote($fields['date_format']);
381     $values .= ', '.$mdb2->quote($fields['time_format']);
382     $values .= ', '.(int)$fields['week_start'];
383     $values .= ', '.(int)$fields['tracking_mode'];
384     $values .= ', '.(int)$fields['project_required'];
385     $values .= ', '.(int)$fields['task_required'];
386     $values .= ', '.(int)$fields['record_type'];
387     $values .= ', '.$mdb2->quote($fields['bcc_email']);
388     $values .= ', '.$mdb2->quote($fields['allow_ip']);
389     $values .= ', '.$mdb2->quote($fields['password_complexity']);
390     $values .= ', '.$mdb2->quote($fields['plugins']);
391     $values .= ', '.$mdb2->quote($fields['lock_spec']);
392     $values .= ', '.(int)$fields['workday_minutes'];
393     $values .= ', '.$mdb2->quote($fields['config']);
394     $values .= ', now(), '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', '.$mdb2->quote($user->id);
395     $values .= ')';
396
397     $sql = 'insert into tt_groups '.$columns.$values;
398     $affected = $mdb2->exec($sql);
399     if (is_a($affected, 'PEAR_Error')) {
400       $this->errors->add($i18n->get('error.db'));
401       return false;
402     }
403
404     $group_id = $mdb2->lastInsertID('tt_groups', 'id');
405     return $group_id;
406   }
407 }