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 // ttImportHelper2 - this class is a future replacement for ttImportHelper.
42 // Currently, it is work in progress.
43 // When done, it should handle import of complex groups consisting of other groups.
44 class ttImportHelper2 {
45 var $errors = null; // Errors go here. Set in constructor by reference.
47 var $currentElement = array(); // Current element of the XML file we are parsing.
48 var $currentTag = ''; // XML tag of the current element.
50 var $canImport = true; // False if we cannot import data due to a login collision.
51 var $groupData = array(); // Array of group data such as group name, etc.
52 var $org_id = null; // New organization id we are importing. It is created during the import operation.
53 var $group_id = null; // New group id we are importing. It is created during the import operation.
54 var $roles = array(); // Array of arrays of role properties.
55 var $users = array(); // Array of arrays of user properties.
56 var $top_role_id = null; // Top manager role id on the new server.
58 // The following arrays are maps between entity ids in the file versus the database.
59 // In the file they are sequential (1,2,3...) while in the database the entities have different ids.
60 var $roleMap = array(); // Role ids.
61 var $userMap = array(); // User ids.
62 var $projectMap = array(); // Project ids.
63 var $taskMap = array(); // Task ids.
64 var $clientMap = array(); // Client ids.
65 var $invoiceMap = array(); // Invoice ids.
67 var $customFieldMap = array(); // Custom field ids.
68 var $customFieldOptionMap = array(); // Custop field option ids.
69 var $logMap = array(); // Time log ids.
72 function ttImportHelper(&$errors) {
73 $this->errors = &$errors;
76 // startElement - callback handler for opening tag of an XML element.
77 // In this function we assign passed in attributes to currentElement.
78 function startElement($parser, $name, $attrs) {
85 || $name == 'MONTHLY_QUOTA'
86 || $name == 'LOG_ITEM'
87 || $name == 'CUSTOM_FIELD'
88 || $name == 'CUSTOM_FIELD_OPTION'
89 || $name == 'CUSTOM_FIELD_LOG_ENTRY'
90 || $name == 'INVOICE_HEADER'
91 || $name == 'USER_PROJECT_BIND'
92 || $name == 'EXPENSE_ITEM'
93 || $name == 'FAV_REPORT'
95 $this->currentElement = $attrs;
97 $this->currentTag = $name;
100 // endElement - callback handler for the closing tag of an XML element.
101 // When we are here, currentElement is an array of the element attributes (as set in startElement).
102 // Here we do the actual import of data into the database.
103 function endElement($parser, $name) {
104 if ($name == 'GROUP') {
105 $this->groupData = $this->currentElement;
106 // Now groupData is an array of group properties. We'll use it later to create a group.
107 // Cannot create the group here. Need to determine whether logins collide with existing logins.
108 $this->currentElement = array();
110 if ($name == 'ROLE') {
111 $this->roles[$this->currentElement['ID']] = $this->currentElement;
112 $this->currentElement = array();
114 if ($name == 'USER') {
115 $this->users[$this->currentElement['ID']] = $this->currentElement;
116 $this->currentElement = array();
118 if ($name == 'USERS') {
119 foreach ($this->users as $user_item) {
120 if (('' != $user_item['STATUS']) && ttUserHelper::getUserByLogin($user_item['LOGIN'])) {
121 // We have a login collision, cannot import any data.
122 $this->canImport = false;
127 // Now we can create a group.
128 if ($this->canImport) {
129 $this->top_role_id = ttRoleHelper::getRoleByRank(512, 0);
130 $group_id = $this->createGroup(array(
131 'name' => $this->groupData['NAME'],
132 'currency' => $this->groupData['CURRENCY'],
133 'decimal_mark' => $this->groupData['DECIMAL_MARK'],
134 'lang' => $this->groupData['LANG'],
135 'date_format' => $this->groupData['DATE_FORMAT'],
136 'time_format' => $this->groupData['TIME_FORMAT'],
137 'week_start' => $this->groupData['WEEK_START'],
138 'tracking_mode' => $this->groupData['TRACKING_MODE'],
139 'project_required' => $this->groupData['PROJECT_REQUIRED'],
140 'task_required' => $this->groupData['TASK_REQUIRED'],
141 'record_type' => $this->groupData['RECORD_TYPE'],
142 'bcc_email' => $this->groupData['BCC_EMAIL'],
143 'allow_ip' => $this->groupData['ALLOW_IP'],
144 'password_complexity' => $this->groupData['PASSWORD_COMPLEXITY'],
145 'plugins' => $this->groupData['PLUGINS'],
146 'lock_spec' => $this->groupData['LOCK_SPEC'],
147 'workday_minutes' => $this->groupData['WORKDAY_MINUTES'],
148 'config' => $this->groupData['CONFIG']));
150 $this->org_id = $group_id;
151 $this->group_id = $group_id;
154 foreach ($this->roles as $key=>$role_item) {
155 $role_id = ttRoleHelper::insert(array(
156 'group_id' => $this->group_id,
157 'name' => $role_item['NAME'],
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 'name' => $this->currentElement['NAME'],
188 'description' => $this->currentElement['DESCRIPTION'],
189 'status' => $this->currentElement['STATUS']));
191 if ($name == 'PROJECT' && $this->canImport) {
192 // Prepare a list of task ids.
193 $tasks = explode(',', $this->currentElement['TASKS']);
194 foreach ($tasks as $id)
195 $mapped_tasks[] = $this->taskMap[$id];
197 // Add a new project.
198 $this->projectMap[$this->currentElement['ID']] =
199 ttProjectHelper::insert(array(
200 'group_id' => $this->group_id,
201 'name' => $this->currentElement['NAME'],
202 'description' => $this->currentElement['DESCRIPTION'],
203 'tasks' => $mapped_tasks,
204 'status' => $this->currentElement['STATUS']));
206 if ($name == 'USER_PROJECT_BIND' && $this->canImport) {
207 ttUserHelper::insertBind(
208 $this->userMap[$this->currentElement['USER_ID']],
209 $this->projectMap[$this->currentElement['PROJECT_ID']],
210 $this->currentElement['RATE'],
211 $this->currentElement['STATUS']);
214 if ($name == 'CLIENT' && $this->canImport) {
215 // Prepare a list of project ids.
216 if ($this->currentElement['PROJECTS']) {
217 $projects = explode(',', $this->currentElement['PROJECTS']);
218 foreach ($projects as $id)
219 $mapped_projects[] = $this->projectMap[$id];
222 $this->clientMap[$this->currentElement['ID']] =
223 ttClientHelper::insert(array(
224 'group_id' => $this->group_id,
225 'name' => $this->currentElement['NAME'],
226 'address' => $this->currentElement['ADDRESS'],
227 'tax' => $this->currentElement['TAX'],
228 'projects' => $mapped_projects,
229 'status' => $this->currentElement['STATUS']));
231 // Update client_id for tt_users to a mapped value.
232 // We did not do it during user insertion because clientMap was not ready then.
233 if ($this->currentElement['ID'] != $this->clientMap[$this->currentElement['ID']])
234 ttClientHelper::setMappedClient($this->group_id, $this->currentElement['ID'], $this->clientMap[$this->currentElement['ID']]);
237 if ($name == 'INVOICE' && $this->canImport) {
238 $this->invoiceMap[$this->currentElement['ID']] =
239 ttInvoiceHelper::insert(array(
240 'group_id' => $this->group_id,
241 'name' => $this->currentElement['NAME'],
242 'date' => $this->currentElement['DATE'],
243 'client_id' => $this->clientMap[$this->currentElement['CLIENT_ID']],
244 'discount' => $this->currentElement['DISCOUNT'],
245 'status' => $this->currentElement['STATUS']));
248 if ($name == 'MONTHLY_QUOTA' && $this->canImport) {
249 $this->insertMonthlyQuota($this->group_id, $this->currentElement['YEAR'], $this->currentElement['MONTH'], $this->currentElement['MINUTES']);
252 if ($name == 'LOG_ITEM' && $this->canImport) {
253 $this->logMap[$this->currentElement['ID']] =
254 ttTimeHelper::insert(array(
255 'user_id' => $this->userMap[$this->currentElement['USER_ID']],
256 'group_id' => $this->group_id,
257 'date' => $this->currentElement['DATE'],
258 'start' => $this->currentElement['START'],
259 'finish' => $this->currentElement['FINISH'],
260 'duration' => $this->currentElement['DURATION'],
261 'client' => $this->clientMap[$this->currentElement['CLIENT_ID']],
262 'project' => $this->projectMap[$this->currentElement['PROJECT_ID']],
263 'task' => $this->taskMap[$this->currentElement['TASK_ID']],
264 'invoice' => $this->invoiceMap[$this->currentElement['INVOICE_ID']],
265 'note' => (isset($this->currentElement['COMMENT']) ? $this->currentElement['COMMENT'] : ''),
266 'billable' => $this->currentElement['BILLABLE'],
267 'paid' => $this->currentElement['PAID'],
268 'status' => $this->currentElement['STATUS']));
271 if ($name == 'CUSTOM_FIELD' && $this->canImport) {
272 $this->customFieldMap[$this->currentElement['ID']] =
273 ttCustomFieldHelper::insertField(array(
274 'group_id' => $this->group_id,
275 'type' => $this->currentElement['TYPE'],
276 'label' => $this->currentElement['LABEL'],
277 'required' => $this->currentElement['REQUIRED'],
278 'status' => $this->currentElement['STATUS']));
281 if ($name == 'CUSTOM_FIELD_OPTION' && $this->canImport) {
282 $this->customFieldOptionMap[$this->currentElement['ID']] =
283 ttCustomFieldHelper::insertOption(array(
284 'field_id' => $this->customFieldMap[$this->currentElement['FIELD_ID']],
285 'value' => $this->currentElement['VALUE']));
288 if ($name == 'CUSTOM_FIELD_LOG_ENTRY' && $this->canImport) {
289 ttCustomFieldHelper::insertLogEntry(array(
290 'log_id' => $this->logMap[$this->currentElement['LOG_ID']],
291 'field_id' => $this->customFieldMap[$this->currentElement['FIELD_ID']],
292 'option_id' => $this->customFieldOptionMap[$this->currentElement['OPTION_ID']],
293 'value' => $this->currentElement['VALUE'],
294 'status' => $this->currentElement['STATUS']));
297 if ($name == 'EXPENSE_ITEM' && $this->canImport) {
298 ttExpenseHelper::insert(array(
299 'date' => $this->currentElement['DATE'],
300 'user_id' => $this->userMap[$this->currentElement['USER_ID']],
301 'group_id' => $this->group_id,
302 'client_id' => $this->clientMap[$this->currentElement['CLIENT_ID']],
303 'project_id' => $this->projectMap[$this->currentElement['PROJECT_ID']],
304 'name' => $this->currentElement['NAME'],
305 'cost' => $this->currentElement['COST'],
306 'invoice_id' => $this->invoiceMap[$this->currentElement['INVOICE_ID']],
307 'paid' => $this->currentElement['PAID'],
308 'status' => $this->currentElement['STATUS']));
311 if ($name == 'FAV_REPORT' && $this->canImport) {
313 if (strlen($this->currentElement['USERS']) > 0) {
314 $arr = explode(',', $this->currentElement['USERS']);
316 $user_list .= (strlen($user_list) == 0 ? '' : ',').$this->userMap[$v];
318 ttFavReportHelper::insertReport(array(
319 'name' => $this->currentElement['NAME'],
320 'user_id' => $this->userMap[$this->currentElement['USER_ID']],
321 'client' => $this->clientMap[$this->currentElement['CLIENT_ID']],
322 'option' => $this->customFieldOptionMap[$this->currentElement['CF_1_OPTION_ID']],
323 'project' => $this->projectMap[$this->currentElement['PROJECT_ID']],
324 'task' => $this->taskMap[$this->currentElement['TASK_ID']],
325 'billable' => $this->currentElement['BILLABLE'],
326 'users' => $user_list,
327 'period' => $this->currentElement['PERIOD'],
328 'from' => $this->currentElement['PERIOD_START'],
329 'to' => $this->currentElement['PERIOD_END'],
330 'chclient' => (int) $this->currentElement['SHOW_CLIENT'],
331 'chinvoice' => (int) $this->currentElement['SHOW_INVOICE'],
332 'chpaid' => (int) $this->currentElement['SHOW_PAID'],
333 'chip' => (int) $this->currentElement['SHOW_IP'],
334 'chproject' => (int) $this->currentElement['SHOW_PROJECT'],
335 'chstart' => (int) $this->currentElement['SHOW_START'],
336 'chduration' => (int) $this->currentElement['SHOW_DURATION'],
337 'chcost' => (int) $this->currentElement['SHOW_COST'],
338 'chtask' => (int) $this->currentElement['SHOW_TASK'],
339 'chfinish' => (int) $this->currentElement['SHOW_END'],
340 'chnote' => (int) $this->currentElement['SHOW_NOTE'],
341 'chcf_1' => (int) $this->currentElement['SHOW_CUSTOM_FIELD_1'],
342 'chunits' => (int) $this->currentElement['SHOW_WORK_UNITS'],
343 'group_by1' => $this->currentElement['GROUP_BY1'],
344 'group_by2' => $this->currentElement['GROUP_BY2'],
345 'group_by3' => $this->currentElement['GROUP_BY3'],
346 'chtotalsonly' => (int) $this->currentElement['SHOW_TOTALS_ONLY']));
348 $this->currentTag = '';
351 // dataElement - callback handler for text data fragments. It builds up currentElement array with text pieces from XML.
352 function dataElement($parser, $data) {
353 if ($this->currentTag == 'NAME'
354 || $this->currentTag == 'DESCRIPTION'
355 || $this->currentTag == 'LABEL'
356 || $this->currentTag == 'VALUE'
357 || $this->currentTag == 'COMMENT'
358 || $this->currentTag == 'ADDRESS'
359 || $this->currentTag == 'ALLOW_IP'
360 || $this->currentTag == 'PASSWORD_COMPLEXITY') {
361 if (isset($this->currentElement[$this->currentTag]))
362 $this->currentElement[$this->currentTag] .= trim($data);
364 $this->currentElement[$this->currentTag] = trim($data);
368 // importXml - uncompresses the file, reads and parses its content. During parsing,
369 // startElement, endElement, and dataElement functions are called as many times as necessary.
370 // Actual import occurs in the endElement handler.
371 function importXml() {
374 // Do we have a compressed file?
376 $file_ext = substr($_FILES['xmlfile']['name'], strrpos($_FILES['xmlfile']['name'], '.') + 1);
377 if (in_array($file_ext, array('bz','tbz','bz2','tbz2'))) {
381 // Create a temporary file.
382 $dirName = dirname(TEMPLATE_DIR . '_c/.');
383 $filename = tempnam($dirName, 'import_');
385 // If the file is compressed - uncompress it.
387 if (!$this->uncompress($_FILES['xmlfile']['tmp_name'], $filename)) {
388 $this->errors->add($i18n->get('error.sys'));
391 unlink($_FILES['xmlfile']['tmp_name']);
393 if (!move_uploaded_file($_FILES['xmlfile']['tmp_name'], $filename)) {
394 $this->errors->add($i18n->get('error.upload'));
399 // Initialize XML parser.
400 $parser = xml_parser_create();
401 xml_set_object($parser, $this);
402 xml_set_element_handler($parser, 'startElement', 'endElement');
403 xml_set_character_data_handler($parser, 'dataElement');
405 // Read and parse the content of the file. During parsing, startElement, endElement, and dataElement functions are called.
406 $file = fopen($filename, 'r');
407 while ($data = fread($file, 4096)) {
408 if (!xml_parse($parser, $data, feof($file))) {
409 $this->errors->add(sprintf("XML error: %s at line %d",
410 xml_error_string(xml_get_error_code($parser)),
411 xml_get_current_line_number($parser)));
413 if (!$this->canImport) {
414 $this->errors->add($i18n->get('error.user_exists'));
418 xml_parser_free($parser);
419 if ($file) fclose($file);
423 // uncompress - uncompresses the content of the $in file into the $out file.
424 function uncompress($in, $out) {
425 // Do we have the uncompress function?
426 if (!function_exists('bzopen'))
429 // Initial checks of file names and permissions.
430 if (!file_exists($in) || !is_readable ($in))
432 if ((!file_exists($out) && !is_writable(dirname($out))) || (file_exists($out) && !is_writable($out)))
435 if (!$out_file = fopen($out, 'wb'))
437 if (!$in_file = bzopen ($in, 'r'))
440 while (!feof($in_file)) {
441 $buffer = bzread($in_file, 4096);
442 fwrite($out_file, $buffer, 4096);
449 // createGroup function creates a new group.
450 private function createGroup($fields) {
453 $mdb2 = getConnection();
455 $columns = '(name, currency, decimal_mark, lang, date_format, time_format, week_start, tracking_mode'.
456 ', project_required, task_required, record_type, bcc_email, allow_ip, password_complexity, plugins'.
457 ', lock_spec, workday_minutes, config, created, created_ip, created_by)';
459 $values = ' values ('.$mdb2->quote(trim($fields['name']));
460 $values .= ', '.$mdb2->quote(trim($fields['currency']));
461 $values .= ', '.$mdb2->quote($fields['decimal_mark']);
462 $values .= ', '.$mdb2->quote($fields['lang']);
463 $values .= ', '.$mdb2->quote($fields['date_format']);
464 $values .= ', '.$mdb2->quote($fields['time_format']);
465 $values .= ', '.(int)$fields['week_start'];
466 $values .= ', '.(int)$fields['tracking_mode'];
467 $values .= ', '.(int)$fields['project_required'];
468 $values .= ', '.(int)$fields['task_required'];
469 $values .= ', '.(int)$fields['record_type'];
470 $values .= ', '.$mdb2->quote($fields['bcc_email']);
471 $values .= ', '.$mdb2->quote($fields['allow_ip']);
472 $values .= ', '.$mdb2->quote($fields['password_complexity']);
473 $values .= ', '.$mdb2->quote($fields['plugins']);
474 $values .= ', '.$mdb2->quote($fields['lock_spec']);
475 $values .= ', '.(int)$fields['workday_minutes'];
476 $values .= ', '.$mdb2->quote($fields['config']);
477 $values .= ', now(), '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', '.$mdb2->quote($user->id);
480 $sql = 'insert into tt_groups '.$columns.$values;
481 $affected = $mdb2->exec($sql);
482 if (is_a($affected, 'PEAR_Error')) return false;
484 $group_id = $mdb2->lastInsertID('tt_groups', 'id');
486 // Update org_id with group_id.
487 // NOTE: Both export and import need an additional effort to properly operate on subgroups.
488 // Currently we are importing one group only, which becomes a top level group.
489 $sql = "update tt_groups set org_id = $group_id where org_id is NULL and id = $group_id";
490 $affected = $mdb2->exec($sql);
491 if (is_a($affected, 'PEAR_Error')) return false;
496 // insertMonthlyQuota - a helper function to insert a monthly quota.
497 private function insertMonthlyQuota($group_id, $year, $month, $minutes) {
498 $mdb2 = getConnection();
499 $sql = "INSERT INTO tt_monthly_quotas (group_id, year, month, minutes) values ($group_id, $year, $month, $minutes)";
500 $affected = $mdb2->exec($sql);
501 return (!is_a($affected, 'PEAR_Error'));