Added a comment about vertical tab problem.
[timetracker.git] / WEB-INF / lib / ttOrgImportHelper.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 // ttOrgImportHelper class is used to import organization data from an XML file
30 // prepared by ttOrgExportHelper and consisting of nested groups with their info.
31 class ttOrgImportHelper {
32   var $errors               = null; // Errors go here. Set in constructor by reference.
33   var $schema_version       = null; // Database schema version from XML file we import from.
34   var $conflicting_logins   = null; // A comma-separated list of logins we cannot import.
35   var $canImport      = true;    // False if we cannot import data due to a conflict such as login collision.
36   var $firstPass      = true;    // True during first pass through the file.
37   var $org_id         = null;    // Organization id (same as top group_id).
38   var $current_group_id        = null; // Current group id during parsing.
39   var $parents        = array(); // A stack of parent group ids for current group all the way to the root including self.
40   var $top_role_id    = 0;       // Top role id.
41
42   // Entity maps for current group. They map XML ids with database ids.
43   var $currentGroupRoleMap    = array();
44   var $currentGroupTaskMap    = array();
45   var $currentGroupProjectMap = array();
46   var $currentGroupClientMap  = array();
47   var $currentGroupUserMap    = array();
48   var $currentGroupInvoiceMap = array();
49   var $currentGroupLogMap     = array();
50   var $currentGroupCustomFieldMap = array();
51   var $currentGroupCustomFieldOptionMap = array();
52   var $currentGroupFavReportMap = array();
53
54   // Constructor.
55   function __construct(&$errors) {
56     $this->errors = &$errors;
57     $this->top_role_id = $this->getTopRole();
58   }
59
60   // startElement - callback handler for opening tags in XML.
61   function startElement($parser, $name, $attrs) {
62     global $i18n;
63
64     // First pass through the file determines if we can import data.
65     // We require 2 things:
66     //   1) Database schema version must be set. This ensures we have a compatible file.
67     //   2) No login coillisions are allowed.
68     if ($this->firstPass) {
69       if ($name == 'ORG' && $this->canImport) {
70          if ($attrs['SCHEMA'] == null) {
71            // We need (database) schema attribute to be available for import to work.
72            // Old Time Tracker export files don't have this.
73            // Current import code does not work with old format because we had to
74            // restructure data in export files for subgroup support.
75            $this->canImport = false;
76            $this->errors->add($i18n->get('error.format'));
77            return;
78          }
79       }
80
81       // In first pass we check user logins for potential collisions with existing.
82       if ($name == 'USER' && $this->canImport) {
83         $login = $attrs['LOGIN'];
84         if ('' != $attrs['STATUS'] && $this->loginExists($login)) {
85           // We have a login collision. Append colliding login to a list of things we cannot import.
86           $this->conflicting_logins .= ($this->conflicting_logins ? ", $login" : $login);
87           // The above is printed in error message with all found colliding logins.
88         }
89       }
90     }
91
92     // Second pass processing. We import data here, one tag at a time.
93     if (!$this->firstPass && $this->canImport && $this->errors->no()) {
94       $mdb2 = getConnection();
95
96       // We are in second pass and can import data.
97       if ($name == 'GROUP') {
98         // Create a new group.
99         $this->current_group_id = $this->createGroup(array(
100           'parent_id' => $this->current_group_id, // Note: after insert current_group_id changes.
101           'org_id' => $this->org_id,
102           'name' => $attrs['NAME'],
103           'description' => $attrs['DESCRIPTION'],
104           'currency' => $attrs['CURRENCY'],
105           'decimal_mark' => $attrs['DECIMAL_MARK'],
106           'lang' => $attrs['LANG'],
107           'date_format' => $attrs['DATE_FORMAT'],
108           'time_format' => $attrs['TIME_FORMAT'],
109           'week_start' => $attrs['WEEK_START'],
110           'tracking_mode' => $attrs['TRACKING_MODE'],
111           'project_required' => $attrs['PROJECT_REQUIRED'],
112           'task_required' => $attrs['TASK_REQUIRED'],
113           'record_type' => $attrs['RECORD_TYPE'],
114           'bcc_email' => $attrs['BCC_EMAIL'],
115           'allow_ip' => $attrs['ALLOW_IP'],
116           'password_complexity' => $attrs['PASSWORD_COMPLEXITY'],
117           'plugins' => $attrs['PLUGINS'],
118           'lock_spec' => $attrs['LOCK_SPEC'],
119           'workday_minutes' => $attrs['WORKDAY_MINUTES'],
120           'custom_logo' => $attrs['CUSTOM_LOGO'],
121           'config' => $attrs['CONFIG']));
122
123         // Special handling for top group.
124         if (!$this->org_id && $this->current_group_id) {
125           $this->org_id = $this->current_group_id;
126           $sql = "update tt_groups set org_id = $this->current_group_id where org_id is NULL and id = $this->current_group_id";
127           $affected = $mdb2->exec($sql);
128         }
129         // Add self to parent stack.
130         array_push($this->parents, $this->current_group_id);
131
132         // Recycle all maps as we are starting to work on new group.
133         // Note that for this to work properly all nested groups must be last entries in xml for each group.
134         unset($this->currentGroupRoleMap); $this->currentGroupRoleMap = array();
135         unset($this->currentGroupTaskMap); $this->currentGroupTaskMap = array();
136         unset($this->currentGroupProjectMap); $this->currentGroupProjectMap = array();
137         unset($this->currentGroupClientMap); $this->currentGroupClientMap = array();
138         unset($this->currentGroupUserMap); $this->currentGroupUserMap = array();
139         unset($this->currentGroupInvoiceMap); $this->currentGroupInvoiceMap = array();
140         unset($this->currentGroupLogMap); $this->currentGroupLogMap = array();
141         unset($this->currentGroupCustomFieldMap); $this->currentGroupCustomFieldMap = array();
142         unset($this->currentGroupCustomFieldOptionMap); $this->currentGroupCustomFieldOptionMap = array();
143         unset($this->currentGroupFavReportMap); $this->currentGroupCustomFavReportMap = array();
144         return;
145       }
146
147       if ($name == 'ROLE') {
148         // We get here when processing <role> tags for the current group.
149         $role_id = $this->insertRole(array(
150           'group_id' => $this->current_group_id,
151           'org_id' => $this->org_id,
152           'name' => $attrs['NAME'],
153           'description' => $attrs['DESCRIPTION'],
154           'rank' => $attrs['RANK'],
155           'rights' => $attrs['RIGHTS'],
156           'status' => $attrs['STATUS']));
157         if ($role_id) {
158           // Add a mapping.
159           $this->currentGroupRoleMap[$attrs['ID']] = $role_id;
160         } else {
161           $this->errors->add($i18n->get('error.db'));
162         }
163         return;
164       }
165
166       if ($name == 'TASK') {
167         // We get here when processing <task> tags for the current group.
168         $task_id = $this->insertTask(array(
169           'group_id' => $this->current_group_id,
170           'org_id' => $this->org_id,
171           'name' => $attrs['NAME'],
172           'description' => $attrs['DESCRIPTION'],
173           'status' => $attrs['STATUS']));
174         if ($task_id) {
175           // Add a mapping.
176           $this->currentGroupTaskMap[$attrs['ID']] = $task_id;
177         } else {
178           $this->errors->add($i18n->get('error.db'));
179         }
180         return;
181       }
182
183       if ($name == 'PROJECT') {
184         // We get here when processing <project> tags for the current group.
185
186         // Prepare a list of task ids.
187         if ($attrs['TASKS']) {
188           $tasks = explode(',', $attrs['TASKS']);
189           foreach ($tasks as $id)
190             $mapped_tasks[] = $this->currentGroupTaskMap[$id];
191         }
192
193         $project_id = $this->insertProject(array(
194           'group_id' => $this->current_group_id,
195           'org_id' => $this->org_id,
196           'name' => $attrs['NAME'],
197           'description' => $attrs['DESCRIPTION'],
198           'tasks' => $mapped_tasks,
199           'status' => $attrs['STATUS']));
200         if ($project_id) {
201           // Add a mapping.
202           $this->currentGroupProjectMap[$attrs['ID']] = $project_id;
203         } else {
204           $this->errors->add($i18n->get('error.db'));
205         }
206         return;
207       }
208
209       if ($name == 'CLIENT') {
210         // We get here when processing <client> tags for the current group.
211
212         // Prepare a list of project ids.
213         if ($attrs['PROJECTS']) {
214           $projects = explode(',', $attrs['PROJECTS']);
215           foreach ($projects as $id)
216             $mapped_projects[] = $this->currentGroupProjectMap[$id];
217         }
218
219         $client_id = $this->insertClient(array(
220           'group_id' => $this->current_group_id,
221           'org_id' => $this->org_id,
222           'name' => $attrs['NAME'],
223           'address' => $attrs['ADDRESS'],
224           'tax' => $attrs['TAX'],
225           'projects' => $mapped_projects,
226           'status' => $attrs['STATUS']));
227         if ($client_id) {
228           // Add a mapping.
229           $this->currentGroupClientMap[$attrs['ID']] = $client_id;
230         } else {
231           $this->errors->add($i18n->get('error.db'));
232         }
233         return;
234       }
235
236       if ($name == 'USER') {
237         // We get here when processing <user> tags for the current group.
238
239         $role_id = $attrs['ROLE_ID'] === '0' ? $this->top_role_id :  $this->currentGroupRoleMap[$attrs['ROLE_ID']]; // 0 (not null) means top manager role.
240
241         $user_id = $this->insertUser(array(
242           'group_id' => $this->current_group_id,
243           'org_id' => $this->org_id,
244           'role_id' => $role_id,
245           'client_id' => $this->currentGroupClientMap[$attrs['CLIENT_ID']],
246           'name' => $attrs['NAME'],
247           'login' => $attrs['LOGIN'],
248           'password' => $attrs['PASSWORD'],
249           'rate' => $attrs['RATE'],
250           'email' => $attrs['EMAIL'],
251           'status' => $attrs['STATUS']), false);
252         if ($user_id) {
253           // Add a mapping.
254           $this->currentGroupUserMap[$attrs['ID']] = $user_id;
255         } else {
256           $this->errors->add($i18n->get('error.db'));
257         }
258         return;
259       }
260
261       if ($name == 'USER_PROJECT_BIND') {
262         if (!$this->insertUserProjectBind(array(
263           'user_id' => $this->currentGroupUserMap[$attrs['USER_ID']],
264           'project_id' => $this->currentGroupProjectMap[$attrs['PROJECT_ID']],
265           'group_id' => $this->current_group_id,
266           'org_id' => $this->org_id,
267           'rate' => $attrs['RATE'],
268           'status' => $attrs['STATUS']))) {
269           $this->errors->add($i18n->get('error.db'));
270         }
271         return;
272       }
273
274       if ($name == 'INVOICE') {
275         // We get here when processing <invoice> tags for the current group.
276         $invoice_id = $this->insertInvoice(array(
277           'group_id' => $this->current_group_id,
278           'org_id' => $this->org_id,
279           'name' => $attrs['NAME'],
280           'date' => $attrs['DATE'],
281           'client_id' => $this->currentGroupClientMap[$attrs['CLIENT_ID']],
282           'status' => $attrs['STATUS']));
283         if ($invoice_id) {
284           // Add a mapping.
285           $this->currentGroupInvoiceMap[$attrs['ID']] = $invoice_id;
286         } else {
287           $this->errors->add($i18n->get('error.db'));
288         }
289         return;
290       }
291
292       if ($name == 'LOG_ITEM') {
293         // We get here when processing <log_item> tags for the current group.
294         $log_item_id = $this->insertLogEntry(array(
295           'user_id' => $this->currentGroupUserMap[$attrs['USER_ID']],
296           'group_id' => $this->current_group_id,
297           'org_id' => $this->org_id,
298           'date' => $attrs['DATE'],
299           'start' => $attrs['START'],
300           'finish' => $attrs['FINISH'],
301           'duration' => $attrs['DURATION'],
302           'client_id' => $this->currentGroupClientMap[$attrs['CLIENT_ID']],
303           'project_id' => $this->currentGroupProjectMap[$attrs['PROJECT_ID']],
304           'task_id' => $this->currentGroupTaskMap[$attrs['TASK_ID']],
305           'invoice_id' => $this->currentGroupInvoiceMap[$attrs['INVOICE_ID']],
306           'comment' => (isset($attrs['COMMENT']) ? $attrs['COMMENT'] : ''),
307           'billable' => $attrs['BILLABLE'],
308           'paid' => $attrs['PAID'],
309           'status' => $attrs['STATUS']));
310         if ($log_item_id) {
311           // Add a mapping.
312           $this->currentGroupLogMap[$attrs['ID']] = $log_item_id;
313         } else $this->errors->add($i18n->get('error.db'));
314         return;
315       }
316
317       if ($name == 'CUSTOM_FIELD') {
318         // We get here when processing <custom_field> tags for the current group.
319         $custom_field_id = $this->insertCustomField(array(
320           'group_id' => $this->current_group_id,
321           'org_id' => $this->org_id,
322           'type' => $attrs['TYPE'],
323           'label' => $attrs['LABEL'],
324           'required' => $attrs['REQUIRED'],
325           'status' => $attrs['STATUS']));
326         if ($custom_field_id) {
327           // Add a mapping.
328           $this->currentGroupCustomFieldMap[$attrs['ID']] = $custom_field_id;
329         } else $this->errors->add($i18n->get('error.db'));
330         return;
331       }
332
333       if ($name == 'CUSTOM_FIELD_OPTION') {
334         // We get here when processing <custom_field_option> tags for the current group.
335         $custom_field_option_id = $this->insertCustomFieldOption(array(
336           'group_id' => $this->current_group_id,
337           'org_id' => $this->org_id,
338           'field_id' => $this->currentGroupCustomFieldMap[$attrs['FIELD_ID']],
339           'value' => $attrs['VALUE']));
340         if ($custom_field_option_id) {
341           // Add a mapping.
342           $this->currentGroupCustomFieldOptionMap[$attrs['ID']] = $custom_field_option_id;
343         } else $this->errors->add($i18n->get('error.db'));
344         return;
345       }
346
347       if ($name == 'CUSTOM_FIELD_LOG_ENTRY') {
348         // We get here when processing <custom_field_log_entry> tags for the current group.
349         if (!$this->insertCustomFieldLogEntry(array(
350           'group_id' => $this->current_group_id,
351           'org_id' => $this->org_id,
352           'log_id' => $this->currentGroupLogMap[$attrs['LOG_ID']],
353           'field_id' => $this->currentGroupCustomFieldMap[$attrs['FIELD_ID']],
354           'option_id' => $this->currentGroupCustomFieldOptionMap[$attrs['OPTION_ID']],
355           'value' => $attrs['VALUE'],
356           'status' => $attrs['STATUS']))) {
357           $this->errors->add($i18n->get('error.db'));
358         }
359         return;
360       }
361
362       if ($name == 'EXPENSE_ITEM') {
363         // We get here when processing <expense_item> tags for the current group.
364         $expense_item_id = $this->insertExpense(array(
365           'date' => $attrs['DATE'],
366           'user_id' => $this->currentGroupUserMap[$attrs['USER_ID']],
367           'group_id' => $this->current_group_id,
368           'org_id' => $this->org_id,
369           'client_id' => $this->currentGroupClientMap[$attrs['CLIENT_ID']],
370           'project_id' => $this->currentGroupProjectMap[$attrs['PROJECT_ID']],
371           'name' => $attrs['NAME'],
372           'cost' => $attrs['COST'],
373           'invoice_id' => $this->currentGroupInvoiceMap[$attrs['INVOICE_ID']],
374           'paid' => $attrs['PAID'],
375           'status' => $attrs['STATUS']));
376         if (!$expense_item_id) $this->errors->add($i18n->get('error.db'));
377         return;
378       }
379
380       if ($name == 'PREDEFINED_EXPENSE') {
381         if (!$this->insertPredefinedExpense(array(
382           'group_id' => $this->current_group_id,
383           'org_id' => $this->org_id,
384           'name' => $attrs['NAME'],
385           'cost' => $attrs['COST']))) {
386           $this->errors->add($i18n->get('error.db'));
387         }
388         return;
389       }
390
391       if ($name == 'MONTHLY_QUOTA') {
392         if (!$this->insertMonthlyQuota(array(
393           'group_id' => $this->current_group_id,
394           'org_id' => $this->org_id,
395           'year' => $attrs['YEAR'],
396           'month' => $attrs['MONTH'],
397           'minutes' => $attrs['MINUTES']))) {
398           $this->errors->add($i18n->get('error.db'));
399         }
400         return;
401       }
402
403       if ($name == 'FAV_REPORT') {
404         $user_list = '';
405         if (strlen($attrs['USERS']) > 0) {
406           $arr = explode(',', $attrs['USERS']);
407           foreach ($arr as $v)
408             $user_list .= (strlen($user_list) == 0 ? '' : ',').$this->currentGroupUserMap[$v];
409         }
410         $fav_report_id = $this->insertFavReport(array(
411           'name' => $attrs['NAME'],
412           'user_id' => $this->currentGroupUserMap[$attrs['USER_ID']],
413           'group_id' => $this->current_group_id,
414           'org_id' => $this->org_id,
415           'client' => $this->currentGroupClientMap[$attrs['CLIENT_ID']],
416           'option' => $this->currentGroupCustomFieldOptionMap[$attrs['CF_1_OPTION_ID']],
417           'project' => $this->currentGroupProjectMap[$attrs['PROJECT_ID']],
418           'task' => $this->currentGroupTaskMap[$attrs['TASK_ID']],
419           'billable' => $attrs['BILLABLE'],
420           'users' => $user_list,
421           'period' => $attrs['PERIOD'],
422           'from' => $attrs['PERIOD_START'],
423           'to' => $attrs['PERIOD_END'],
424           'chclient' => (int) $attrs['SHOW_CLIENT'],
425           'chinvoice' => (int) $attrs['SHOW_INVOICE'],
426           'chpaid' => (int) $attrs['SHOW_PAID'],
427           'chip' => (int) $attrs['SHOW_IP'],
428           'chproject' => (int) $attrs['SHOW_PROJECT'],
429           'chstart' => (int) $attrs['SHOW_START'],
430           'chduration' => (int) $attrs['SHOW_DURATION'],
431           'chcost' => (int) $attrs['SHOW_COST'],
432           'chtask' => (int) $attrs['SHOW_TASK'],
433           'chfinish' => (int) $attrs['SHOW_END'],
434           'chnote' => (int) $attrs['SHOW_NOTE'],
435           'chcf_1' => (int) $attrs['SHOW_CUSTOM_FIELD_1'],
436           'chunits' => (int) $attrs['SHOW_WORK_UNITS'],
437           'group_by1' => $attrs['GROUP_BY1'],
438           'group_by2' => $attrs['GROUP_BY2'],
439           'group_by3' => $attrs['GROUP_BY3'],
440           'chtotalsonly' => (int) $attrs['SHOW_TOTALS_ONLY']));
441         if ($fav_report_id) {
442           // Add a mapping.
443           $this->currentGroupFavReportMap[$attrs['ID']] = $fav_report_id;
444           } else $this->errors->add($i18n->get('error.db'));
445         return;
446       }
447
448       if ($name == 'NOTIFICATION') {
449         if (!$this->insertNotification(array(
450           'group_id' => $this->current_group_id,
451           'org_id' => $this->org_id,
452           'cron_spec' => $attrs['CRON_SPEC'],
453           'last' => $attrs['LAST'],
454           'next' => $attrs['NEXT'],
455           'report_id' => $this->currentGroupFavReportMap[$attrs['REPORT_ID']],
456           'email' => $attrs['EMAIL'],
457           'cc' => $attrs['CC'],
458           'subject' => $attrs['SUBJECT'],
459           'report_condition' => $attrs['REPORT_CONDITION'],
460           'status' => $attrs['STATUS']))) {
461           $this->errors->add($i18n->get('error.db'));
462         }
463         return;
464       }
465
466       if ($name == 'USER_PARAM') {
467         if (!$this->insertUserParam(array(
468           'group_id' => $this->current_group_id,
469           'org_id' => $this->org_id,
470           'user_id' => $this->currentGroupUserMap[$attrs['USER_ID']],
471           'param_name' => $attrs['PARAM_NAME'],
472           'param_value' => $attrs['PARAM_VALUE']))) {
473           $this->errors->add($i18n->get('error.db'));
474         }
475         return;
476       }
477     }
478   }
479
480   // endElement - callback handler for ending tags in XML.
481   // We use this only for process </group> element endings and
482   // set current_group_id to an immediate parent.
483   // This is required to import group hierarchy correctly.
484   function endElement($parser, $name) {
485     // No need to care about first or second pass, as this is used only in second pass.
486     // See 2nd xml_set_element_handler, where this handler is set.
487     if ($name == 'GROUP') {
488       // Remove self from the parent stack.
489       $self = array_pop($this->parents);
490       // Set current group id to an immediate parent.
491       $len = count($this->parents);
492       $this->current_group_id = $len ? $this->parents[$len-1] : null;
493     }
494   }
495
496   // importXml - uncompresses the file, reads and parses its content.
497   // It goes through the file 2 times.
498   //
499   // During 1st pass, it determines whether we can import data.
500   // In 1st pass, startElement function is called as many times as necessary.
501   //
502   // Actual import occurs during 2nd pass.
503   // In 2nd pass, startElement and endElement are called many times.
504   // We only use endElement to finish current group processing.
505   //
506   // The above allows us to export/import complex orgs with nested groups,
507   // while by design all data are in attributes of the elements (no CDATA).
508   //
509   // There is currently at least one problem with keeping all data in attributes:
510   // a vertical tab character 0xB anywhere breaks parsing, making import impossible.
511   // See https://github.com/sparklemotion/nokogiri/issues/1581 - looks like
512   // an XML standard thing. Apparently, other invalid characters break parsing too.
513   // This problem needs to be addressed at some point but how exactly without
514   // complicating export-import too much with CDATA and dataElement processing?
515   function importXml() {
516     global $i18n;
517
518     if (!$_FILES['xmlfile']['name']) {
519       $this->errors->add($i18n->get('error.upload'));
520       return; // There is nothing to do if we don't have a file.
521     }
522
523     // Do we have a compressed file?
524     $compressed = false;
525     $file_ext = substr($_FILES['xmlfile']['name'], strrpos($_FILES['xmlfile']['name'], '.') + 1);
526     if (in_array($file_ext, array('bz','tbz','bz2','tbz2'))) {
527       $compressed = true;
528     }
529
530     // Create a temporary file.
531     $dirName = dirname(TEMPLATE_DIR . '_c/.');
532     $filename = tempnam($dirName, 'import_');
533
534     // If the file is compressed - uncompress it.
535     if ($compressed) {
536       if (!$this->uncompress($_FILES['xmlfile']['tmp_name'], $filename)) {
537         $this->errors->add($i18n->get('error.sys'));
538         return;
539       }
540       unlink($_FILES['xmlfile']['tmp_name']);
541     } else {
542       if (!move_uploaded_file($_FILES['xmlfile']['tmp_name'], $filename)) {
543         $this->errors->add($i18n->get('error.upload'));
544         return;
545       }
546     }
547
548     // Initialize XML parser.
549     $parser = xml_parser_create();
550     xml_set_object($parser, $this);
551     xml_set_element_handler($parser, 'startElement', false); // No need to process end tags in 1st pass.
552
553     // We need to parse the file 2 times:
554     //   1) First pass: determine if import is possible.
555     //   2) Second pass: import data, one tag at a time.
556
557     // Read and parse the content of the file. During parsing, startElement is called back for each tag.
558     $file = fopen($filename, 'r');
559     while (($data = fread($file, 4096)) && $this->errors->no()) {
560       if (!xml_parse($parser, $data, feof($file))) {
561         $this->errors->add(sprintf($i18n->get('error.xml'),
562           xml_get_current_line_number($parser),
563           xml_error_string(xml_get_error_code($parser))));
564       }
565     }
566     if ($this->conflicting_logins) {
567       $this->canImport = false;
568       $this->errors->add($i18n->get('error.user_exists'));
569       $this->errors->add(sprintf($i18n->get('error.cannot_import'), $this->conflicting_logins));
570     }
571
572     $this->firstPass = false; // We are done with 1st pass.
573     xml_parser_free($parser);
574     if ($file) fclose($file);
575     if ($this->errors->yes()) {
576       // Remove the file and exit if we have errors.
577       unlink($filename);
578       return;
579     }
580
581     // Now we can do a second pass, where real work is done.
582     $parser = xml_parser_create();
583     xml_set_object($parser, $this);
584     xml_set_element_handler($parser, 'startElement', 'endElement'); // Need to process ending tags too.
585
586     // Read and parse the content of the file. During parsing, startElement and endElement are called back for each tag.
587     $file = fopen($filename, 'r');
588     while (($data = fread($file, 4096)) && $this->errors->no()) {
589       if (!xml_parse($parser, $data, feof($file))) {
590         $this->errors->add(sprintf($i18n->get('error.xml'),
591           xml_get_current_line_number($parser),
592           xml_error_string(xml_get_error_code($parser))));
593       }
594     }
595     xml_parser_free($parser);
596     if ($file) fclose($file);
597     unlink($filename);
598   }
599
600   // uncompress - uncompresses the content of the $in file into the $out file.
601   function uncompress($in, $out) {
602     // Do we have the uncompress function?
603     if (!function_exists('bzopen'))
604       return false;
605
606     // Initial checks of file names and permissions.
607     if (!file_exists($in) || !is_readable ($in))
608       return false;
609     if ((!file_exists($out) && !is_writable(dirname($out))) || (file_exists($out) && !is_writable($out)))
610       return false;
611
612     if (!$out_file = fopen($out, 'wb'))
613       return false;
614     if (!$in_file = bzopen ($in, 'r'))
615       return false;
616
617     while (!feof($in_file)) {
618       $buffer = bzread($in_file, 4096);
619       fwrite($out_file, $buffer, 4096);
620     }
621     bzclose($in_file);
622     fclose ($out_file);
623     return true;
624   }
625
626   // createGroup function creates a new group.
627   private function createGroup($fields) {
628     global $user;
629     global $i18n;
630     $mdb2 = getConnection();
631
632     $columns = '(parent_id, org_id, name, description, currency, decimal_mark, lang, date_format, time_format'.
633       ', week_start, tracking_mode, project_required, task_required, record_type, bcc_email'.
634       ', allow_ip, password_complexity, plugins, lock_spec'.
635       ', workday_minutes, config, created, created_ip, created_by)';
636
637     $values = ' values (';
638     $values .= $mdb2->quote($fields['parent_id']);
639     $values .= ', '.$mdb2->quote($fields['org_id']);
640     $values .= ', '.$mdb2->quote(trim($fields['name']));
641     $values .= ', '.$mdb2->quote(trim($fields['description']));
642     $values .= ', '.$mdb2->quote(trim($fields['currency']));
643     $values .= ', '.$mdb2->quote($fields['decimal_mark']);
644     $values .= ', '.$mdb2->quote($fields['lang']);
645     $values .= ', '.$mdb2->quote($fields['date_format']);
646     $values .= ', '.$mdb2->quote($fields['time_format']);
647     $values .= ', '.(int)$fields['week_start'];
648     $values .= ', '.(int)$fields['tracking_mode'];
649     $values .= ', '.(int)$fields['project_required'];
650     $values .= ', '.(int)$fields['task_required'];
651     $values .= ', '.(int)$fields['record_type'];
652     $values .= ', '.$mdb2->quote($fields['bcc_email']);
653     $values .= ', '.$mdb2->quote($fields['allow_ip']);
654     $values .= ', '.$mdb2->quote($fields['password_complexity']);
655     $values .= ', '.$mdb2->quote($fields['plugins']);
656     $values .= ', '.$mdb2->quote($fields['lock_spec']);
657     $values .= ', '.(int)$fields['workday_minutes'];
658     $values .= ', '.$mdb2->quote($fields['config']);
659     $values .= ', now(), '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', '.$user->id;
660     $values .= ')';
661
662     $sql = 'insert into tt_groups '.$columns.$values;
663     $affected = $mdb2->exec($sql);
664     if (is_a($affected, 'PEAR_Error')) {
665       $this->errors->add($i18n->get('error.db'));
666       return false;
667     }
668
669     $group_id = $mdb2->lastInsertID('tt_groups', 'id');
670     return $group_id;
671   }
672
673   // insertMonthlyQuota - a helper function to insert a monthly quota.
674   private function insertMonthlyQuota($fields) {
675     $mdb2 = getConnection();
676
677     $group_id = (int) $fields['group_id'];
678     $org_id = (int) $fields['org_id'];
679     $year = (int) $fields['year'];
680     $month = (int) $fields['month'];
681     $minutes = (int) $fields['minutes'];
682
683     $sql = "INSERT INTO tt_monthly_quotas (group_id, org_id, year, month, minutes)".
684       " values ($group_id, $org_id, $year, $month, $minutes)";
685     $affected = $mdb2->exec($sql);
686     return (!is_a($affected, 'PEAR_Error'));
687   }
688
689   // insertPredefinedExpense - a helper function to insert a predefined expense.
690   private function insertPredefinedExpense($fields) {
691     $mdb2 = getConnection();
692
693     $group_id = (int) $fields['group_id'];
694     $org_id = (int) $fields['org_id'];
695     $name = $mdb2->quote($fields['name']);
696     $cost = $mdb2->quote($fields['cost']);
697
698     $sql = "INSERT INTO tt_predefined_expenses (group_id, org_id, name, cost)".
699       " values ($group_id, $org_id, $name, $cost)";
700     $affected = $mdb2->exec($sql);
701     return (!is_a($affected, 'PEAR_Error'));
702   }
703
704   // insertExpense - a helper function to insert an expense item.
705   private function insertExpense($fields) {
706     global $user;
707     $mdb2 = getConnection();
708
709     $group_id = (int) $fields['group_id'];
710     $org_id = (int) $fields['org_id'];
711     $date = $fields['date'];
712     $user_id = (int) $fields['user_id'];
713     $client_id = $fields['client_id'];
714     $project_id = $fields['project_id'];
715     $name = $fields['name'];
716     $cost = str_replace(',', '.', $fields['cost']);
717     $invoice_id = $fields['invoice_id'];
718     $status = $fields['status'];
719     $paid = (int) $fields['paid'];
720     $created = ', now(), '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', '.$user->id;
721
722     $sql = "insert into tt_expense_items".
723       " (date, user_id, group_id, org_id, client_id, project_id, name, cost, invoice_id, paid, created, created_ip, created_by, status)".
724       " values (".$mdb2->quote($date).", $user_id, $group_id, $org_id, ".$mdb2->quote($client_id).", ".$mdb2->quote($project_id).
725       ", ".$mdb2->quote($name).", ".$mdb2->quote($cost).", ".$mdb2->quote($invoice_id).", $paid $created, ".$mdb2->quote($status).")";
726     $affected = $mdb2->exec($sql);
727     return (!is_a($affected, 'PEAR_Error'));
728   }
729
730   // insertTask function inserts a new task into database.
731   private function insertTask($fields)
732   {
733     $mdb2 = getConnection();
734
735     $group_id = (int) $fields['group_id'];
736     $org_id = (int) $fields['org_id'];
737     $name = $fields['name'];
738     $description = $fields['description'];
739     $projects = $fields['projects'];
740     $status = $fields['status'];
741
742     $sql = "insert into tt_tasks (group_id, org_id, name, description, status)
743       values ($group_id, $org_id, ".$mdb2->quote($name).", ".$mdb2->quote($description).", ".$mdb2->quote($status).")";
744     $affected = $mdb2->exec($sql);
745     $last_id = 0;
746     if (is_a($affected, 'PEAR_Error'))
747       return false;
748
749     $last_id = $mdb2->lastInsertID('tt_tasks', 'id');
750     return $last_id;
751   }
752
753   // insertUserProjectBind - inserts a user to project bind into tt_user_project_binds table.
754   private function insertUserProjectBind($fields) {
755     $mdb2 = getConnection();
756
757     $group_id = (int) $fields['group_id'];
758     $org_id = (int) $fields['org_id'];
759     $user_id = (int) $fields['user_id'];
760     $project_id = (int) $fields['project_id'];
761     $rate = $mdb2->quote($fields['rate']);
762     $status = $mdb2->quote($fields['status']);
763
764     $sql = "insert into tt_user_project_binds (user_id, project_id, group_id, org_id, rate, status)".
765       " values($user_id, $project_id, $group_id, $org_id, $rate, $status)";
766     $affected = $mdb2->exec($sql);
767     return (!is_a($affected, 'PEAR_Error'));
768   }
769
770   // insertUser - inserts a user into database.
771   private function insertUser($fields) {
772     global $user;
773     $mdb2 = getConnection();
774
775     $group_id = (int) $fields['group_id'];
776     $org_id = (int) $fields['org_id'];
777
778     $columns = '(login, password, name, group_id, org_id, role_id, client_id, rate, email, created, created_ip, created_by, status)';
779
780     $values = 'values (';
781     $values .= $mdb2->quote($fields['login']);
782     $values .= ', '.$mdb2->quote($fields['password']);
783     $values .= ', '.$mdb2->quote($fields['name']);
784     $values .= ', '.$group_id;
785     $values .= ', '.$org_id;
786     $values .= ', '.(int)$fields['role_id'];
787     $values .= ', '.$mdb2->quote($fields['client_id']);
788     $values .= ', '.$mdb2->quote($fields['rate']);
789     $values .= ', '.$mdb2->quote($fields['email']);
790     $values .= ', now(), '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', '.$user->id;
791     $values .= ', '.$mdb2->quote($fields['status']);
792     $values .= ')';
793
794     $sql = "insert into tt_users $columns $values";
795     $affected = $mdb2->exec($sql);
796     if (is_a($affected, 'PEAR_Error')) return false;
797
798     $last_id = $mdb2->lastInsertID('tt_users', 'id');
799     return $last_id;
800   }
801
802   // insertProject - a helper function to insert a project as well as project to task binds.
803   private function insertProject($fields)
804   {
805     $mdb2 = getConnection();
806
807     $group_id = (int) $fields['group_id'];
808     $org_id = (int) $fields['org_id'];
809     $name = $fields['name'];
810     $description = $fields['description'];
811     $tasks = $fields['tasks'];
812     $comma_separated = implode(',', $tasks); // This is a comma-separated list of associated task ids.
813     $status = $fields['status'];
814
815     $sql = "insert into tt_projects (group_id, org_id, name, description, tasks, status)
816       values ($group_id, $org_id, ".$mdb2->quote($name).", ".$mdb2->quote($description).", ".$mdb2->quote($comma_separated).", ".$mdb2->quote($status).")";
817     $affected = $mdb2->exec($sql);
818     if (is_a($affected, 'PEAR_Error'))
819       return false;
820
821     $last_id = $mdb2->lastInsertID('tt_projects', 'id');
822
823     // Insert binds into tt_project_task_binds table.
824     if (is_array($tasks)) {
825       foreach ($tasks as $task_id) {
826         $sql = "insert into tt_project_task_binds (project_id, task_id, group_id, org_id)".
827           " values($last_id, $task_id, $group_id, $org_id)";
828         $affected = $mdb2->exec($sql);
829         if (is_a($affected, 'PEAR_Error'))
830           return false;
831       }
832     }
833
834     return $last_id;
835   }
836
837   // insertRole - inserts a role into tt_roles table.
838   private function insertRole($fields)
839   {
840     $mdb2 = getConnection();
841
842     $group_id = (int) $fields['group_id'];
843     $org_id = (int) $fields['org_id'];
844     $name = $fields['name'];
845     $rank = (int) $fields['rank'];
846     $description = $fields['description'];
847     $rights = $fields['rights'];
848     $status = $fields['status'];
849
850     $sql = "insert into tt_roles (group_id, org_id, name, rank, description, rights, status)
851       values ($group_id, $org_id, ".$mdb2->quote($name).", $rank, ".$mdb2->quote($description).", ".$mdb2->quote($rights).", ".$mdb2->quote($status).")";
852     $affected = $mdb2->exec($sql);
853     if (is_a($affected, 'PEAR_Error'))
854       return false;
855
856     $last_id = $mdb2->lastInsertID('tt_roles', 'id');
857     return $last_id;
858   }
859
860   // insertInvoice - inserts an invoice in database.
861   private function insertInvoice($fields)
862   {
863     $mdb2 = getConnection();
864
865     $group_id = (int) $fields['group_id'];
866     $org_id = (int) $fields['org_id'];
867     $name = $fields['name'];
868     $client_id = (int) $fields['client_id'];
869     $date = $fields['date'];
870     $status = $fields['status'];
871
872     // Insert a new invoice record.
873     $sql = "insert into tt_invoices (group_id, org_id, name, date, client_id, status)".
874       " values($group_id, $org_id, ".$mdb2->quote($name).", ".$mdb2->quote($date).", $client_id, ".$mdb2->quote($fields['status']).")";
875     $affected = $mdb2->exec($sql);
876     if (is_a($affected, 'PEAR_Error')) return false;
877
878     $last_id = $mdb2->lastInsertID('tt_invoices', 'id');
879     return $last_id;
880   }
881
882   // The insertClient function inserts a new client as well as client to project binds.
883   private function insertClient($fields)
884   {
885     $mdb2 = getConnection();
886
887     $group_id = (int) $fields['group_id'];
888     $org_id = (int) $fields['org_id'];
889     $name = $fields['name'];
890     $address = $fields['address'];
891     $tax = $fields['tax'];
892     $projects = $fields['projects'];
893     if ($projects)
894       $comma_separated = implode(',', $projects); // This is a comma-separated list of associated projects ids.
895     $status = $fields['status'];
896
897     $tax = str_replace(',', '.', $tax);
898     if ($tax == '') $tax = 0;
899
900     $sql = "insert into tt_clients (group_id, org_id, name, address, tax, projects, status)".
901       " values ($group_id, $org_id, ".$mdb2->quote($name).", ".$mdb2->quote($address).", $tax, ".$mdb2->quote($comma_separated).", ".$mdb2->quote($status).")";
902
903     $affected = $mdb2->exec($sql);
904     if (is_a($affected, 'PEAR_Error'))
905       return false;
906
907     $last_id = $mdb2->lastInsertID('tt_clients', 'id');
908
909     if (count($projects) > 0)
910       foreach ($projects as $p_id) {
911         $sql = "insert into tt_client_project_binds (client_id, project_id, group_id, org_id) values($last_id, $p_id, $group_id, $org_id)";
912         $affected = $mdb2->exec($sql);
913         if (is_a($affected, 'PEAR_Error'))
914           return false;
915       }
916
917     return $last_id;
918   }
919
920   // insertFavReport - inserts a favorite report in database.
921   private function insertFavReport($fields) {
922     $mdb2 = getConnection();
923
924     $group_id = (int) $fields['group_id'];
925     $org_id = (int) $fields['org_id'];
926
927     $sql = "insert into tt_fav_reports".
928       " (name, user_id, group_id, org_id, client_id, cf_1_option_id, project_id, task_id,".
929       " billable, invoice, paid_status, users, period, period_start, period_end,".
930       " show_client, show_invoice, show_paid, show_ip,".
931       " show_project, show_start, show_duration, show_cost,".
932       " show_task, show_end, show_note, show_custom_field_1, show_work_units,".
933       " group_by1, group_by2, group_by3, show_totals_only)".
934       " values(".
935       $mdb2->quote($fields['name']).", ".$fields['user_id'].", $group_id, $org_id, ".
936       $mdb2->quote($fields['client']).", ".$mdb2->quote($fields['option']).", ".
937       $mdb2->quote($fields['project']).", ".$mdb2->quote($fields['task']).", ".
938       $mdb2->quote($fields['billable']).", ".$mdb2->quote($fields['invoice']).", ".
939       $mdb2->quote($fields['paid_status']).", ".
940       $mdb2->quote($fields['users']).", ".$mdb2->quote($fields['period']).", ".
941       $mdb2->quote($fields['from']).", ".$mdb2->quote($fields['to']).", ".
942       $fields['chclient'].", ".$fields['chinvoice'].", ".$fields['chpaid'].", ".$fields['chip'].", ".
943       $fields['chproject'].", ".$fields['chstart'].", ".$fields['chduration'].", ".$fields['chcost'].", ".
944       $fields['chtask'].", ".$fields['chfinish'].", ".$fields['chnote'].", ".$fields['chcf_1'].", ".$fields['chunits'].", ".
945       $mdb2->quote($fields['group_by1']).", ".$mdb2->quote($fields['group_by2']).", ".
946       $mdb2->quote($fields['group_by3']).", ".$fields['chtotalsonly'].")";
947     $affected = $mdb2->exec($sql);
948     if (is_a($affected, 'PEAR_Error'))
949       return false;
950
951     $last_id = $mdb2->lastInsertID('tt_fav_reports', 'id');
952     return $last_id;
953   }
954
955   // insertNotification function inserts a new notification into database.
956   private function insertNotification($fields)
957   {
958     $mdb2 = getConnection();
959
960     $group_id = (int) $fields['group_id'];
961     $org_id = (int) $fields['org_id'];
962     $cron_spec = $fields['cron_spec'];
963     $last = (int) $fields['last'];
964     $next = (int) $fields['next'];
965     $report_id = (int) $fields['report_id'];
966     $email = $fields['email'];
967     $cc = $fields['cc'];
968     $subject = $fields['subject'];
969     $report_condition = $fields['report_condition'];
970     $status = $fields['status'];
971
972     $sql = "insert into tt_cron".
973       " (group_id, org_id, cron_spec, last, next, report_id, email, cc, subject, report_condition, status)".
974       " values ($group_id, $org_id, ".$mdb2->quote($cron_spec).", $last, $next, $report_id, ".$mdb2->quote($email).", ".$mdb2->quote($cc).", ".$mdb2->quote($subject).", ".$mdb2->quote($report_condition).", ".$mdb2->quote($status).")";
975     $affected = $mdb2->exec($sql);
976     return (!is_a($affected, 'PEAR_Error'));
977   }
978
979   // insertUserParam - a helper function to insert a user parameter.
980   private function insertUserParam($fields) {
981     $mdb2 = getConnection();
982
983     $group_id = (int) $fields['group_id'];
984     $org_id = (int) $fields['org_id'];
985     $user_id = (int) $fields['user_id'];
986     $param_name = $fields['param_name'];
987     $param_value = $fields['param_value'];
988
989     $sql = "insert into tt_config".
990       " (user_id, group_id, org_id, param_name, param_value)".
991       " values ($user_id, $group_id, $org_id, ".$mdb2->quote($param_name).", ".$mdb2->quote($param_value).")";
992     $affected = $mdb2->exec($sql);
993     return (!is_a($affected, 'PEAR_Error'));
994   }
995
996   // insertCustomField - a helper function to insert a custom field.
997   private function insertCustomField($fields) {
998     $mdb2 = getConnection();
999
1000     $group_id = (int) $fields['group_id'];
1001     $org_id = (int) $fields['org_id'];
1002     $type = (int) $fields['type'];
1003     $label = $fields['label'];
1004     $required = (int) $fields['required'];
1005     $status = $fields['status'];
1006
1007     $sql = "insert into tt_custom_fields".
1008       " (group_id, org_id, type, label, required, status)".
1009       " values($group_id, $org_id, $type, ".$mdb2->quote($label).", $required, ".$mdb2->quote($status).")";
1010     $affected = $mdb2->exec($sql);
1011     if (is_a($affected, 'PEAR_Error'))
1012       return false;
1013
1014     $last_id = $mdb2->lastInsertID('tt_custom_fields', 'id');
1015     return $last_id;
1016   }
1017
1018   // insertCustomFieldOption - a helper function to insert a custom field option.
1019   private function insertCustomFieldOption($fields) {
1020     $mdb2 = getConnection();
1021
1022     $group_id = (int) $fields['group_id'];
1023     $org_id = (int) $fields['org_id'];
1024     $field_id = (int) $fields['field_id'];
1025     $value = $fields['value'];
1026
1027     $sql = "insert into tt_custom_field_options (group_id, org_id, field_id, value)".
1028       " values ($group_id, $org_id, $field_id, ".$mdb2->quote($value).")";
1029     $affected = $mdb2->exec($sql);
1030     if (is_a($affected, 'PEAR_Error'))
1031       return false;
1032
1033     $last_id = $mdb2->lastInsertID('tt_custom_field_options', 'id');
1034     return $last_id;
1035   }
1036
1037   // insertLogEntry - a helper function to insert a time log entry.
1038   private function insertLogEntry($fields) {
1039     global $user;
1040     $mdb2 = getConnection();
1041
1042     $group_id = (int) $fields['group_id'];
1043     $org_id = (int) $fields['org_id'];
1044     $user_id = (int) $fields['user_id'];
1045     $date = $fields['date'];
1046     $start = $fields['start'];
1047     $duration = $fields['duration'];
1048     $client_id = $fields['client_id'];
1049     $project_id = $fields['project_id'];
1050     $task_id = $fields['task_id'];
1051     $invoice_id = $fields['invoice_id'];
1052     $comment = $fields['comment'];
1053     $billable = (int) $fields['billable'];
1054     $paid = (int) $fields['paid'];
1055     $status = $fields['status'];
1056
1057     $sql = "insert into tt_log".
1058       " (user_id, group_id, org_id, date, start, duration, client_id, project_id, task_id, invoice_id, comment".
1059       ", billable, paid, created, created_ip, created_by, status)".
1060       " values ($user_id, $group_id, $org_id".
1061       ", ".$mdb2->quote($date).
1062       ", ".$mdb2->quote($start).
1063       ", ".$mdb2->quote($duration).
1064       ", ".$mdb2->quote($client_id).
1065       ", ".$mdb2->quote($project_id).
1066       ", ".$mdb2->quote($task_id).
1067       ", ".$mdb2->quote($invoice_id).
1068       ", ".$mdb2->quote($comment).
1069       ", $billable, $paid".
1070       ", now(), ".$mdb2->quote($_SERVER['REMOTE_ADDR']).", ".$user->id.
1071       ", ". $mdb2->quote($status).")";
1072     $affected = $mdb2->exec($sql);
1073     if (is_a($affected, 'PEAR_Error')) {
1074       $this->errors->add($i18n->get('error.db')); // TODO: review whether or not to add error here in all insert calls.
1075       return false;
1076     }
1077
1078     $log_id = $mdb2->lastInsertID('tt_log', 'id');
1079     return $log_id;
1080   }
1081
1082   // insertCustomFieldLogEntry - a helper function to insert a custom field log entry.
1083   private function insertCustomFieldLogEntry($fields) {
1084     $mdb2 = getConnection();
1085
1086     $group_id = (int) $fields['group_id'];
1087     $org_id = (int) $fields['org_id'];
1088     $log_id = (int) $fields['log_id'];
1089     $field_id = (int) $fields['field_id'];
1090     $option_id = $fields['option_id'];
1091     $value = $fields['value'];
1092     $status = $fields['status'];
1093
1094     $sql = "insert into tt_custom_field_log (group_id, org_id, log_id, field_id, option_id, value, status)".
1095       " values ($group_id, $org_id, $log_id, $field_id, ".$mdb2->quote($option_id).", ".$mdb2->quote($value).", ".$mdb2->quote($status).")";
1096     $affected = $mdb2->exec($sql);
1097     return (!is_a($affected, 'PEAR_Error'));
1098   }
1099
1100   // getTopRole returns top role id.
1101   private function getTopRole() {
1102     $mdb2 = getConnection();
1103
1104     $sql = "select id from tt_roles where group_id = 0 and rank = ".MAX_RANK." and status = 1";
1105     $res = $mdb2->query($sql);
1106
1107     if (!is_a($res, 'PEAR_Error')) {
1108       $val = $res->fetchRow();
1109       if ($val['id'])
1110         return $val['id'];
1111     }
1112     return false;
1113   }
1114
1115   // The loginExists function detrmines if a login already exists.
1116   private function loginExists($login) {
1117     $mdb2 = getConnection();
1118
1119     $sql = "select id from tt_users where login = ".$mdb2->quote($login)." and (status = 1 or status = 0)";
1120     $res = $mdb2->query($sql);
1121     if (!is_a($res, 'PEAR_Error')) {
1122       if ($val = $res->fetchRow()) {
1123         return true;
1124       }
1125     }
1126     return false;
1127   }
1128 }