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