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 $conflicting_entities = null; // A comma-separated list of entity names we cannot import.
37 var $canImport = true; // False if we cannot import data due to a conflict such as login collision.
38 var $firstPass = true; // True during first pass through the file.
39 var $org_id = null; // Organization id (same as top group_id).
40 var $current_parent_group_id = null; // Current parent group id as we parse the file.
41 // Set when we create a new group.
42 // Entities for current group.
43 var $currentGroupRoles = array(); // Array of arrays of role properties.
44 // var $currentGroupUsers = array(); // Array of arrays of user properties.
46 // Entity maps for current group. They map XML ids with database ids.
47 var $currentGroupRoleMap = array(); // Maps role ids from XML to their database ids.
48 //var $userMap = array(); // User ids.
49 //var $projectMap = array(); // Project ids.
50 //var $taskMap = array(); // Task ids.
51 //var $clientMap = array(); // Client ids.
52 //var $invoiceMap = array(); // Invoice ids.
55 function __construct(&$errors) {
56 $this->errors = &$errors;
59 // startElement - callback handler for opening tag of an XML element in the file.
60 function startElement($parser, $name, $attrs) {
62 // First pass. We only check user logins for potential collisions with existing.
63 if ($this->firstPass) {
64 if ($name == 'USER' && $this->canImport) {
65 $login = $attrs['LOGIN'];
66 if ('' != $attrs['STATUS'] && ttUserHelper::getUserByLogin($login)) {
67 // We have a login collision. Append colliding login to a list of things we cannot import.
68 $this->conflicting_entities .= ($this->conflicting_entities ? ", $login" : $login);
73 // Second pass processing. We import data here, one tag at a time.
74 if (!$this->firstPass && $this->canImport) {
75 $mdb2 = getConnection();
77 // We are in second pass and can import data.
78 if ($name == 'GROUP') {
79 // Create a new group.
80 $group_id = $this->createGroup(array(
81 'parent_id' => $this->current_parent_group_id,
82 'org_id' => $this->org_id,
83 'name' => $attrs['NAME'],
84 'currency' => $attrs['CURRENCY'],
85 'lang' => $attrs['LANG']));
86 // We only have 3 properties at the moment, while work is ongoing...
88 // Special handling for top group.
90 $this->org_id = $group_id;
91 $sql = "update tt_groups set org_id = $group_id where org_id is NULL and id = $group_id";
92 $affected = $mdb2->exec($sql);
93 // TODO: design a better error handling approach for the entire import process.
95 // Set current parent group.
96 $this->current_parent_group_id = $group_id;
99 if ($name == 'ROLES') {
100 // If we get here, we have to recycle both $currentGroupRoles and $currentGroupRoleMap.
101 unset($this->currentGroupRoles);
102 unset($this->currentGroupRoleMap);
103 $this->currentGroupRoles = array();
104 $this->currentGroupRoleMap = array();
105 // Both arrays are now empty.
106 // They will get reconstructed after processing of <role> elements in XML. See below.
109 if ($name == 'ROLE') {
110 // We get here when processing a <role> tag for the current group.
111 // Add new role to $this->currentGroupRoles and a mapping to $this->currentGroupRoleMap.
112 $this->currentGroupRoles[$attrs['ID']] = $attrs;
117 // importXml - uncompresses the file, reads and parses its content. During parsing,
118 // startElement, endElement, and dataElement functions are called as many times as necessary.
119 // Actual import occurs in the endElement handler.
120 function importXml() {
123 // Do we have a compressed file?
125 $file_ext = substr($_FILES['xmlfile']['name'], strrpos($_FILES['xmlfile']['name'], '.') + 1);
126 if (in_array($file_ext, array('bz','tbz','bz2','tbz2'))) {
130 // Create a temporary file.
131 $dirName = dirname(TEMPLATE_DIR . '_c/.');
132 $filename = tempnam($dirName, 'import_');
134 // If the file is compressed - uncompress it.
136 if (!$this->uncompress($_FILES['xmlfile']['tmp_name'], $filename)) {
137 $this->errors->add($i18n->get('error.sys'));
140 unlink($_FILES['xmlfile']['tmp_name']);
142 if (!move_uploaded_file($_FILES['xmlfile']['tmp_name'], $filename)) {
143 $this->errors->add($i18n->get('error.upload'));
148 // Initialize XML parser.
149 $parser = xml_parser_create();
150 xml_set_object($parser, $this);
151 xml_set_element_handler($parser, 'startElement', false);
153 // We need to parse the file 2 times:
154 // 1) First pass: determine if import is possible - there must be no login collisions.
155 // 2) Second pass: if we can import, then do import in a second pass.
156 // This is different from earlier approach for single group import, where we could
157 // do both things in one pass because user info was in the beginning of XML file.
158 // Now, with subgroups, users can be located anywhere in the file.
160 // Read and parse the content of the file. During parsing, startElement, endElement, and dataElement functions are called.
161 $file = fopen($filename, 'r');
162 while ($data = fread($file, 4096)) {
163 if (!xml_parse($parser, $data, feof($file))) {
164 $this->errors->add(sprintf("XML error: %s at line %d",
165 xml_error_string(xml_get_error_code($parser)),
166 xml_get_current_line_number($parser)));
169 if ($this->conflicting_entities) {
170 $this->canImport = false;
171 $this->errors->add($i18n->get('error.user_exists'));
172 $this->errors->add(sprintf($i18n->get('error.cannot_import'), $this->conflicting_entities));
175 $this->firstPass = false; // We are done with 1st pass.
176 xml_parser_free($parser);
177 if ($file) fclose($file);
178 if (!$this->canImport) {
183 // Now we can do a second pass, where real work is done.
184 $parser = xml_parser_create();
185 xml_set_object($parser, $this);
186 xml_set_element_handler($parser, 'startElement', false);
188 // Read and parse the content of the file. During parsing, startElement, endElement, and dataElement functions are called.
189 $file = fopen($filename, 'r');
190 while ($data = fread($file, 4096)) {
191 if (!xml_parse($parser, $data, feof($file))) {
192 $this->errors->add(sprintf("XML error: %s at line %d",
193 xml_error_string(xml_get_error_code($parser)),
194 xml_get_current_line_number($parser)));
197 xml_parser_free($parser);
198 if ($file) fclose($file);
202 // uncompress - uncompresses the content of the $in file into the $out file.
203 function uncompress($in, $out) {
204 // Do we have the uncompress function?
205 if (!function_exists('bzopen'))
208 // Initial checks of file names and permissions.
209 if (!file_exists($in) || !is_readable ($in))
211 if ((!file_exists($out) && !is_writable(dirname($out))) || (file_exists($out) && !is_writable($out)))
214 if (!$out_file = fopen($out, 'wb'))
216 if (!$in_file = bzopen ($in, 'r'))
219 while (!feof($in_file)) {
220 $buffer = bzread($in_file, 4096);
221 fwrite($out_file, $buffer, 4096);
228 // createGroup function creates a new group.
229 private function createGroup($fields) {
232 $mdb2 = getConnection();
234 $columns = '(parent_id, org_id, name, currency, lang)';
236 // $columns = '(name, currency, decimal_mark, lang, date_format, time_format, week_start, tracking_mode'.
237 // ', project_required, task_required, record_type, bcc_email, allow_ip, password_complexity, plugins'.
238 // ', lock_spec, workday_minutes, config, created, created_ip, created_by)';
240 $values = ' values (';
241 $values .= $mdb2->quote($fields['parent_id']);
242 $values .= ', '.$mdb2->quote($fields['org_id']);
243 $values .= ', '.$mdb2->quote(trim($fields['name']));
244 $values .= ', '.$mdb2->quote(trim($fields['currency']));
245 //$values .= ', '.$mdb2->quote($fields['decimal_mark']);
246 $values .= ', '.$mdb2->quote($fields['lang']);
248 $values .= ', '.$mdb2->quote($fields['date_format']);
249 $values .= ', '.$mdb2->quote($fields['time_format']);
250 $values .= ', '.(int)$fields['week_start'];
251 $values .= ', '.(int)$fields['tracking_mode'];
252 $values .= ', '.(int)$fields['project_required'];
253 $values .= ', '.(int)$fields['task_required'];
254 $values .= ', '.(int)$fields['record_type'];
255 $values .= ', '.$mdb2->quote($fields['bcc_email']);
256 $values .= ', '.$mdb2->quote($fields['allow_ip']);
257 $values .= ', '.$mdb2->quote($fields['password_complexity']);
258 $values .= ', '.$mdb2->quote($fields['plugins']);
259 $values .= ', '.$mdb2->quote($fields['lock_spec']);
260 $values .= ', '.(int)$fields['workday_minutes'];
261 $values .= ', '.$mdb2->quote($fields['config']);
262 $values .= ', now(), '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', '.$mdb2->quote($user->id); */
265 $sql = 'insert into tt_groups '.$columns.$values;
266 $affected = $mdb2->exec($sql);
267 if (is_a($affected, 'PEAR_Error')) return false;
269 $group_id = $mdb2->lastInsertID('tt_groups', 'id');