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.
11 // | There are only two ways to violate the license:
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).
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).
21 // | This license applies to this document only, not any other software
22 // | that it may be combined with.
24 // +----------------------------------------------------------------------+
26 // | https://www.anuko.com/time_tracker/credits.htm
27 // +----------------------------------------------------------------------+
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');
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.
45 var $currentElement = array(); // Current element of the XML file we are parsing.
46 var $currentTag = ''; // XML tag of the current element.
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.
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.
65 var $customFieldMap = array(); // Custom field ids.
66 var $customFieldOptionMap = array(); // Custop field option ids.
67 var $logMap = array(); // Time log ids.
70 function __construct(&$errors) {
71 $this->errors = &$errors;
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) {
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'
93 $this->currentElement = $attrs;
95 $this->currentTag = $name;
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();
108 if ($name == 'ROLE') {
109 $this->roles[$this->currentElement['ID']] = $this->currentElement;
110 $this->currentElement = array();
112 if ($name == 'USER') {
113 $this->users[$this->currentElement['ID']] = $this->currentElement;
114 $this->currentElement = array();
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;
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']));
148 $this->org_id = $group_id;
149 $this->group_id = $group_id;
152 foreach ($this->roles as $key=>$role_item) {
153 $role_id = ttRoleHelper::insert(array(
154 'group_id' => $this->group_id,
155 'org_id' => $this->org_id,
156 'name' => $role_item['NAME'],
157 'description' => $role_item['DESCRIPTION'],
158 'rank' => $role_item['RANK'],
159 'rights' => $role_item['RIGHTS'],
160 'status' => $role_item['STATUS']));
161 $this->roleMap[$role_item['ID']] = $role_id;
164 foreach ($this->users as $key=>$user_item) {
165 $role_id = $user_item['ROLE_ID'] === '0' ? $this->top_role_id : $this->roleMap[$user_item['ROLE_ID']]; // 0 (not null) means top manager role.
166 $user_id = ttUserHelper::insert(array(
167 'group_id' => $this->group_id,
168 'org_id' => $this->org_id,
169 'role_id' => $role_id,
170 'client_id' => $user_item['CLIENT_ID'], // Note: NOT mapped value, replaced in CLIENT handler.
171 'name' => $user_item['NAME'],
172 'login' => $user_item['LOGIN'],
173 'password' => $user_item['PASSWORD'],
174 'rate' => $user_item['RATE'],
175 'email' => $user_item['EMAIL'],
176 'status' => $user_item['STATUS']), false);
177 $this->userMap[$key] = $user_id;
183 if ($name == 'TASK' && $this->canImport) {
184 $this->taskMap[$this->currentElement['ID']] =
185 ttTaskHelper::insert(array(
186 'group_id' => $this->group_id,
187 'org_id' => $this->org_id,
188 'name' => $this->currentElement['NAME'],
189 'description' => $this->currentElement['DESCRIPTION'],
190 'status' => $this->currentElement['STATUS']));
192 if ($name == 'PROJECT' && $this->canImport) {
193 // Prepare a list of task ids.
194 $tasks = explode(',', $this->currentElement['TASKS']);
195 foreach ($tasks as $id)
196 $mapped_tasks[] = $this->taskMap[$id];
198 // Add a new project.
199 $this->projectMap[$this->currentElement['ID']] =
200 ttProjectHelper::insert(array(
201 'group_id' => $this->group_id,
202 'org_id' => $this->org_id,
203 'name' => $this->currentElement['NAME'],
204 'description' => $this->currentElement['DESCRIPTION'],
205 'tasks' => $mapped_tasks,
206 'status' => $this->currentElement['STATUS']));
208 if ($name == 'USER_PROJECT_BIND' && $this->canImport) {
209 ttUserHelper::insertBind(
210 $this->userMap[$this->currentElement['USER_ID']],
211 $this->projectMap[$this->currentElement['PROJECT_ID']],
212 $this->currentElement['RATE'],
213 $this->currentElement['STATUS']);
216 if ($name == 'CLIENT' && $this->canImport) {
217 // Prepare a list of project ids.
218 if ($this->currentElement['PROJECTS']) {
219 $projects = explode(',', $this->currentElement['PROJECTS']);
220 foreach ($projects as $id)
221 $mapped_projects[] = $this->projectMap[$id];
224 $this->clientMap[$this->currentElement['ID']] =
225 ttClientHelper::insert(array(
226 'group_id' => $this->group_id,
227 'org_id' => $this->org_id,
228 'name' => $this->currentElement['NAME'],
229 'address' => $this->currentElement['ADDRESS'],
230 'tax' => $this->currentElement['TAX'],
231 'projects' => $mapped_projects,
232 'status' => $this->currentElement['STATUS']));
234 // Update client_id for tt_users to a mapped value.
235 // We did not do it during user insertion because clientMap was not ready then.
236 if ($this->currentElement['ID'] != $this->clientMap[$this->currentElement['ID']])
237 ttClientHelper::setMappedClient($this->group_id, $this->currentElement['ID'], $this->clientMap[$this->currentElement['ID']]);
240 if ($name == 'INVOICE' && $this->canImport) {
241 $this->invoiceMap[$this->currentElement['ID']] =
242 ttInvoiceHelper::insert(array(
243 'group_id' => $this->group_id,
244 'name' => $this->currentElement['NAME'],
245 'date' => $this->currentElement['DATE'],
246 'client_id' => $this->clientMap[$this->currentElement['CLIENT_ID']],
247 'discount' => $this->currentElement['DISCOUNT'],
248 'status' => $this->currentElement['STATUS']));
251 if ($name == 'MONTHLY_QUOTA' && $this->canImport) {
252 $this->insertMonthlyQuota($this->group_id, $this->currentElement['YEAR'], $this->currentElement['MONTH'], $this->currentElement['MINUTES']);
255 if ($name == 'LOG_ITEM' && $this->canImport) {
256 $this->logMap[$this->currentElement['ID']] =
257 ttTimeHelper::insert(array(
258 'user_id' => $this->userMap[$this->currentElement['USER_ID']],
259 'group_id' => $this->group_id,
260 'date' => $this->currentElement['DATE'],
261 'start' => $this->currentElement['START'],
262 'finish' => $this->currentElement['FINISH'],
263 'duration' => $this->currentElement['DURATION'],
264 'client' => $this->clientMap[$this->currentElement['CLIENT_ID']],
265 'project' => $this->projectMap[$this->currentElement['PROJECT_ID']],
266 'task' => $this->taskMap[$this->currentElement['TASK_ID']],
267 'invoice' => $this->invoiceMap[$this->currentElement['INVOICE_ID']],
268 'note' => (isset($this->currentElement['COMMENT']) ? $this->currentElement['COMMENT'] : ''),
269 'billable' => $this->currentElement['BILLABLE'],
270 'paid' => $this->currentElement['PAID'],
271 'status' => $this->currentElement['STATUS']));
274 if ($name == 'CUSTOM_FIELD' && $this->canImport) {
275 $this->customFieldMap[$this->currentElement['ID']] =
276 ttCustomFieldHelper::insertField(array(
277 'group_id' => $this->group_id,
278 'type' => $this->currentElement['TYPE'],
279 'label' => $this->currentElement['LABEL'],
280 'required' => $this->currentElement['REQUIRED'],
281 'status' => $this->currentElement['STATUS']));
284 if ($name == 'CUSTOM_FIELD_OPTION' && $this->canImport) {
285 $this->customFieldOptionMap[$this->currentElement['ID']] =
286 ttCustomFieldHelper::insertOption(array(
287 'field_id' => $this->customFieldMap[$this->currentElement['FIELD_ID']],
288 'value' => $this->currentElement['VALUE']));
291 if ($name == 'CUSTOM_FIELD_LOG_ENTRY' && $this->canImport) {
292 ttCustomFieldHelper::insertLogEntry(array(
293 'log_id' => $this->logMap[$this->currentElement['LOG_ID']],
294 'field_id' => $this->customFieldMap[$this->currentElement['FIELD_ID']],
295 'option_id' => $this->customFieldOptionMap[$this->currentElement['OPTION_ID']],
296 'value' => $this->currentElement['VALUE'],
297 'status' => $this->currentElement['STATUS']));
300 if ($name == 'EXPENSE_ITEM' && $this->canImport) {
301 ttExpenseHelper::insert(array(
302 'date' => $this->currentElement['DATE'],
303 'user_id' => $this->userMap[$this->currentElement['USER_ID']],
304 'group_id' => $this->group_id,
305 'client_id' => $this->clientMap[$this->currentElement['CLIENT_ID']],
306 'project_id' => $this->projectMap[$this->currentElement['PROJECT_ID']],
307 'name' => $this->currentElement['NAME'],
308 'cost' => $this->currentElement['COST'],
309 'invoice_id' => $this->invoiceMap[$this->currentElement['INVOICE_ID']],
310 'paid' => $this->currentElement['PAID'],
311 'status' => $this->currentElement['STATUS']));
314 if ($name == 'FAV_REPORT' && $this->canImport) {
316 if (strlen($this->currentElement['USERS']) > 0) {
317 $arr = explode(',', $this->currentElement['USERS']);
319 $user_list .= (strlen($user_list) == 0 ? '' : ',').$this->userMap[$v];
321 ttFavReportHelper::insertReport(array(
322 'name' => $this->currentElement['NAME'],
323 'user_id' => $this->userMap[$this->currentElement['USER_ID']],
324 'client' => $this->clientMap[$this->currentElement['CLIENT_ID']],
325 'option' => $this->customFieldOptionMap[$this->currentElement['CF_1_OPTION_ID']],
326 'project' => $this->projectMap[$this->currentElement['PROJECT_ID']],
327 'task' => $this->taskMap[$this->currentElement['TASK_ID']],
328 'billable' => $this->currentElement['BILLABLE'],
329 'users' => $user_list,
330 'period' => $this->currentElement['PERIOD'],
331 'from' => $this->currentElement['PERIOD_START'],
332 'to' => $this->currentElement['PERIOD_END'],
333 'chclient' => (int) $this->currentElement['SHOW_CLIENT'],
334 'chinvoice' => (int) $this->currentElement['SHOW_INVOICE'],
335 'chpaid' => (int) $this->currentElement['SHOW_PAID'],
336 'chip' => (int) $this->currentElement['SHOW_IP'],
337 'chproject' => (int) $this->currentElement['SHOW_PROJECT'],
338 'chstart' => (int) $this->currentElement['SHOW_START'],
339 'chduration' => (int) $this->currentElement['SHOW_DURATION'],
340 'chcost' => (int) $this->currentElement['SHOW_COST'],
341 'chtask' => (int) $this->currentElement['SHOW_TASK'],
342 'chfinish' => (int) $this->currentElement['SHOW_END'],
343 'chnote' => (int) $this->currentElement['SHOW_NOTE'],
344 'chcf_1' => (int) $this->currentElement['SHOW_CUSTOM_FIELD_1'],
345 'chunits' => (int) $this->currentElement['SHOW_WORK_UNITS'],
346 'group_by1' => $this->currentElement['GROUP_BY1'],
347 'group_by2' => $this->currentElement['GROUP_BY2'],
348 'group_by3' => $this->currentElement['GROUP_BY3'],
349 'chtotalsonly' => (int) $this->currentElement['SHOW_TOTALS_ONLY']));
351 $this->currentTag = '';
354 // dataElement - callback handler for text data fragments. It builds up currentElement array with text pieces from XML.
355 function dataElement($parser, $data) {
356 if ($this->currentTag == 'NAME'
357 || $this->currentTag == 'DESCRIPTION'
358 || $this->currentTag == 'LABEL'
359 || $this->currentTag == 'VALUE'
360 || $this->currentTag == 'COMMENT'
361 || $this->currentTag == 'ADDRESS'
362 || $this->currentTag == 'ALLOW_IP'
363 || $this->currentTag == 'PASSWORD_COMPLEXITY') {
364 if (isset($this->currentElement[$this->currentTag]))
365 $this->currentElement[$this->currentTag] .= trim($data);
367 $this->currentElement[$this->currentTag] = trim($data);
371 // importXml - uncompresses the file, reads and parses its content. During parsing,
372 // startElement, endElement, and dataElement functions are called as many times as necessary.
373 // Actual import occurs in the endElement handler.
374 function importXml() {
377 // Do we have a compressed file?
379 $file_ext = substr($_FILES['xmlfile']['name'], strrpos($_FILES['xmlfile']['name'], '.') + 1);
380 if (in_array($file_ext, array('bz','tbz','bz2','tbz2'))) {
384 // Create a temporary file.
385 $dirName = dirname(TEMPLATE_DIR . '_c/.');
386 $filename = tempnam($dirName, 'import_');
388 // If the file is compressed - uncompress it.
390 if (!$this->uncompress($_FILES['xmlfile']['tmp_name'], $filename)) {
391 $this->errors->add($i18n->get('error.sys'));
394 unlink($_FILES['xmlfile']['tmp_name']);
396 if (!move_uploaded_file($_FILES['xmlfile']['tmp_name'], $filename)) {
397 $this->errors->add($i18n->get('error.upload'));
402 // Initialize XML parser.
403 $parser = xml_parser_create();
404 xml_set_object($parser, $this);
405 xml_set_element_handler($parser, 'startElement', 'endElement');
406 xml_set_character_data_handler($parser, 'dataElement');
408 // Read and parse the content of the file. During parsing, startElement, endElement, and dataElement functions are called.
409 $file = fopen($filename, 'r');
410 while ($data = fread($file, 4096)) {
411 if (!xml_parse($parser, $data, feof($file))) {
412 $this->errors->add(sprintf("XML error: %s at line %d",
413 xml_error_string(xml_get_error_code($parser)),
414 xml_get_current_line_number($parser)));
416 if (!$this->canImport) {
417 $this->errors->add($i18n->get('error.user_exists'));
421 xml_parser_free($parser);
422 if ($file) fclose($file);
426 // uncompress - uncompresses the content of the $in file into the $out file.
427 function uncompress($in, $out) {
428 // Do we have the uncompress function?
429 if (!function_exists('bzopen'))
432 // Initial checks of file names and permissions.
433 if (!file_exists($in) || !is_readable ($in))
435 if ((!file_exists($out) && !is_writable(dirname($out))) || (file_exists($out) && !is_writable($out)))
438 if (!$out_file = fopen($out, 'wb'))
440 if (!$in_file = bzopen ($in, 'r'))
443 while (!feof($in_file)) {
444 $buffer = bzread($in_file, 4096);
445 fwrite($out_file, $buffer, 4096);
452 // createGroup function creates a new group.
453 private function createGroup($fields) {
456 $mdb2 = getConnection();
458 $columns = '(name, currency, decimal_mark, lang, date_format, time_format, week_start, tracking_mode'.
459 ', project_required, task_required, record_type, bcc_email, allow_ip, password_complexity, plugins'.
460 ', lock_spec, workday_minutes, config, created, created_ip, created_by)';
462 $values = ' values ('.$mdb2->quote(trim($fields['name']));
463 $values .= ', '.$mdb2->quote(trim($fields['currency']));
464 $values .= ', '.$mdb2->quote($fields['decimal_mark']);
465 $values .= ', '.$mdb2->quote($fields['lang']);
466 $values .= ', '.$mdb2->quote($fields['date_format']);
467 $values .= ', '.$mdb2->quote($fields['time_format']);
468 $values .= ', '.(int)$fields['week_start'];
469 $values .= ', '.(int)$fields['tracking_mode'];
470 $values .= ', '.(int)$fields['project_required'];
471 $values .= ', '.(int)$fields['task_required'];
472 $values .= ', '.(int)$fields['record_type'];
473 $values .= ', '.$mdb2->quote($fields['bcc_email']);
474 $values .= ', '.$mdb2->quote($fields['allow_ip']);
475 $values .= ', '.$mdb2->quote($fields['password_complexity']);
476 $values .= ', '.$mdb2->quote($fields['plugins']);
477 $values .= ', '.$mdb2->quote($fields['lock_spec']);
478 $values .= ', '.(int)$fields['workday_minutes'];
479 $values .= ', '.$mdb2->quote($fields['config']);
480 $values .= ', now(), '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', '.$mdb2->quote($user->id);
483 $sql = 'insert into tt_groups '.$columns.$values;
484 $affected = $mdb2->exec($sql);
485 if (is_a($affected, 'PEAR_Error')) return false;
487 $group_id = $mdb2->lastInsertID('tt_groups', 'id');
489 // Update org_id with group_id.
490 // NOTE: Both export and import need an additional effort to properly operate on subgroups.
491 // Currently we are importing one group only, which becomes a top level group.
492 $sql = "update tt_groups set org_id = $group_id where org_id is NULL and id = $group_id";
493 $affected = $mdb2->exec($sql);
494 if (is_a($affected, 'PEAR_Error')) return false;
499 // insertMonthlyQuota - a helper function to insert a monthly quota.
500 private function insertMonthlyQuota($group_id, $year, $month, $minutes) {
501 $mdb2 = getConnection();
502 $sql = "INSERT INTO tt_monthly_quotas (group_id, year, month, minutes) values ($group_id, $year, $month, $minutes)";
503 $affected = $mdb2->exec($sql);
504 return (!is_a($affected, 'PEAR_Error'));