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 $group_id = null; // New group id we are importing. It is created during the import operation.
51 var $roles = array(); // Array of arrays of role properties.
52 var $users = array(); // Array of arrays of user properties.
53 var $top_role_id = null; // Top manager role id on the new server.
55 // The following arrays are maps between entity ids in the file versus the database.
56 // In the file they are sequential (1,2,3...) while in the database the entities have different ids.
57 var $roleMap = array(); // Role ids.
58 var $userMap = array(); // User ids.
59 var $projectMap = array(); // Project ids.
60 var $taskMap = array(); // Task ids.
61 var $clientMap = array(); // Client ids.
62 var $invoiceMap = array(); // Invoice ids.
64 var $customFieldMap = array(); // Custom field ids.
65 var $customFieldOptionMap = array(); // Custop field option ids.
66 var $logMap = array(); // Time log ids.
69 function ttImportHelper(&$errors) {
70 $this->errors = &$errors;
73 // startElement - callback handler for opening tag of an XML element.
74 // In this function we assign passed in attributes to currentElement.
75 function startElement($parser, $name, $attrs) {
82 || $name == 'MONTHLY_QUOTA'
83 || $name == 'LOG_ITEM'
84 || $name == 'CUSTOM_FIELD'
85 || $name == 'CUSTOM_FIELD_OPTION'
86 || $name == 'CUSTOM_FIELD_LOG_ENTRY'
87 || $name == 'INVOICE_HEADER'
88 || $name == 'USER_PROJECT_BIND'
89 || $name == 'EXPENSE_ITEM'
90 || $name == 'FAV_REPORT'
92 $this->currentElement = $attrs;
94 $this->currentTag = $name;
97 // endElement - callback handler for the closing tag of an XML element.
98 // When we are here, currentElement is an array of the element attributes (as set in startElement).
99 // Here we do the actual import of data into the database.
100 function endElement($parser, $name) {
101 if ($name == 'GROUP') {
102 $this->groupData = $this->currentElement;
103 // Now groupData is an array of group properties. We'll use it later to create a group.
104 // Cannot create the group here. Need to determine whether logins collide with existing logins.
105 $this->currentElement = array();
107 if ($name == 'ROLE') {
108 $this->roles[$this->currentElement['ID']] = $this->currentElement;
109 $this->currentElement = array();
111 if ($name == 'USER') {
112 $this->users[$this->currentElement['ID']] = $this->currentElement;
113 $this->currentElement = array();
115 if ($name == 'USERS') {
116 foreach ($this->users as $user_item) {
117 if (('' != $user_item['STATUS']) && ttUserHelper::getUserByLogin($user_item['LOGIN'])) {
118 // We have a login collision, cannot import any data.
119 $this->canImport = false;
124 // Now we can create a group.
125 if ($this->canImport) {
126 $this->top_role_id = ttRoleHelper::getRoleByRank(512, 0);
127 $group_id = $this->createGroup(array(
128 'name' => $this->groupData['NAME'],
129 'currency' => $this->groupData['CURRENCY'],
130 'decimal_mark' => $this->groupData['DECIMAL_MARK'],
131 'lang' => $this->groupData['LANG'],
132 'date_format' => $this->groupData['DATE_FORMAT'],
133 'time_format' => $this->groupData['TIME_FORMAT'],
134 'week_start' => $this->groupData['WEEK_START'],
135 'tracking_mode' => $this->groupData['TRACKING_MODE'],
136 'project_required' => $this->groupData['PROJECT_REQUIRED'],
137 'task_required' => $this->groupData['TASK_REQUIRED'],
138 'record_type' => $this->groupData['RECORD_TYPE'],
139 'bcc_email' => $this->groupData['BCC_EMAIL'],
140 'allow_ip' => $this->groupData['ALLOW_IP'],
141 'password_complexity' => $this->groupData['PASSWORD_COMPLEXITY'],
142 'plugins' => $this->groupData['PLUGINS'],
143 'lock_spec' => $this->groupData['LOCK_SPEC'],
144 'workday_minutes' => $this->groupData['WORKDAY_MINUTES'],
145 'config' => $this->groupData['CONFIG']));
147 $this->group_id = $group_id;
150 foreach ($this->roles as $key=>$role_item) {
151 $role_id = ttRoleHelper::insert(array(
152 'group_id' => $this->group_id,
153 'name' => $role_item['NAME'],
154 'rank' => $role_item['RANK'],
155 'rights' => $role_item['RIGHTS'],
156 'status' => $role_item['STATUS']));
157 $this->roleMap[$role_item['ID']] = $role_id;
160 foreach ($this->users as $key=>$user_item) {
161 $role_id = $user_item['ROLE_ID'] === '0' ? $this->top_role_id : $this->roleMap[$user_item['ROLE_ID']]; // 0 (not null) means top manager role.
162 $user_id = ttUserHelper::insert(array(
163 'group_id' => $this->group_id,
164 'role_id' => $role_id,
165 'client_id' => $user_item['CLIENT_ID'], // Note: NOT mapped value, replaced in CLIENT handler.
166 'name' => $user_item['NAME'],
167 'login' => $user_item['LOGIN'],
168 'password' => $user_item['PASSWORD'],
169 'rate' => $user_item['RATE'],
170 'email' => $user_item['EMAIL'],
171 'status' => $user_item['STATUS']), false);
172 $this->userMap[$key] = $user_id;
178 if ($name == 'TASK' && $this->canImport) {
179 $this->taskMap[$this->currentElement['ID']] =
180 ttTaskHelper::insert(array(
181 'group_id' => $this->group_id,
182 'name' => $this->currentElement['NAME'],
183 'description' => $this->currentElement['DESCRIPTION'],
184 'status' => $this->currentElement['STATUS']));
186 if ($name == 'PROJECT' && $this->canImport) {
187 // Prepare a list of task ids.
188 $tasks = explode(',', $this->currentElement['TASKS']);
189 foreach ($tasks as $id)
190 $mapped_tasks[] = $this->taskMap[$id];
192 // Add a new project.
193 $this->projectMap[$this->currentElement['ID']] =
194 ttProjectHelper::insert(array(
195 'group_id' => $this->group_id,
196 'name' => $this->currentElement['NAME'],
197 'description' => $this->currentElement['DESCRIPTION'],
198 'tasks' => $mapped_tasks,
199 'status' => $this->currentElement['STATUS']));
201 if ($name == 'USER_PROJECT_BIND' && $this->canImport) {
202 ttUserHelper::insertBind(
203 $this->userMap[$this->currentElement['USER_ID']],
204 $this->projectMap[$this->currentElement['PROJECT_ID']],
205 $this->currentElement['RATE'],
206 $this->currentElement['STATUS']);
209 if ($name == 'CLIENT' && $this->canImport) {
210 // Prepare a list of project ids.
211 if ($this->currentElement['PROJECTS']) {
212 $projects = explode(',', $this->currentElement['PROJECTS']);
213 foreach ($projects as $id)
214 $mapped_projects[] = $this->projectMap[$id];
217 $this->clientMap[$this->currentElement['ID']] =
218 ttClientHelper::insert(array(
219 'group_id' => $this->group_id,
220 'name' => $this->currentElement['NAME'],
221 'address' => $this->currentElement['ADDRESS'],
222 'tax' => $this->currentElement['TAX'],
223 'projects' => $mapped_projects,
224 'status' => $this->currentElement['STATUS']));
226 // Update client_id for tt_users to a mapped value.
227 // We did not do it during user insertion because clientMap was not ready then.
228 if ($this->currentElement['ID'] != $this->clientMap[$this->currentElement['ID']])
229 ttClientHelper::setMappedClient($this->group_id, $this->currentElement['ID'], $this->clientMap[$this->currentElement['ID']]);
232 if ($name == 'INVOICE' && $this->canImport) {
233 $this->invoiceMap[$this->currentElement['ID']] =
234 ttInvoiceHelper::insert(array(
235 'group_id' => $this->group_id,
236 'name' => $this->currentElement['NAME'],
237 'date' => $this->currentElement['DATE'],
238 'client_id' => $this->clientMap[$this->currentElement['CLIENT_ID']],
239 'discount' => $this->currentElement['DISCOUNT'],
240 'status' => $this->currentElement['STATUS']));
243 if ($name == 'MONTHLY_QUOTA' && $this->canImport) {
244 $this->insertMonthlyQuota($this->group_id, $this->currentElement['YEAR'], $this->currentElement['MONTH'], $this->currentElement['MINUTES']);
247 if ($name == 'LOG_ITEM' && $this->canImport) {
248 $this->logMap[$this->currentElement['ID']] =
249 ttTimeHelper::insert(array(
250 'user_id' => $this->userMap[$this->currentElement['USER_ID']],
251 'date' => $this->currentElement['DATE'],
252 'start' => $this->currentElement['START'],
253 'finish' => $this->currentElement['FINISH'],
254 'duration' => $this->currentElement['DURATION'],
255 'client' => $this->clientMap[$this->currentElement['CLIENT_ID']],
256 'project' => $this->projectMap[$this->currentElement['PROJECT_ID']],
257 'task' => $this->taskMap[$this->currentElement['TASK_ID']],
258 'invoice' => $this->invoiceMap[$this->currentElement['INVOICE_ID']],
259 'note' => (isset($this->currentElement['COMMENT']) ? $this->currentElement['COMMENT'] : ''),
260 'billable' => $this->currentElement['BILLABLE'],
261 'paid' => $this->currentElement['PAID'],
262 'status' => $this->currentElement['STATUS']));
265 if ($name == 'CUSTOM_FIELD' && $this->canImport) {
266 $this->customFieldMap[$this->currentElement['ID']] =
267 ttCustomFieldHelper::insertField(array(
268 'group_id' => $this->group_id,
269 'type' => $this->currentElement['TYPE'],
270 'label' => $this->currentElement['LABEL'],
271 'required' => $this->currentElement['REQUIRED'],
272 'status' => $this->currentElement['STATUS']));
275 if ($name == 'CUSTOM_FIELD_OPTION' && $this->canImport) {
276 $this->customFieldOptionMap[$this->currentElement['ID']] =
277 ttCustomFieldHelper::insertOption(array(
278 'field_id' => $this->customFieldMap[$this->currentElement['FIELD_ID']],
279 'value' => $this->currentElement['VALUE']));
282 if ($name == 'CUSTOM_FIELD_LOG_ENTRY' && $this->canImport) {
283 ttCustomFieldHelper::insertLogEntry(array(
284 'log_id' => $this->logMap[$this->currentElement['LOG_ID']],
285 'field_id' => $this->customFieldMap[$this->currentElement['FIELD_ID']],
286 'option_id' => $this->customFieldOptionMap[$this->currentElement['OPTION_ID']],
287 'value' => $this->currentElement['VALUE'],
288 'status' => $this->currentElement['STATUS']));
291 if ($name == 'EXPENSE_ITEM' && $this->canImport) {
292 ttExpenseHelper::insert(array(
293 'date' => $this->currentElement['DATE'],
294 'user_id' => $this->userMap[$this->currentElement['USER_ID']],
295 'client_id' => $this->clientMap[$this->currentElement['CLIENT_ID']],
296 'project_id' => $this->projectMap[$this->currentElement['PROJECT_ID']],
297 'name' => $this->currentElement['NAME'],
298 'cost' => $this->currentElement['COST'],
299 'invoice_id' => $this->invoiceMap[$this->currentElement['INVOICE_ID']],
300 'paid' => $this->currentElement['PAID'],
301 'status' => $this->currentElement['STATUS']));
304 if ($name == 'FAV_REPORT' && $this->canImport) {
306 if (strlen($this->currentElement['USERS']) > 0) {
307 $arr = explode(',', $this->currentElement['USERS']);
309 $user_list .= (strlen($user_list) == 0 ? '' : ',').$this->userMap[$v];
311 ttFavReportHelper::insertReport(array(
312 'name' => $this->currentElement['NAME'],
313 'user_id' => $this->userMap[$this->currentElement['USER_ID']],
314 'client' => $this->clientMap[$this->currentElement['CLIENT_ID']],
315 'option' => $this->customFieldOptionMap[$this->currentElement['CF_1_OPTION_ID']],
316 'project' => $this->projectMap[$this->currentElement['PROJECT_ID']],
317 'task' => $this->taskMap[$this->currentElement['TASK_ID']],
318 'billable' => $this->currentElement['BILLABLE'],
319 'users' => $user_list,
320 'period' => $this->currentElement['PERIOD'],
321 'from' => $this->currentElement['PERIOD_START'],
322 'to' => $this->currentElement['PERIOD_END'],
323 'chclient' => (int) $this->currentElement['SHOW_CLIENT'],
324 'chinvoice' => (int) $this->currentElement['SHOW_INVOICE'],
325 'chpaid' => (int) $this->currentElement['SHOW_PAID'],
326 'chip' => (int) $this->currentElement['SHOW_IP'],
327 'chproject' => (int) $this->currentElement['SHOW_PROJECT'],
328 'chstart' => (int) $this->currentElement['SHOW_START'],
329 'chduration' => (int) $this->currentElement['SHOW_DURATION'],
330 'chcost' => (int) $this->currentElement['SHOW_COST'],
331 'chtask' => (int) $this->currentElement['SHOW_TASK'],
332 'chfinish' => (int) $this->currentElement['SHOW_END'],
333 'chnote' => (int) $this->currentElement['SHOW_NOTE'],
334 'chcf_1' => (int) $this->currentElement['SHOW_CUSTOM_FIELD_1'],
335 'group_by' => $this->currentElement['GROUP_BY'],
336 'chtotalsonly' => (int) $this->currentElement['SHOW_TOTALS_ONLY']));
338 $this->currentTag = '';
341 // dataElement - callback handler for text data fragments. It builds up currentElement array with text pieces from XML.
342 function dataElement($parser, $data) {
343 if ($this->currentTag == 'NAME'
344 || $this->currentTag == 'DESCRIPTION'
345 || $this->currentTag == 'LABEL'
346 || $this->currentTag == 'VALUE'
347 || $this->currentTag == 'COMMENT'
348 || $this->currentTag == 'ADDRESS'
349 || $this->currentTag == 'ALLOW_IP'
350 || $this->currentTag == 'PASSWORD_COMPLEXITY') {
351 if (isset($this->currentElement[$this->currentTag]))
352 $this->currentElement[$this->currentTag] .= trim($data);
354 $this->currentElement[$this->currentTag] = trim($data);
358 // importXml - uncompresses the file, reads and parses its content. During parsing,
359 // startElement, endElement, and dataElement functions are called as many times as necessary.
360 // Actual import occurs in the endElement handler.
361 function importXml() {
364 // Do we have a compressed file?
366 $file_ext = substr($_FILES['xmlfile']['name'], strrpos($_FILES['xmlfile']['name'], '.') + 1);
367 if (in_array($file_ext, array('bz','tbz','bz2','tbz2'))) {
371 // Create a temporary file.
372 $dirName = dirname(TEMPLATE_DIR . '_c/.');
373 $filename = tempnam($dirName, 'import_');
375 // If the file is compressed - uncompress it.
377 if (!$this->uncompress($_FILES['xmlfile']['tmp_name'], $filename)) {
378 $this->errors->add($i18n->get('error.sys'));
381 unlink($_FILES['xmlfile']['tmp_name']);
383 if (!move_uploaded_file($_FILES['xmlfile']['tmp_name'], $filename)) {
384 $this->errors->add($i18n->get('error.upload'));
389 // Initialize XML parser.
390 $parser = xml_parser_create();
391 xml_set_object($parser, $this);
392 xml_set_element_handler($parser, 'startElement', 'endElement');
393 xml_set_character_data_handler($parser, 'dataElement');
395 // Read and parse the content of the file. During parsing, startElement, endElement, and dataElement functions are called.
396 $file = fopen($filename, 'r');
397 while ($data = fread($file, 4096)) {
398 if (!xml_parse($parser, $data, feof($file))) {
399 $this->errors->add(sprintf("XML error: %s at line %d",
400 xml_error_string(xml_get_error_code($parser)),
401 xml_get_current_line_number($parser)));
403 if (!$this->canImport) {
404 $this->errors->add($i18n->get('error.user_exists'));
408 xml_parser_free($parser);
409 if ($file) fclose($file);
413 // uncompress - uncompresses the content of the $in file into the $out file.
414 function uncompress($in, $out) {
415 // Do we have the uncompress function?
416 if (!function_exists('bzopen'))
419 // Initial checks of file names and permissions.
420 if (!file_exists($in) || !is_readable ($in))
422 if ((!file_exists($out) && !is_writable(dirname($out))) || (file_exists($out) && !is_writable($out)))
425 if (!$out_file = fopen($out, 'wb'))
427 if (!$in_file = bzopen ($in, 'r'))
430 while (!feof($in_file)) {
431 $buffer = bzread($in_file, 4096);
432 fwrite($out_file, $buffer, 4096);
439 // createGroup function creates a new group.
440 private function createGroup($fields) {
443 $mdb2 = getConnection();
445 $columns = '(name, currency, decimal_mark, lang, date_format, time_format, week_start, tracking_mode'.
446 ', project_required, task_required, record_type, bcc_email, allow_ip, password_complexity, plugins'.
447 ', lock_spec, workday_minutes, config, created, created_ip, created_by)';
449 $values = ' values ('.$mdb2->quote(trim($fields['name']));
450 $values .= ', '.$mdb2->quote(trim($fields['currency']));
451 $values .= ', '.$mdb2->quote($fields['decimal_mark']);
452 $values .= ', '.$mdb2->quote($fields['lang']);
453 $values .= ', '.$mdb2->quote($fields['date_format']);
454 $values .= ', '.$mdb2->quote($fields['time_format']);
455 $values .= ', '.(int)$fields['week_start'];
456 $values .= ', '.(int)$fields['tracking_mode'];
457 $values .= ', '.(int)$fields['project_required'];
458 $values .= ', '.(int)$fields['task_required'];
459 $values .= ', '.(int)$fields['record_type'];
460 $values .= ', '.$mdb2->quote($fields['bcc_email']);
461 $values .= ', '.$mdb2->quote($fields['allow_ip']);
462 $values .= ', '.$mdb2->quote($fields['password_complexity']);
463 $values .= ', '.$mdb2->quote($fields['plugins']);
464 $values .= ', '.$mdb2->quote($fields['lock_spec']);
465 $values .= ', '.(int)$fields['workday_minutes'];
466 $values .= ', '.$mdb2->quote($fields['config']);
467 $values .= ', now(), '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', '.$mdb2->quote($user->id);
470 $sql = 'insert into tt_groups '.$columns.$values;
471 $affected = $mdb2->exec($sql);
472 if (!is_a($affected, 'PEAR_Error')) {
473 $group_id = $mdb2->lastInsertID('tt_groups', 'id');
479 // insertMonthlyQuota - a helper function to insert a monthly quota.
480 private function insertMonthlyQuota($group_id, $year, $month, $minutes) {
481 $mdb2 = getConnection();
482 $sql = "INSERT INTO tt_monthly_quotas (group_id, year, month, minutes) values ($group_id, $year, $month, $minutes)";
483 $affected = $mdb2->exec($sql);
484 return (!is_a($affected, 'PEAR_Error'));