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