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');
31 import('ttTaskHelper');
33 // ttOrgImportHelper - this class is a future replacement for ttImportHelper.
34 // Currently, it is work in progress.
35 // When done, it should handle import of complex groups consisting of other groups.
36 class ttOrgImportHelper {
37 var $errors = null; // Errors go here. Set in constructor by reference.
38 var $conflicting_entities = null; // A comma-separated list of entity names we cannot import.
39 var $canImport = true; // False if we cannot import data due to a conflict such as 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_group_id = null; // Current group id during parsing.
43 var $current_parent_group_id = null; // Current parent group id during parsing.
44 // Set when we create a new group.
45 // Entities for current group. -- Looks like they are not needed as we insert right away...
46 // var $currentGroupRoles = array(); // Array of arrays of role properties.
47 // var $currentGroupUsers = array(); // Array of arrays of user properties.
49 // Entity maps for current group. They map XML ids with database ids.
50 var $currentGroupRoleMap = array();
51 var $currentGroupTaskMap = array();
52 //var $userMap = array(); // User ids.
53 //var $projectMap = array(); // Project ids.
54 //var $taskMap = array(); // Task ids.
55 //var $clientMap = array(); // Client ids.
56 //var $invoiceMap = array(); // Invoice ids.
59 function __construct(&$errors) {
60 $this->errors = &$errors;
63 // startElement - callback handler for opening tag of an XML element in the file.
64 function startElement($parser, $name, $attrs) {
67 // First pass. We only check user logins for potential collisions with existing.
68 if ($this->firstPass) {
69 if ($name == 'USER' && $this->canImport) {
70 $login = $attrs['LOGIN'];
71 if ('' != $attrs['STATUS'] && ttUserHelper::getUserByLogin($login)) {
72 // We have a login collision. Append colliding login to a list of things we cannot import.
73 $this->conflicting_entities .= ($this->conflicting_entities ? ", $login" : $login);
78 // Second pass processing. We import data here, one tag at a time.
79 if (!$this->firstPass && $this->canImport && $this->errors->no()) {
80 $mdb2 = getConnection();
82 // We are in second pass and can import data.
83 if ($name == 'GROUP') {
84 // Create a new group.
85 $this->current_group_id = $this->createGroup(array(
86 'parent_id' => $this->current_parent_group_id,
87 'org_id' => $this->org_id,
88 'name' => $attrs['NAME'],
89 'currency' => $attrs['CURRENCY'],
90 'lang' => $attrs['LANG']));
91 // We only have 3 properties at the moment, while work is ongoing...
93 // Special handling for top group.
94 if (!$this->org_id && $this->current_group_id) {
95 $this->org_id = $this->current_group_id;
96 $sql = "update tt_groups set org_id = $this->current_group_id where org_id is NULL and id = $this->current_group_id";
97 $affected = $mdb2->exec($sql);
99 // Set parent group to create subgroups with this group as parent at next entry here.
100 $this->current_parent_group_id = $this->current_group_id;
103 if ($name == 'ROLES') {
104 // If we get here, we have to recycle $currentGroupRoleMap.
105 unset($this->currentGroupRoleMap);
106 $this->currentGroupRoleMap = array();
107 // Role map is reconstructed after processing <role> elements in XML. See below.
110 if ($name == 'ROLE') {
111 // We get here when processing <role> tags for the current group.
112 $role_id = ttRoleHelper::insert(array(
113 'group_id' => $this->current_group_id,
114 'org_id' => $this->org_id,
115 'name' => $attrs['NAME'],
116 'description' => $attrs['DESCRIPTION'],
117 'rank' => $attrs['RANK'],
118 'rights' => $attrs['RIGHTS'],
119 'status' => $attrs['STATUS']));
122 $this->currentGroupRoleMap[$attrs['ID']] = $role_id;
123 } else $this->errors->add($i18n->get('error.db'));
126 if ($name == 'TASKS') {
127 // If we get here, we have to recycle $currentGroupTaskMap.
128 unset($this->currentGroupTaskMap);
129 $this->currentGroupTaskMap = array();
130 // Task map is reconstructed after processing <task> elements in XML. See below.
133 if ($name == 'TASK') {
134 // We get here when processing <task> tags for the current group.
135 $task_id = ttTaskHelper::insert(array(
136 'group_id' => $this->current_group_id,
137 'org_id' => $this->org_id,
138 'name' => $attrs['NAME'],
139 'description' => $attrs['DESCRIPTION'],
140 'status' => $attrs['STATUS']));
143 $this->currentGroupTaskMap[$attrs['ID']] = $task_id;
144 } else $this->errors->add($i18n->get('error.db'));
149 // importXml - uncompresses the file, reads and parses its content. During parsing,
150 // startElement, endElement, and dataElement functions are called as many times as necessary.
151 // Actual import occurs in the endElement handler.
152 function importXml() {
155 // Do we have a compressed file?
157 $file_ext = substr($_FILES['xmlfile']['name'], strrpos($_FILES['xmlfile']['name'], '.') + 1);
158 if (in_array($file_ext, array('bz','tbz','bz2','tbz2'))) {
162 // Create a temporary file.
163 $dirName = dirname(TEMPLATE_DIR . '_c/.');
164 $filename = tempnam($dirName, 'import_');
166 // If the file is compressed - uncompress it.
168 if (!$this->uncompress($_FILES['xmlfile']['tmp_name'], $filename)) {
169 $this->errors->add($i18n->get('error.sys'));
172 unlink($_FILES['xmlfile']['tmp_name']);
174 if (!move_uploaded_file($_FILES['xmlfile']['tmp_name'], $filename)) {
175 $this->errors->add($i18n->get('error.upload'));
180 // Initialize XML parser.
181 $parser = xml_parser_create();
182 xml_set_object($parser, $this);
183 xml_set_element_handler($parser, 'startElement', false);
185 // We need to parse the file 2 times:
186 // 1) First pass: determine if import is possible - there must be no login collisions.
187 // 2) Second pass: if we can import, then do import in a second pass.
188 // This is different from earlier approach for single group import, where we could
189 // do both things in one pass because user info was in the beginning of XML file.
190 // Now, with subgroups, users can be located anywhere in the file.
192 // Read and parse the content of the file. During parsing, startElement, endElement, and dataElement functions are called.
193 $file = fopen($filename, 'r');
194 while ($data = fread($file, 4096)) {
195 if (!xml_parse($parser, $data, feof($file))) {
196 $this->errors->add(sprintf($i18n->get('error.xml'),
197 xml_get_current_line_number($parser),
198 xml_error_string(xml_get_error_code($parser))));
201 if ($this->conflicting_entities) {
202 $this->canImport = false;
203 $this->errors->add($i18n->get('error.user_exists'));
204 $this->errors->add(sprintf($i18n->get('error.cannot_import'), $this->conflicting_entities));
207 $this->firstPass = false; // We are done with 1st pass.
208 xml_parser_free($parser);
209 if ($file) fclose($file);
210 if (!$this->canImport) {
214 if ($this->errors->yes()) return; // Exit if we have errors.
216 // Now we can do a second pass, where real work is done.
217 $parser = xml_parser_create();
218 xml_set_object($parser, $this);
219 xml_set_element_handler($parser, 'startElement', false);
221 // Read and parse the content of the file. During parsing, startElement, endElement, and dataElement functions are called.
222 $file = fopen($filename, 'r');
223 while ($data = fread($file, 4096)) {
224 if (!xml_parse($parser, $data, feof($file))) {
225 $this->errors->add(sprintf($i18n->get('error.xml'),
226 xml_get_current_line_number($parser),
227 xml_error_string(xml_get_error_code($parser))));
230 xml_parser_free($parser);
231 if ($file) fclose($file);
235 // uncompress - uncompresses the content of the $in file into the $out file.
236 function uncompress($in, $out) {
237 // Do we have the uncompress function?
238 if (!function_exists('bzopen'))
241 // Initial checks of file names and permissions.
242 if (!file_exists($in) || !is_readable ($in))
244 if ((!file_exists($out) && !is_writable(dirname($out))) || (file_exists($out) && !is_writable($out)))
247 if (!$out_file = fopen($out, 'wb'))
249 if (!$in_file = bzopen ($in, 'r'))
252 while (!feof($in_file)) {
253 $buffer = bzread($in_file, 4096);
254 fwrite($out_file, $buffer, 4096);
261 // createGroup function creates a new group.
262 private function createGroup($fields) {
265 $mdb2 = getConnection();
267 $columns = '(parent_id, org_id, name, currency, lang)';
269 // $columns = '(name, currency, decimal_mark, lang, date_format, time_format, week_start, tracking_mode'.
270 // ', project_required, task_required, record_type, bcc_email, allow_ip, password_complexity, plugins'.
271 // ', lock_spec, workday_minutes, config, created, created_ip, created_by)';
273 $values = ' values (';
274 $values .= $mdb2->quote($fields['parent_id']);
275 $values .= ', '.$mdb2->quote($fields['org_id']);
276 $values .= ', '.$mdb2->quote(trim($fields['name']));
277 $values .= ', '.$mdb2->quote(trim($fields['currency']));
278 //$values .= ', '.$mdb2->quote($fields['decimal_mark']);
279 $values .= ', '.$mdb2->quote($fields['lang']);
281 $values .= ', '.$mdb2->quote($fields['date_format']);
282 $values .= ', '.$mdb2->quote($fields['time_format']);
283 $values .= ', '.(int)$fields['week_start'];
284 $values .= ', '.(int)$fields['tracking_mode'];
285 $values .= ', '.(int)$fields['project_required'];
286 $values .= ', '.(int)$fields['task_required'];
287 $values .= ', '.(int)$fields['record_type'];
288 $values .= ', '.$mdb2->quote($fields['bcc_email']);
289 $values .= ', '.$mdb2->quote($fields['allow_ip']);
290 $values .= ', '.$mdb2->quote($fields['password_complexity']);
291 $values .= ', '.$mdb2->quote($fields['plugins']);
292 $values .= ', '.$mdb2->quote($fields['lock_spec']);
293 $values .= ', '.(int)$fields['workday_minutes'];
294 $values .= ', '.$mdb2->quote($fields['config']);
295 $values .= ', now(), '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', '.$mdb2->quote($user->id); */
298 $sql = 'insert into tt_groups '.$columns.$values;
299 $affected = $mdb2->exec($sql);
300 if (is_a($affected, 'PEAR_Error')) {
301 $this->errors->add($i18n->get('error.db'));
305 $group_id = $mdb2->lastInsertID('tt_groups', 'id');