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