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