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