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