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.
11 // | There are only two ways to violate the license:
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).
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).
21 // | This license applies to this document only, not any other software
22 // | that it may be combined with.
24 // +----------------------------------------------------------------------+
26 // | https://www.anuko.com/time_tracker/credits.htm
27 // +----------------------------------------------------------------------+
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');
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.
47 var $currentElement = array(); // Current element of the XML file we are parsing.
48 var $currentTag = ''; // XML tag of the current element.
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.
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.
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.
69 function __construct(&$errors) {
70 $this->errors = &$errors;
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) {
79 $this->currentElement = $attrs;
81 $this->currentTag = $name;
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;
91 //$this->currentTag = '';
94 // Second pass processing. We import data here, one tag at a time.
95 if (!$this->firstPass && $this->canImport) {
96 $mdb2 = getConnection();
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...
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.
116 // Set current parent group.
117 $this->current_parent_group_id = $group_id;
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.
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();
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.
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;
153 $this->currentTag = '';
156 // During second pass we import data.
157 if (!$this->firstPass && $this->canImport) {
158 // Nothing is done here, see startElement for second pass.
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).
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);
177 $this->currentElement[$this->currentTag] = trim($data);
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() {
188 // Do we have a compressed file?
190 $file_ext = substr($_FILES['xmlfile']['name'], strrpos($_FILES['xmlfile']['name'], '.') + 1);
191 if (in_array($file_ext, array('bz','tbz','bz2','tbz2'))) {
195 // Create a temporary file.
196 $dirName = dirname(TEMPLATE_DIR . '_c/.');
197 $filename = tempnam($dirName, 'import_');
199 // If the file is compressed - uncompress it.
201 if (!$this->uncompress($_FILES['xmlfile']['tmp_name'], $filename)) {
202 $this->errors->add($i18n->get('error.sys'));
205 unlink($_FILES['xmlfile']['tmp_name']);
207 if (!move_uploaded_file($_FILES['xmlfile']['tmp_name'], $filename)) {
208 $this->errors->add($i18n->get('error.upload'));
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');
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.
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)));
234 if (!$this->canImport) {
235 $this->errors->add($i18n->get('error.user_exists'));
239 $this->firstPass = false; // We are done with 1st pass.
240 xml_parser_free($parser);
241 if ($file) fclose($file);
242 if (!$this->canImport) {
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');
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)));
262 xml_parser_free($parser);
263 if ($file) fclose($file);
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'))
273 // Initial checks of file names and permissions.
274 if (!file_exists($in) || !is_readable ($in))
276 if ((!file_exists($out) && !is_writable(dirname($out))) || (file_exists($out) && !is_writable($out)))
279 if (!$out_file = fopen($out, 'wb'))
281 if (!$in_file = bzopen ($in, 'r'))
284 while (!feof($in_file)) {
285 $buffer = bzread($in_file, 4096);
286 fwrite($out_file, $buffer, 4096);
293 // createGroup function creates a new group.
294 private function createGroup($fields) {
297 $mdb2 = getConnection();
299 $columns = '(parent_id, org_id, name, currency, lang)';
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)';
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']);
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); */
330 $sql = 'insert into tt_groups '.$columns.$values;
331 $affected = $mdb2->exec($sql);
332 if (is_a($affected, 'PEAR_Error')) return false;
334 $group_id = $mdb2->lastInsertID('tt_groups', 'id');