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('ttUserHelper');
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.
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.
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.
57 function __construct(&$errors) {
58 $this->errors = &$errors;
61 // startElement - callback handler for opening tag of an XML element in the file.
62 function startElement($parser, $name, $attrs) {
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);
75 // Second pass processing. We import data here, one tag at a time.
76 if (!$this->firstPass && $this->canImport) {
77 $mdb2 = getConnection();
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...
90 // Special handling for top group.
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.
97 // Set current parent group.
98 $this->current_parent_group_id = $group_id;
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.
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;
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() {
125 // Do we have a compressed file?
127 $file_ext = substr($_FILES['xmlfile']['name'], strrpos($_FILES['xmlfile']['name'], '.') + 1);
128 if (in_array($file_ext, array('bz','tbz','bz2','tbz2'))) {
132 // Create a temporary file.
133 $dirName = dirname(TEMPLATE_DIR . '_c/.');
134 $filename = tempnam($dirName, 'import_');
136 // If the file is compressed - uncompress it.
138 if (!$this->uncompress($_FILES['xmlfile']['tmp_name'], $filename)) {
139 $this->errors->add($i18n->get('error.sys'));
142 unlink($_FILES['xmlfile']['tmp_name']);
144 if (!move_uploaded_file($_FILES['xmlfile']['tmp_name'], $filename)) {
145 $this->errors->add($i18n->get('error.upload'));
150 // Initialize XML parser.
151 $parser = xml_parser_create();
152 xml_set_object($parser, $this);
153 xml_set_element_handler($parser, 'startElement', false);
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.
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)));
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));
177 $this->firstPass = false; // We are done with 1st pass.
178 xml_parser_free($parser);
179 if ($file) fclose($file);
180 if (!$this->canImport) {
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);
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)));
199 xml_parser_free($parser);
200 if ($file) fclose($file);
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'))
210 // Initial checks of file names and permissions.
211 if (!file_exists($in) || !is_readable ($in))
213 if ((!file_exists($out) && !is_writable(dirname($out))) || (file_exists($out) && !is_writable($out)))
216 if (!$out_file = fopen($out, 'wb'))
218 if (!$in_file = bzopen ($in, 'r'))
221 while (!feof($in_file)) {
222 $buffer = bzread($in_file, 4096);
223 fwrite($out_file, $buffer, 4096);
230 // createGroup function creates a new group.
231 private function createGroup($fields) {
234 $mdb2 = getConnection();
236 $columns = '(parent_id, org_id, name, currency, lang)';
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)';
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']);
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); */
267 $sql = 'insert into tt_groups '.$columns.$values;
268 $affected = $mdb2->exec($sql);
269 if (is_a($affected, 'PEAR_Error')) return false;
271 $group_id = $mdb2->lastInsertID('tt_groups', 'id');