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