69af9e12cd9beac5c6b2218d3726632af59d21ff
[timetracker.git] / WEB-INF / lib / ttImportHelper.class.php
1 <?php
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.
10 // |
11 // | There are only two ways to violate the license:
12 // |
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).
16 // |
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).
20 // |
21 // | This license applies to this document only, not any other software
22 // | that it may be combined with.
23 // |
24 // +----------------------------------------------------------------------+
25 // | Contributors:
26 // | https://www.anuko.com/time_tracker/credits.htm
27 // +----------------------------------------------------------------------+
28
29 import('ttTeamHelper');
30 import('ttUserHelper');
31 import('ttProjectHelper');
32 import('ttTaskHelper');
33 import('ttInvoiceHelper');
34 import('ttTimeHelper');
35 import('ttClientHelper');
36 import('ttCustomFieldHelper');
37 import('ttFavReportHelper');
38 import('ttExpenseHelper');
39 import('ttRoleHelper');
40
41 // ttImportHelper - this class is used to import group data from a file.
42 class ttImportHelper {
43   var $errors         = null;    // Errors go here. Set in constructor by reference.
44
45   var $currentElement = array(); // Current element of the XML file we are parsing.
46   var $currentTag     = '';      // XML tag of the current element.
47
48   var $canImport      = true;    // False if we cannot import data due to a login collision.
49   var $groupData      = array(); // Array of group data such as group name, etc.
50   var $org_id         = null;    // New organization id we are importing. It is created during the import operation.
51   var $group_id       = null;    // New group id we are importing. It is created during the import operation.
52   var $roles          = array(); // Array of arrays of role properties.
53   var $users          = array(); // Array of arrays of user properties.
54   var $top_role_id    = null;    // Top manager role id on the new server.
55
56   // The following arrays are maps between entity ids in the file versus the database.
57   // In the file they are sequential (1,2,3...) while in the database the entities have different ids.
58   var $roleMap       = array(); // Role ids.
59   var $userMap       = array(); // User ids.
60   var $projectMap    = array(); // Project ids.
61   var $taskMap       = array(); // Task ids.
62   var $clientMap     = array(); // Client ids.
63   var $invoiceMap    = array(); // Invoice ids.
64
65   var $customFieldMap       = array(); // Custom field ids.
66   var $customFieldOptionMap = array(); // Custop field option ids.
67   var $logMap        = array(); // Time log ids.
68
69   // Constructor.
70   function ttImportHelper(&$errors) {
71     $this->errors = &$errors;
72   }
73
74   // startElement - callback handler for opening tag of an XML element.
75   // In this function we assign passed in attributes to currentElement.
76   function startElement($parser, $name, $attrs) {
77     if ($name == 'GROUP'
78       || $name == 'USER'
79       || $name == 'TASK'
80       || $name == 'PROJECT'
81       || $name == 'CLIENT'
82       || $name == 'INVOICE'
83       || $name == 'MONTHLY_QUOTA'
84       || $name == 'LOG_ITEM'
85       || $name == 'CUSTOM_FIELD'
86       || $name == 'CUSTOM_FIELD_OPTION'
87       || $name == 'CUSTOM_FIELD_LOG_ENTRY'
88       || $name == 'INVOICE_HEADER'
89       || $name == 'USER_PROJECT_BIND'
90       || $name == 'EXPENSE_ITEM'
91       || $name == 'FAV_REPORT'
92       || $name == 'ROLE') {
93       $this->currentElement = $attrs;
94     }
95     $this->currentTag = $name;
96   }
97
98   // endElement - callback handler for the closing tag of an XML element.
99   // When we are here, currentElement is an array of the element attributes (as set in startElement).
100   // Here we do the actual import of data into the database.
101   function endElement($parser, $name) {
102     if ($name == 'GROUP') {
103       $this->groupData = $this->currentElement;
104       // Now groupData is an array of group properties. We'll use it later to create a group.
105       // Cannot create the group here. Need to determine whether logins collide with existing logins.
106       $this->currentElement = array();
107     }
108     if ($name == 'ROLE') {
109       $this->roles[$this->currentElement['ID']] = $this->currentElement;
110       $this->currentElement = array();
111     }
112     if ($name == 'USER') {
113       $this->users[$this->currentElement['ID']] = $this->currentElement;
114       $this->currentElement = array();
115     }
116     if ($name == 'USERS') {
117       foreach ($this->users as $user_item) {
118         if (('' != $user_item['STATUS']) && ttUserHelper::getUserByLogin($user_item['LOGIN'])) {
119           // We have a login collision, cannot import any data.
120           $this->canImport = false;
121           break;
122         }
123       }
124
125       // Now we can create a group.
126       if ($this->canImport) {
127         $this->top_role_id = ttRoleHelper::getRoleByRank(512, 0);
128         $group_id = $this->createGroup(array(
129           'name' => $this->groupData['NAME'],
130           'currency' => $this->groupData['CURRENCY'],
131           'decimal_mark' => $this->groupData['DECIMAL_MARK'],
132           'lang' => $this->groupData['LANG'],
133           'date_format' => $this->groupData['DATE_FORMAT'],
134           'time_format' => $this->groupData['TIME_FORMAT'],
135           'week_start' => $this->groupData['WEEK_START'],
136           'tracking_mode' => $this->groupData['TRACKING_MODE'],
137           'project_required' => $this->groupData['PROJECT_REQUIRED'],
138           'task_required' => $this->groupData['TASK_REQUIRED'],
139           'record_type' => $this->groupData['RECORD_TYPE'],
140           'bcc_email' => $this->groupData['BCC_EMAIL'],
141           'allow_ip' => $this->groupData['ALLOW_IP'],
142           'password_complexity' => $this->groupData['PASSWORD_COMPLEXITY'],
143           'plugins' => $this->groupData['PLUGINS'],
144           'lock_spec' => $this->groupData['LOCK_SPEC'],
145           'workday_minutes' => $this->groupData['WORKDAY_MINUTES'],
146           'config' => $this->groupData['CONFIG']));
147         if ($group_id) {
148           $this->org_id = $group_id;
149           $this->group_id = $group_id;
150
151           // Create roles.
152           foreach ($this->roles as $key=>$role_item) {
153             $role_id = ttRoleHelper::insert(array(
154               'group_id' => $this->group_id,
155               'name' => $role_item['NAME'],
156               'rank' => $role_item['RANK'],
157               'rights' => $role_item['RIGHTS'],
158               'status' => $role_item['STATUS']));
159             $this->roleMap[$role_item['ID']] = $role_id;
160           }
161
162           foreach ($this->users as $key=>$user_item) {
163             $role_id = $user_item['ROLE_ID'] === '0' ? $this->top_role_id :  $this->roleMap[$user_item['ROLE_ID']]; // 0 (not null) means top manager role.
164             $user_id = ttUserHelper::insert(array(
165               'group_id' => $this->group_id,
166               'org_id' => $this->org_id,
167               'role_id' => $role_id,
168               'client_id' => $user_item['CLIENT_ID'], // Note: NOT mapped value, replaced in CLIENT handler.
169               'name' => $user_item['NAME'],
170               'login' => $user_item['LOGIN'],
171               'password' => $user_item['PASSWORD'],
172               'rate' => $user_item['RATE'],
173               'email' => $user_item['EMAIL'],
174               'status' => $user_item['STATUS']), false);
175             $this->userMap[$key] = $user_id;
176           }
177         }
178       }
179     }
180
181     if ($name == 'TASK' && $this->canImport) {
182       $this->taskMap[$this->currentElement['ID']] =
183         ttTaskHelper::insert(array(
184           'group_id' => $this->group_id,
185           'name' => $this->currentElement['NAME'],
186           'description' => $this->currentElement['DESCRIPTION'],
187           'status' => $this->currentElement['STATUS']));
188     }
189     if ($name == 'PROJECT' && $this->canImport) {
190       // Prepare a list of task ids.
191       $tasks = explode(',', $this->currentElement['TASKS']);
192       foreach ($tasks as $id)
193         $mapped_tasks[] = $this->taskMap[$id];
194
195       // Add a new project.
196       $this->projectMap[$this->currentElement['ID']] =
197         ttProjectHelper::insert(array(
198           'group_id' => $this->group_id,
199           'name' => $this->currentElement['NAME'],
200           'description' => $this->currentElement['DESCRIPTION'],
201           'tasks' => $mapped_tasks,
202           'status' => $this->currentElement['STATUS']));
203     }
204     if ($name == 'USER_PROJECT_BIND' && $this->canImport) {
205       ttUserHelper::insertBind(
206         $this->userMap[$this->currentElement['USER_ID']],
207         $this->projectMap[$this->currentElement['PROJECT_ID']],
208         $this->currentElement['RATE'],
209         $this->currentElement['STATUS']);
210     }
211
212     if ($name == 'CLIENT' && $this->canImport) {
213       // Prepare a list of project ids.
214       if ($this->currentElement['PROJECTS']) {
215         $projects = explode(',', $this->currentElement['PROJECTS']);
216         foreach ($projects as $id)
217           $mapped_projects[] = $this->projectMap[$id];
218       }
219
220       $this->clientMap[$this->currentElement['ID']] =
221         ttClientHelper::insert(array(
222           'group_id' => $this->group_id,
223           'name' => $this->currentElement['NAME'],
224           'address' => $this->currentElement['ADDRESS'],
225           'tax' => $this->currentElement['TAX'],
226           'projects' => $mapped_projects,
227           'status' => $this->currentElement['STATUS']));
228
229         // Update client_id for tt_users to a mapped value.
230         // We did not do it during user insertion because clientMap was not ready then.
231         if ($this->currentElement['ID'] != $this->clientMap[$this->currentElement['ID']])
232           ttClientHelper::setMappedClient($this->group_id, $this->currentElement['ID'], $this->clientMap[$this->currentElement['ID']]);
233     }
234
235     if ($name == 'INVOICE' && $this->canImport) {
236       $this->invoiceMap[$this->currentElement['ID']] =
237         ttInvoiceHelper::insert(array(
238           'group_id' => $this->group_id,
239           'name' => $this->currentElement['NAME'],
240           'date' => $this->currentElement['DATE'],
241           'client_id' => $this->clientMap[$this->currentElement['CLIENT_ID']],
242           'discount' => $this->currentElement['DISCOUNT'],
243           'status' => $this->currentElement['STATUS']));
244     }
245
246     if ($name == 'MONTHLY_QUOTA' && $this->canImport) {
247       $this->insertMonthlyQuota($this->group_id, $this->currentElement['YEAR'], $this->currentElement['MONTH'], $this->currentElement['MINUTES']);
248     }
249
250     if ($name == 'LOG_ITEM' && $this->canImport) {
251       $this->logMap[$this->currentElement['ID']] =
252         ttTimeHelper::insert(array(
253           'user_id' => $this->userMap[$this->currentElement['USER_ID']],
254           'group_id' => $this->group_id,
255           'date' => $this->currentElement['DATE'],
256           'start' => $this->currentElement['START'],
257           'finish' => $this->currentElement['FINISH'],
258           'duration' => $this->currentElement['DURATION'],
259           'client' => $this->clientMap[$this->currentElement['CLIENT_ID']],
260           'project' => $this->projectMap[$this->currentElement['PROJECT_ID']],
261           'task' => $this->taskMap[$this->currentElement['TASK_ID']],
262           'invoice' => $this->invoiceMap[$this->currentElement['INVOICE_ID']],
263           'note' => (isset($this->currentElement['COMMENT']) ? $this->currentElement['COMMENT'] : ''),
264           'billable' => $this->currentElement['BILLABLE'],
265           'paid' => $this->currentElement['PAID'],
266           'status' => $this->currentElement['STATUS']));
267     }
268
269     if ($name == 'CUSTOM_FIELD' && $this->canImport) {
270       $this->customFieldMap[$this->currentElement['ID']] =
271         ttCustomFieldHelper::insertField(array(
272           'group_id' => $this->group_id,
273           'type' => $this->currentElement['TYPE'],
274           'label' => $this->currentElement['LABEL'],
275           'required' => $this->currentElement['REQUIRED'],
276           'status' => $this->currentElement['STATUS']));
277     }
278
279     if ($name == 'CUSTOM_FIELD_OPTION' && $this->canImport) {
280       $this->customFieldOptionMap[$this->currentElement['ID']] =
281         ttCustomFieldHelper::insertOption(array(
282           'field_id' => $this->customFieldMap[$this->currentElement['FIELD_ID']],
283           'value' => $this->currentElement['VALUE']));
284     }
285
286     if ($name == 'CUSTOM_FIELD_LOG_ENTRY' && $this->canImport) {
287       ttCustomFieldHelper::insertLogEntry(array(
288         'log_id' => $this->logMap[$this->currentElement['LOG_ID']],
289         'field_id' => $this->customFieldMap[$this->currentElement['FIELD_ID']],
290         'option_id' => $this->customFieldOptionMap[$this->currentElement['OPTION_ID']],
291         'value' => $this->currentElement['VALUE'],
292         'status' => $this->currentElement['STATUS']));
293     }
294
295     if ($name == 'EXPENSE_ITEM' && $this->canImport) {
296       ttExpenseHelper::insert(array(
297         'date' => $this->currentElement['DATE'],
298         'user_id' => $this->userMap[$this->currentElement['USER_ID']],
299         'group_id' => $this->group_id,
300         'client_id' => $this->clientMap[$this->currentElement['CLIENT_ID']],
301         'project_id' => $this->projectMap[$this->currentElement['PROJECT_ID']],
302         'name' => $this->currentElement['NAME'],
303         'cost' => $this->currentElement['COST'],
304         'invoice_id' => $this->invoiceMap[$this->currentElement['INVOICE_ID']],
305         'paid' => $this->currentElement['PAID'],
306         'status' => $this->currentElement['STATUS']));
307     }
308
309     if ($name == 'FAV_REPORT' && $this->canImport) {
310       $user_list = '';
311       if (strlen($this->currentElement['USERS']) > 0) {
312         $arr = explode(',', $this->currentElement['USERS']);
313         foreach ($arr as $v)
314           $user_list .= (strlen($user_list) == 0 ? '' : ',').$this->userMap[$v];
315       }
316       ttFavReportHelper::insertReport(array(
317         'name' => $this->currentElement['NAME'],
318         'user_id' => $this->userMap[$this->currentElement['USER_ID']],
319         'client' => $this->clientMap[$this->currentElement['CLIENT_ID']],
320         'option' => $this->customFieldOptionMap[$this->currentElement['CF_1_OPTION_ID']],
321         'project' => $this->projectMap[$this->currentElement['PROJECT_ID']],
322         'task' => $this->taskMap[$this->currentElement['TASK_ID']],
323         'billable' => $this->currentElement['BILLABLE'],
324         'users' => $user_list,
325         'period' => $this->currentElement['PERIOD'],
326         'from' => $this->currentElement['PERIOD_START'],
327         'to' => $this->currentElement['PERIOD_END'],
328         'chclient' => (int) $this->currentElement['SHOW_CLIENT'],
329         'chinvoice' => (int) $this->currentElement['SHOW_INVOICE'],
330         'chpaid' => (int) $this->currentElement['SHOW_PAID'],
331         'chip' => (int) $this->currentElement['SHOW_IP'],
332         'chproject' => (int) $this->currentElement['SHOW_PROJECT'],
333         'chstart' => (int) $this->currentElement['SHOW_START'],
334         'chduration' => (int) $this->currentElement['SHOW_DURATION'],
335         'chcost' => (int) $this->currentElement['SHOW_COST'],
336         'chtask' => (int) $this->currentElement['SHOW_TASK'],
337         'chfinish' => (int) $this->currentElement['SHOW_END'],
338         'chnote' => (int) $this->currentElement['SHOW_NOTE'],
339         'chcf_1' => (int) $this->currentElement['SHOW_CUSTOM_FIELD_1'],
340         'chunits' => (int) $this->currentElement['SHOW_WORK_UNITS'],
341         'group_by1' => $this->currentElement['GROUP_BY1'],
342         'group_by2' => $this->currentElement['GROUP_BY2'],
343         'group_by3' => $this->currentElement['GROUP_BY3'],
344         'chtotalsonly' => (int) $this->currentElement['SHOW_TOTALS_ONLY']));
345     }
346     $this->currentTag = '';
347   }
348
349   // dataElement - callback handler for text data fragments. It builds up currentElement array with text pieces from XML.
350   function dataElement($parser, $data) {
351     if ($this->currentTag == 'NAME'
352       || $this->currentTag == 'DESCRIPTION'
353       || $this->currentTag == 'LABEL'
354       || $this->currentTag == 'VALUE'
355       || $this->currentTag == 'COMMENT'
356       || $this->currentTag == 'ADDRESS'
357       || $this->currentTag == 'ALLOW_IP'
358       || $this->currentTag == 'PASSWORD_COMPLEXITY') {
359       if (isset($this->currentElement[$this->currentTag]))
360         $this->currentElement[$this->currentTag] .= trim($data);
361       else
362         $this->currentElement[$this->currentTag] = trim($data);
363     }
364   }
365
366   // importXml - uncompresses the file, reads and parses its content. During parsing,
367   // startElement, endElement, and dataElement functions are called as many times as necessary.
368   // Actual import occurs in the endElement handler.
369   function importXml() {
370     global $i18n;
371
372     // Do we have a compressed file?
373     $compressed = false;
374     $file_ext = substr($_FILES['xmlfile']['name'], strrpos($_FILES['xmlfile']['name'], '.') + 1);
375     if (in_array($file_ext, array('bz','tbz','bz2','tbz2'))) {
376       $compressed = true;
377     }
378
379     // Create a temporary file.
380     $dirName = dirname(TEMPLATE_DIR . '_c/.');
381     $filename = tempnam($dirName, 'import_');
382
383     // If the file is compressed - uncompress it.
384     if ($compressed) {
385       if (!$this->uncompress($_FILES['xmlfile']['tmp_name'], $filename)) {
386         $this->errors->add($i18n->get('error.sys'));
387         return;
388       }
389       unlink($_FILES['xmlfile']['tmp_name']);
390     } else {
391       if (!move_uploaded_file($_FILES['xmlfile']['tmp_name'], $filename)) {
392         $this->errors->add($i18n->get('error.upload'));
393         return;
394       }
395     }
396
397     // Initialize XML parser.
398     $parser = xml_parser_create();
399     xml_set_object($parser, $this);
400     xml_set_element_handler($parser, 'startElement', 'endElement');
401     xml_set_character_data_handler($parser, 'dataElement');
402
403     // Read and parse the content of the file. During parsing, startElement, endElement, and dataElement functions are called.
404     $file = fopen($filename, 'r');
405     while ($data = fread($file, 4096)) {
406       if (!xml_parse($parser, $data, feof($file))) {
407         $this->errors->add(sprintf("XML error: %s at line %d",
408           xml_error_string(xml_get_error_code($parser)),
409           xml_get_current_line_number($parser)));
410       }
411       if (!$this->canImport) {
412         $this->errors->add($i18n->get('error.user_exists'));
413         break;
414       }
415     }
416     xml_parser_free($parser);
417     if ($file) fclose($file);
418     unlink($filename);
419   }
420
421   // uncompress - uncompresses the content of the $in file into the $out file.
422   function uncompress($in, $out) {
423     // Do we have the uncompress function?
424     if (!function_exists('bzopen'))
425       return false;
426
427     // Initial checks of file names and permissions.
428     if (!file_exists($in) || !is_readable ($in))
429       return false;
430     if ((!file_exists($out) && !is_writable(dirname($out))) || (file_exists($out) && !is_writable($out)))
431       return false;
432
433     if (!$out_file = fopen($out, 'wb'))
434       return false;
435     if (!$in_file = bzopen ($in, 'r'))
436       return false;
437
438     while (!feof($in_file)) {
439       $buffer = bzread($in_file, 4096);
440       fwrite($out_file, $buffer, 4096);
441     }
442     bzclose($in_file);
443     fclose ($out_file);
444     return true;
445   }
446
447   // createGroup function creates a new group.
448   private function createGroup($fields) {
449
450     global $user;
451     $mdb2 = getConnection();
452
453     $columns = '(name, currency, decimal_mark, lang, date_format, time_format, week_start, tracking_mode'.
454       ', project_required, task_required, record_type, bcc_email, allow_ip, password_complexity, plugins'.
455       ', lock_spec, workday_minutes, config, created, created_ip, created_by)';
456
457     $values = ' values ('.$mdb2->quote(trim($fields['name']));
458     $values .= ', '.$mdb2->quote(trim($fields['currency']));
459     $values .= ', '.$mdb2->quote($fields['decimal_mark']);
460     $values .= ', '.$mdb2->quote($fields['lang']);
461     $values .= ', '.$mdb2->quote($fields['date_format']);
462     $values .= ', '.$mdb2->quote($fields['time_format']);
463     $values .= ', '.(int)$fields['week_start'];
464     $values .= ', '.(int)$fields['tracking_mode'];
465     $values .= ', '.(int)$fields['project_required'];
466     $values .= ', '.(int)$fields['task_required'];
467     $values .= ', '.(int)$fields['record_type'];
468     $values .= ', '.$mdb2->quote($fields['bcc_email']);
469     $values .= ', '.$mdb2->quote($fields['allow_ip']);
470     $values .= ', '.$mdb2->quote($fields['password_complexity']);
471     $values .= ', '.$mdb2->quote($fields['plugins']);
472     $values .= ', '.$mdb2->quote($fields['lock_spec']);
473     $values .= ', '.(int)$fields['workday_minutes'];
474     $values .= ', '.$mdb2->quote($fields['config']);
475     $values .= ', now(), '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', '.$mdb2->quote($user->id);
476     $values .= ')';
477
478     $sql = 'insert into tt_groups '.$columns.$values;
479     $affected = $mdb2->exec($sql);
480     if (is_a($affected, 'PEAR_Error')) return false;
481
482     $group_id = $mdb2->lastInsertID('tt_groups', 'id');
483
484     // Update org_id with group_id.
485     // NOTE: Both export and import need an additional effort to properly operate on subgroups.
486     // Currently we are importing one group only, which becomes a top level group.
487     $sql = "update tt_groups set org_id = $group_id where org_id is NULL and id = $group_id";
488     $affected = $mdb2->exec($sql);
489     if (is_a($affected, 'PEAR_Error')) return false;
490
491     return $group_id;
492   }
493
494   // insertMonthlyQuota - a helper function to insert a monthly quota.
495   private function insertMonthlyQuota($group_id, $year, $month, $minutes) {
496     $mdb2 = getConnection();
497     $sql = "INSERT INTO tt_monthly_quotas (group_id, year, month, minutes) values ($group_id, $year, $month, $minutes)";
498     $affected = $mdb2->exec($sql);
499     return (!is_a($affected, 'PEAR_Error'));
500   }
501 }