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');
32 import('ttProjectHelper');
33 import('ttClientHelper');
34 import('ttInvoiceHelper');
35 import('ttCustomFieldHelper');
37 // ttOrgImportHelper - this class is a future replacement for ttImportHelper.
38 // Currently, it is work in progress.
39 // When done, it should handle import of complex groups consisting of other groups.
40 class ttOrgImportHelper {
41 var $errors = null; // Errors go here. Set in constructor by reference.
42 var $conflicting_entities = null; // A comma-separated list of entity names we cannot import.
43 var $canImport = true; // False if we cannot import data due to a conflict such as login collision.
44 var $firstPass = true; // True during first pass through the file.
45 var $org_id = null; // Organization id (same as top group_id).
46 var $current_group_id = null; // Current group id during parsing.
47 var $current_parent_group_id = null; // Current parent group id during parsing.
48 // Set when we create a new group.
49 var $top_role_id = 0; // Top role id.
51 // Entity maps for current group. They map XML ids with database ids.
52 var $currentGroupRoleMap = array();
53 var $currentGroupTaskMap = array();
54 var $currentGroupProjectMap = array();
55 var $currentGroupClientMap = array();
56 var $currentGroupUserMap = array();
57 var $currentGroupInvoiceMap = array();
58 var $currentGroupLogMap = array();
59 var $currentGroupCustomFieldMap = array();
60 var $currentGroupCustomFieldOptionMap = array();
63 function __construct(&$errors) {
64 $this->errors = &$errors;
65 $this->top_role_id = ttRoleHelper::getRoleByRank(512, 0);
68 // startElement - callback handler for opening tag of an XML element in the file.
69 function startElement($parser, $name, $attrs) {
72 // First pass. We only check user logins for potential collisions with existing.
73 if ($this->firstPass) {
74 if ($name == 'USER' && $this->canImport) {
75 $login = $attrs['LOGIN'];
76 if ('' != $attrs['STATUS'] && ttUserHelper::getUserByLogin($login)) {
77 // We have a login collision. Append colliding login to a list of things we cannot import.
78 $this->conflicting_entities .= ($this->conflicting_entities ? ", $login" : $login);
83 // Second pass processing. We import data here, one tag at a time.
84 if (!$this->firstPass && $this->canImport && $this->errors->no()) {
85 $mdb2 = getConnection();
87 // We are in second pass and can import data.
88 if ($name == 'GROUP') {
89 // Create a new group.
90 $this->current_group_id = $this->createGroup(array(
91 'parent_id' => $this->current_parent_group_id,
92 'org_id' => $this->org_id,
93 'name' => $attrs['NAME'],
94 'currency' => $attrs['CURRENCY'],
95 'decimal_mark' => $attrs['DECIMAL_MARK'],
96 'lang' => $attrs['LANG'],
97 'date_format' => $attrs['DATE_FORMAT'],
98 'time_format' => $attrs['TIME_FORMAT'],
99 'week_start' => $attrs['WEEK_START'],
100 'tracking_mode' => $attrs['TRACKING_MODE'],
101 'project_required' => $attrs['PROJECT_REQUIRED'],
102 'task_required' => $attrs['TASK_REQUIRED'],
103 'record_type' => $attrs['RECORD_TYPE'],
104 'bcc_email' => $attrs['BCC_EMAIL'],
105 'allow_ip' => $attrs['ALLOW_IP'],
106 'password_complexity' => $attrs['PASSWORD_COMPLEXITY'],
107 'plugins' => $attrs['PLUGINS'],
108 'lock_spec' => $attrs['LOCK_SPEC'],
109 'workday_minutes' => $attrs['WORKDAY_MINUTES'],
110 'custom_logo' => $attrs['CUSTOM_LOGO'],
111 'config' => $attrs['CONFIG']));
113 // Special handling for top group.
114 if (!$this->org_id && $this->current_group_id) {
115 $this->org_id = $this->current_group_id;
116 $sql = "update tt_groups set org_id = $this->current_group_id where org_id is NULL and id = $this->current_group_id";
117 $affected = $mdb2->exec($sql);
119 // Set parent group to create subgroups with this group as parent at next entry here.
120 $this->current_parent_group_id = $this->current_group_id;
123 if ($name == 'ROLES') {
124 // If we get here, we have to recycle $currentGroupRoleMap.
125 unset($this->currentGroupRoleMap);
126 $this->currentGroupRoleMap = array();
127 // Role map is reconstructed after processing <role> elements in XML. See below.
130 if ($name == 'ROLE') {
131 // We get here when processing <role> tags for the current group.
132 $role_id = ttRoleHelper::insert(array(
133 'group_id' => $this->current_group_id,
134 'org_id' => $this->org_id,
135 'name' => $attrs['NAME'],
136 'description' => $attrs['DESCRIPTION'],
137 'rank' => $attrs['RANK'],
138 'rights' => $attrs['RIGHTS'],
139 'status' => $attrs['STATUS']));
142 $this->currentGroupRoleMap[$attrs['ID']] = $role_id;
143 } else $this->errors->add($i18n->get('error.db'));
146 if ($name == 'TASKS') {
147 // If we get here, we have to recycle $currentGroupTaskMap.
148 unset($this->currentGroupTaskMap);
149 $this->currentGroupTaskMap = array();
150 // Task map is reconstructed after processing <task> elements in XML. See below.
153 if ($name == 'TASK') {
154 // We get here when processing <task> tags for the current group.
155 $task_id = ttTaskHelper::insert(array(
156 'group_id' => $this->current_group_id,
157 'org_id' => $this->org_id,
158 'name' => $attrs['NAME'],
159 'description' => $attrs['DESCRIPTION'],
160 'status' => $attrs['STATUS']));
163 $this->currentGroupTaskMap[$attrs['ID']] = $task_id;
164 } else $this->errors->add($i18n->get('error.db'));
167 if ($name == 'PROJECTS') {
168 // If we get here, we have to recycle $currentGroupProjectMap.
169 unset($this->currentGroupProjectMap);
170 $this->currentGroupProjectMap = array();
171 // Project map is reconstructed after processing <project> elements in XML. See below.
174 if ($name == 'PROJECT') {
175 // We get here when processing <project> tags for the current group.
177 // Prepare a list of task ids.
178 $tasks = explode(',', $attrs['TASKS']);
179 foreach ($tasks as $id)
180 $mapped_tasks[] = $this->currentGroupTaskMap[$id];
182 $project_id = ttProjectHelper::insert(array(
183 'group_id' => $this->current_group_id,
184 'org_id' => $this->org_id,
185 'name' => $attrs['NAME'],
186 'description' => $attrs['DESCRIPTION'],
187 'tasks' => $mapped_tasks,
188 'status' => $attrs['STATUS']));
191 $this->currentGroupProjectMap[$attrs['ID']] = $project_id;
192 } else $this->errors->add($i18n->get('error.db'));
195 if ($name == 'CLIENTS') {
196 // If we get here, we have to recycle $currentGroupClientMap.
197 unset($this->currentGroupClientMap);
198 $this->currentGroupClientMap = array();
199 // Client map is reconstructed after processing <client> elements in XML. See below.
202 if ($name == 'CLIENT') {
203 // We get here when processing <client> tags for the current group.
205 // Prepare a list of project ids.
206 $projects = explode(',', $attrs['PROJECTS']);
207 foreach ($projects as $id)
208 $mapped_projects[] = $this->currentGroupProjectMap[$id];
210 $client_id = ttClientHelper::insert(array(
211 'group_id' => $this->current_group_id,
212 'org_id' => $this->org_id,
213 'name' => $attrs['NAME'],
214 'address' => $attrs['ADDRESS'],
215 'tax' => $attrs['TAX'],
216 'projects' => $mapped_projects,
217 'status' => $attrs['STATUS']));
220 $this->currentGroupClientMap[$attrs['ID']] = $client_id;
221 } else $this->errors->add($i18n->get('error.db'));
224 if ($name == 'USERS') {
225 // If we get here, we have to recycle $currentGroupUserMap.
226 unset($this->currentGroupUserMap);
227 $this->currentGroupUserMap = array();
228 // User map is reconstructed after processing <user> elements in XML. See below.
231 if ($name == 'USER') {
232 // We get here when processing <user> tags for the current group.
234 $role_id = $attrs['ROLE_ID'] === '0' ? $this->top_role_id : $this->currentGroupRoleMap[$attrs['ROLE_ID']]; // 0 (not null) means top manager role.
236 $user_id = ttUserHelper::insert(array(
237 'group_id' => $this->current_group_id,
238 'org_id' => $this->org_id,
239 'role_id' => $role_id,
240 'client_id' => $this->currentGroupClientMap[$attrs['CLIENT_ID']],
241 'name' => $attrs['NAME'],
242 'login' => $attrs['LOGIN'],
243 'password' => $attrs['PASSWORD'],
244 'rate' => $attrs['RATE'],
245 'email' => $attrs['EMAIL'],
246 'status' => $attrs['STATUS']), false);
249 $this->currentGroupUserMap[$attrs['ID']] = $user_id;
250 } else $this->errors->add($i18n->get('error.db'));
253 if ($name == 'USER_PROJECT_BIND') {
254 if (!ttUserHelper::insertBind(array(
255 'user_id' => $this->currentGroupUserMap[$attrs['USER_ID']],
256 'project_id' => $this->currentGroupProjectMap[$attrs['PROJECT_ID']],
257 'group_id' => $this->current_group_id,
258 'org_id' => $this->org_id,
259 'rate' => $attrs['RATE'],
260 'status' => $attrs['STATUS']))) {
261 $this->errors->add($i18n->get('error.db'));
265 if ($name == 'INVOICES') {
266 // If we get here, we have to recycle $currentGroupInvoiceMap.
267 unset($this->currentGroupInvoiceMap);
268 $this->currentGroupInvoiceMap = array();
269 // Invoice map is reconstructed after processing <invoice> elements in XML. See below.
272 if ($name == 'INVOICE') {
273 // We get here when processing <invoice> tags for the current group.
274 $invoice_id = ttInvoiceHelper::insert(array(
275 'group_id' => $this->current_group_id,
276 'org_id' => $this->org_id,
277 'name' => $attrs['NAME'],
278 'date' => $attrs['DATE'],
279 'client_id' => $this->currentGroupClientMap[$attrs['CLIENT_ID']],
280 'status' => $attrs['STATUS']));
283 $this->currentGroupInvoiceMap[$attrs['ID']] = $invoice_id;
284 } else $this->errors->add($i18n->get('error.db'));
287 if ($name == 'LOG') {
288 // If we get here, we have to recycle $currentGroupLogMap.
289 unset($this->currentGroupLogMap);
290 $this->currentGroupLogMap = array();
291 // Log map is reconstructed after processing <log_item> elements in XML. See below.
294 if ($name == 'LOG_ITEM') {
295 // We get here when processing <log_item> tags for the current group.
296 $log_item_id = ttTimeHelper::insert(array(
297 'user_id' => $this->currentGroupUserMap[$attrs['USER_ID']],
298 'group_id' => $this->current_group_id,
299 'org_id' => $this->org_id,
300 'date' => $attrs['DATE'],
301 'start' => $attrs['START'],
302 'finish' => $attrs['FINISH'],
303 'duration' => $attrs['DURATION'],
304 'client' => $this->currentGroupClientMap[$attrs['CLIENT_ID']],
305 'project' => $this->currentGroupProjectMap[$attrs['PROJECT_ID']],
306 'task' => $this->currentGroupTaskMap[$attrs['TASK_ID']],
307 'invoice' => $this->currentGroupInvoiceMap[$attrs['INVOICE_ID']],
308 'note' => (isset($attrs['COMMENT']) ? $attrs['COMMENT'] : ''),
309 'billable' => $attrs['BILLABLE'],
310 'paid' => $attrs['PAID'],
311 'status' => $attrs['STATUS']));
314 $this->currentGroupLogMap[$attrs['ID']] = $log_item_id;
315 } else $this->errors->add($i18n->get('error.db'));
318 if ($name == 'CUSTOM_FIELDS') {
319 // If we get here, we have to recycle $currentGroupCustomFieldMap.
320 unset($this->currentGroupCustomFieldMap);
321 $this->currentGroupCustomFieldMap = array();
322 // Custom field map is reconstructed after processing <custom_field> elements in XML. See below.
325 if ($name == 'CUSTOM_FIELD') {
326 // We get here when processing <custom_field> tags for the current group.
327 $custom_field_id = ttCustomFieldHelper::insertField(array(
328 'group_id' => $this->current_group_id,
329 // 'org_id' => $this->org_id, TODO: add this when org_id field is added to the table.
330 'type' => $attrs['TYPE'],
331 'label' => $attrs['LABEL'],
332 'required' => $attrs['REQUIRED'],
333 'status' => $attrs['STATUS']));
334 if ($custom_field_id) {
336 $this->currentGroupCustomFieldMap[$attrs['ID']] = $custom_field_id;
337 } else $this->errors->add($i18n->get('error.db'));
340 if ($name == 'CUSTOM_FIELD_OPTIONS') {
341 // If we get here, we have to recycle $currentGroupCustomFieldOptionMap.
342 unset($this->currentGroupCustomFieldOptionMap);
343 $this->currentGroupCustomFieldOptionMap = array();
344 // Custom field option map is reconstructed after processing <custom_field_option> elements in XML. See below.
347 if ($name == 'CUSTOM_FIELD_OPTION') {
348 // We get here when processing <custom_field_option> tags for the current group.
349 $custom_field_option_id = ttCustomFieldHelper::insertOption(array(
350 // 'group_id' => $this->current_group_id, TODO: add this when group_id field is added to the table.
351 // 'org_id' => $this->org_id, TODO: add this when org_id field is added to the table.
352 'field_id' => $this->currentGroupCustomFieldMap[$attrs['FIELD_ID']],
353 'value' => $attrs['VALUE']));
354 if ($custom_field_option_id) {
356 $this->currentGroupCustomFieldOptionMap[$attrs['ID']] = $custom_field_option_id;
357 } else $this->errors->add($i18n->get('error.db'));
360 if ($name == 'CUSTOM_FIELD_LOG_ENTRY') {
361 // We get here when processing <custom_field_log_entry> tags for the current group.
362 if (!ttCustomFieldHelper::insertLogEntry(array(
363 // 'group_id' => $this->current_group_id, TODO: add this when group_id field is added to the table.
364 // 'org_id' => $this->org_id, TODO: add this when org_id field is added to the table.
365 'log_id' => $this->currentGroupLogMap[$attrs['LOG_ID']],
366 'field_id' => $this->currentGroupCustomFieldMap[$attrs['FIELD_ID']],
367 'option_id' => $this->currentGroupCustomFieldOptionMap[$attrs['OPTION_ID']],
368 'value' => $attrs['VALUE'],
369 'status' => $attrs['STATUS']))) {
370 $this->errors->add($i18n->get('error.db'));
376 // importXml - uncompresses the file, reads and parses its content. During parsing,
377 // startElement, endElement, and dataElement functions are called as many times as necessary.
378 // Actual import occurs in the endElement handler.
379 function importXml() {
382 // Do we have a compressed file?
384 $file_ext = substr($_FILES['xmlfile']['name'], strrpos($_FILES['xmlfile']['name'], '.') + 1);
385 if (in_array($file_ext, array('bz','tbz','bz2','tbz2'))) {
389 // Create a temporary file.
390 $dirName = dirname(TEMPLATE_DIR . '_c/.');
391 $filename = tempnam($dirName, 'import_');
393 // If the file is compressed - uncompress it.
395 if (!$this->uncompress($_FILES['xmlfile']['tmp_name'], $filename)) {
396 $this->errors->add($i18n->get('error.sys'));
399 unlink($_FILES['xmlfile']['tmp_name']);
401 if (!move_uploaded_file($_FILES['xmlfile']['tmp_name'], $filename)) {
402 $this->errors->add($i18n->get('error.upload'));
407 // Initialize XML parser.
408 $parser = xml_parser_create();
409 xml_set_object($parser, $this);
410 xml_set_element_handler($parser, 'startElement', false);
412 // We need to parse the file 2 times:
413 // 1) First pass: determine if import is possible - there must be no login collisions.
414 // 2) Second pass: if we can import, then do import in a second pass.
415 // This is different from earlier approach for single group import, where we could
416 // do both things in one pass because user info was in the beginning of XML file.
417 // Now, with subgroups, users can be located anywhere in the file.
419 // Read and parse the content of the file. During parsing, startElement, endElement, and dataElement functions are called.
420 $file = fopen($filename, 'r');
421 while ($data = fread($file, 4096)) {
422 if (!xml_parse($parser, $data, feof($file))) {
423 $this->errors->add(sprintf($i18n->get('error.xml'),
424 xml_get_current_line_number($parser),
425 xml_error_string(xml_get_error_code($parser))));
428 if ($this->conflicting_entities) {
429 $this->canImport = false;
430 $this->errors->add($i18n->get('error.user_exists'));
431 $this->errors->add(sprintf($i18n->get('error.cannot_import'), $this->conflicting_entities));
434 $this->firstPass = false; // We are done with 1st pass.
435 xml_parser_free($parser);
436 if ($file) fclose($file);
437 if (!$this->canImport) {
441 if ($this->errors->yes()) return; // Exit if we have errors.
443 // Now we can do a second pass, where real work is done.
444 $parser = xml_parser_create();
445 xml_set_object($parser, $this);
446 xml_set_element_handler($parser, 'startElement', false);
448 // Read and parse the content of the file. During parsing, startElement, endElement, and dataElement functions are called.
449 $file = fopen($filename, 'r');
450 while ($data = fread($file, 4096)) {
451 if (!xml_parse($parser, $data, feof($file))) {
452 $this->errors->add(sprintf($i18n->get('error.xml'),
453 xml_get_current_line_number($parser),
454 xml_error_string(xml_get_error_code($parser))));
457 xml_parser_free($parser);
458 if ($file) fclose($file);
462 // uncompress - uncompresses the content of the $in file into the $out file.
463 function uncompress($in, $out) {
464 // Do we have the uncompress function?
465 if (!function_exists('bzopen'))
468 // Initial checks of file names and permissions.
469 if (!file_exists($in) || !is_readable ($in))
471 if ((!file_exists($out) && !is_writable(dirname($out))) || (file_exists($out) && !is_writable($out)))
474 if (!$out_file = fopen($out, 'wb'))
476 if (!$in_file = bzopen ($in, 'r'))
479 while (!feof($in_file)) {
480 $buffer = bzread($in_file, 4096);
481 fwrite($out_file, $buffer, 4096);
488 // createGroup function creates a new group.
489 private function createGroup($fields) {
492 $mdb2 = getConnection();
494 $columns = '(parent_id, org_id, name, currency, decimal_mark, lang, date_format, time_format'.
495 ', week_start, tracking_mode, project_required, task_required, record_type, bcc_email'.
496 ', allow_ip, password_complexity, plugins, lock_spec'.
497 ', workday_minutes, config, created, created_ip, created_by)';
499 $values = ' values (';
500 $values .= $mdb2->quote($fields['parent_id']);
501 $values .= ', '.$mdb2->quote($fields['org_id']);
502 $values .= ', '.$mdb2->quote(trim($fields['name']));
503 $values .= ', '.$mdb2->quote(trim($fields['currency']));
504 $values .= ', '.$mdb2->quote($fields['decimal_mark']);
505 $values .= ', '.$mdb2->quote($fields['lang']);
506 $values .= ', '.$mdb2->quote($fields['date_format']);
507 $values .= ', '.$mdb2->quote($fields['time_format']);
508 $values .= ', '.(int)$fields['week_start'];
509 $values .= ', '.(int)$fields['tracking_mode'];
510 $values .= ', '.(int)$fields['project_required'];
511 $values .= ', '.(int)$fields['task_required'];
512 $values .= ', '.(int)$fields['record_type'];
513 $values .= ', '.$mdb2->quote($fields['bcc_email']);
514 $values .= ', '.$mdb2->quote($fields['allow_ip']);
515 $values .= ', '.$mdb2->quote($fields['password_complexity']);
516 $values .= ', '.$mdb2->quote($fields['plugins']);
517 $values .= ', '.$mdb2->quote($fields['lock_spec']);
518 $values .= ', '.(int)$fields['workday_minutes'];
519 $values .= ', '.$mdb2->quote($fields['config']);
520 $values .= ', now(), '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', '.$mdb2->quote($user->id);
523 $sql = 'insert into tt_groups '.$columns.$values;
524 $affected = $mdb2->exec($sql);
525 if (is_a($affected, 'PEAR_Error')) {
526 $this->errors->add($i18n->get('error.db'));
530 $group_id = $mdb2->lastInsertID('tt_groups', 'id');