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