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