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');
30 import('ttRoleHelper');
32 // ttOrgImportHelper - this class is a future replacement for ttImportHelper.
33 // Currently, it is work in progress.
34 // When done, it should handle import of complex groups consisting of other groups.
35 class ttOrgImportHelper {
36 var $errors = null; // Errors go here. Set in constructor by reference.
37 var $conflicting_entities = null; // A comma-separated list of entity names we cannot import.
38 var $canImport = true; // False if we cannot import data due to a conflict such as login collision.
39 var $firstPass = true; // True during first pass through the file.
40 var $org_id = null; // Organization id (same as top group_id).
41 var $current_group_id = null; // Current group id during parsing.
42 var $current_parent_group_id = null; // Current parent group id during parsing.
43 // Set when we create a new group.
44 // Entities for current group. -- Looks like they are not needed as we insert right away...
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->conflicting_entities .= ($this->conflicting_entities ? ", $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 $this->current_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 = $this->current_group_id;
93 $sql = "update tt_groups set org_id = $this->current_group_id where org_id is NULL and id = $this->current_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 = $this->current_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 $role_id = ttRoleHelper::insert(array(
114 'group_id' => $this->current_group_id,
115 'org_id' => $this->org_id,
116 'name' => $attrs['NAME'],
117 'description' => $attrs['DESCRIPTION'],
118 'rank' => $attrs['RANK'],
119 'rights' => $attrs['RIGHTS'],
120 'status' => $attrs['STATUS']));
122 $this->currentGroupRoleMap[$attrs['ID']] = $role_id;
127 // importXml - uncompresses the file, reads and parses its content. During parsing,
128 // startElement, endElement, and dataElement functions are called as many times as necessary.
129 // Actual import occurs in the endElement handler.
130 function importXml() {
133 // Do we have a compressed file?
135 $file_ext = substr($_FILES['xmlfile']['name'], strrpos($_FILES['xmlfile']['name'], '.') + 1);
136 if (in_array($file_ext, array('bz','tbz','bz2','tbz2'))) {
140 // Create a temporary file.
141 $dirName = dirname(TEMPLATE_DIR . '_c/.');
142 $filename = tempnam($dirName, 'import_');
144 // If the file is compressed - uncompress it.
146 if (!$this->uncompress($_FILES['xmlfile']['tmp_name'], $filename)) {
147 $this->errors->add($i18n->get('error.sys'));
150 unlink($_FILES['xmlfile']['tmp_name']);
152 if (!move_uploaded_file($_FILES['xmlfile']['tmp_name'], $filename)) {
153 $this->errors->add($i18n->get('error.upload'));
158 // Initialize XML parser.
159 $parser = xml_parser_create();
160 xml_set_object($parser, $this);
161 xml_set_element_handler($parser, 'startElement', false);
163 // We need to parse the file 2 times:
164 // 1) First pass: determine if import is possible - there must be no login collisions.
165 // 2) Second pass: if we can import, then do import in a second pass.
166 // This is different from earlier approach for single group import, where we could
167 // do both things in one pass because user info was in the beginning of XML file.
168 // Now, with subgroups, users can be located anywhere in the file.
170 // Read and parse the content of the file. During parsing, startElement, endElement, and dataElement functions are called.
171 $file = fopen($filename, 'r');
172 while ($data = fread($file, 4096)) {
173 if (!xml_parse($parser, $data, feof($file))) {
174 $this->errors->add(sprintf($i18n->get('error.xml'),
175 xml_get_current_line_number($parser),
176 xml_error_string(xml_get_error_code($parser))));
179 if ($this->conflicting_entities) {
180 $this->canImport = false;
181 $this->errors->add($i18n->get('error.user_exists'));
182 $this->errors->add(sprintf($i18n->get('error.cannot_import'), $this->conflicting_entities));
185 $this->firstPass = false; // We are done with 1st pass.
186 xml_parser_free($parser);
187 if ($file) fclose($file);
188 if (!$this->canImport) {
193 // Now we can do a second pass, where real work is done.
194 $parser = xml_parser_create();
195 xml_set_object($parser, $this);
196 xml_set_element_handler($parser, 'startElement', false);
198 // Read and parse the content of the file. During parsing, startElement, endElement, and dataElement functions are called.
199 $file = fopen($filename, 'r');
200 while ($data = fread($file, 4096)) {
201 if (!xml_parse($parser, $data, feof($file))) {
202 $this->errors->add(sprintf($i18n->get('error.xml'),
203 xml_get_current_line_number($parser),
204 xml_error_string(xml_get_error_code($parser))));
207 xml_parser_free($parser);
208 if ($file) fclose($file);
212 // uncompress - uncompresses the content of the $in file into the $out file.
213 function uncompress($in, $out) {
214 // Do we have the uncompress function?
215 if (!function_exists('bzopen'))
218 // Initial checks of file names and permissions.
219 if (!file_exists($in) || !is_readable ($in))
221 if ((!file_exists($out) && !is_writable(dirname($out))) || (file_exists($out) && !is_writable($out)))
224 if (!$out_file = fopen($out, 'wb'))
226 if (!$in_file = bzopen ($in, 'r'))
229 while (!feof($in_file)) {
230 $buffer = bzread($in_file, 4096);
231 fwrite($out_file, $buffer, 4096);
238 // createGroup function creates a new group.
239 private function createGroup($fields) {
242 $mdb2 = getConnection();
244 $columns = '(parent_id, org_id, name, currency, lang)';
246 // $columns = '(name, currency, decimal_mark, lang, date_format, time_format, week_start, tracking_mode'.
247 // ', project_required, task_required, record_type, bcc_email, allow_ip, password_complexity, plugins'.
248 // ', lock_spec, workday_minutes, config, created, created_ip, created_by)';
250 $values = ' values (';
251 $values .= $mdb2->quote($fields['parent_id']);
252 $values .= ', '.$mdb2->quote($fields['org_id']);
253 $values .= ', '.$mdb2->quote(trim($fields['name']));
254 $values .= ', '.$mdb2->quote(trim($fields['currency']));
255 //$values .= ', '.$mdb2->quote($fields['decimal_mark']);
256 $values .= ', '.$mdb2->quote($fields['lang']);
258 $values .= ', '.$mdb2->quote($fields['date_format']);
259 $values .= ', '.$mdb2->quote($fields['time_format']);
260 $values .= ', '.(int)$fields['week_start'];
261 $values .= ', '.(int)$fields['tracking_mode'];
262 $values .= ', '.(int)$fields['project_required'];
263 $values .= ', '.(int)$fields['task_required'];
264 $values .= ', '.(int)$fields['record_type'];
265 $values .= ', '.$mdb2->quote($fields['bcc_email']);
266 $values .= ', '.$mdb2->quote($fields['allow_ip']);
267 $values .= ', '.$mdb2->quote($fields['password_complexity']);
268 $values .= ', '.$mdb2->quote($fields['plugins']);
269 $values .= ', '.$mdb2->quote($fields['lock_spec']);
270 $values .= ', '.(int)$fields['workday_minutes'];
271 $values .= ', '.$mdb2->quote($fields['config']);
272 $values .= ', now(), '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', '.$mdb2->quote($user->id); */
275 $sql = 'insert into tt_groups '.$columns.$values;
276 $affected = $mdb2->exec($sql);
277 if (is_a($affected, 'PEAR_Error')) return false;
279 $group_id = $mdb2->lastInsertID('tt_groups', 'id');