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