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