Populating org_id in tt_custom_fields table.
[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('ttCustomFieldHelper');
36 import('ttExpenseHelper');
37 import('ttFavReportHelper');
38
39 // ttOrgImportHelper class is used to import organization data from an XML file
40 // prepared by ttOrgExportHelper and consisting of nested groups with their info.
41 class ttOrgImportHelper {
42   var $errors               = null; // Errors go here. Set in constructor by reference.
43   var $schema_version       = null; // Database schema version from XML file we import from.
44   var $conflicting_logins   = null; // A comma-separated list of logins we cannot import.
45   var $canImport      = true;    // False if we cannot import data due to a conflict such as login collision.
46   var $firstPass      = true;    // True during first pass through the file.
47   var $org_id         = null;    // Organization id (same as top group_id).
48   var $current_group_id        = null; // Current group id during parsing.
49   var $current_parent_group_id = null; // Current parent group id during parsing.
50   var $top_role_id    = 0;       // Top role id.
51
52   // Entity maps for current group. They map XML ids with database ids.
53   var $currentGroupRoleMap    = array();
54   var $currentGroupTaskMap    = array();
55   var $currentGroupProjectMap = array();
56   var $currentGroupClientMap  = array();
57   var $currentGroupUserMap    = array();
58   var $currentGroupInvoiceMap = array();
59   var $currentGroupLogMap     = array();
60   var $currentGroupCustomFieldMap = array();
61   var $currentGroupCustomFieldOptionMap = array();
62   var $currentGroupFavReportMap = array();
63
64   // Constructor.
65   function __construct(&$errors) {
66     $this->errors = &$errors;
67     $this->top_role_id = ttRoleHelper::getRoleByRank(512, 0);
68   }
69
70   // startElement - callback handler for opening tags in XML.
71   function startElement($parser, $name, $attrs) {
72     global $i18n;
73
74     // First pass through the file determines if we can import data.
75     // We require 2 things:
76     //   1) Database schema version must be set. This ensures we have a compatible file.
77     //   2) No login coillisions are allowed.
78     if ($this->firstPass) {
79       if ($name == 'ORG' && $this->canImport) {
80          if ($attrs['SCHEMA'] == null) {
81            // We need (database) schema attribute to be available for import to work.
82            // Old Time Tracker export files don't have this.
83            // Current import code does not work with old format because we had to
84            // restructure data in export files for subgroup support.
85            $this->canImport = false;
86            $this->errors->add($i18n->get('error.format'));
87            return;
88          }
89       }
90
91       // In first pass we check user logins for potential collisions with existing.
92       if ($name == 'USER' && $this->canImport) {
93         $login = $attrs['LOGIN'];
94         if ('' != $attrs['STATUS'] && ttUserHelper::getUserByLogin($login)) {
95           // We have a login collision. Append colliding login to a list of things we cannot import.
96           $this->conflicting_logins .= ($this->conflicting_logins ? ", $login" : $login);
97           // The above is printed in error message with all found colliding logins.
98         }
99       }
100     }
101
102     // Second pass processing. We import data here, one tag at a time.
103     if (!$this->firstPass && $this->canImport && $this->errors->no()) {
104       $mdb2 = getConnection();
105
106       // We are in second pass and can import data.
107       if ($name == 'GROUP') {
108         // Create a new group.
109         $this->current_group_id = $this->createGroup(array(
110           'parent_id' => $this->current_parent_group_id,
111           'org_id' => $this->org_id,
112           'name' => $attrs['NAME'],
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 = ttCustomFieldHelper::insertOption(array(
392           // 'group_id' => $this->current_group_id, TODO: add this when group_id field is added to the table.
393           // 'org_id' => $this->org_id, TODO: add this when org_id field is added to the table.
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 (!ttCustomFieldHelper::insertLogEntry(array(
406           // 'group_id' => $this->current_group_id, TODO: add this when group_id field is added to the table.
407           // 'org_id' => $this->org_id, TODO: add this when org_id field is added to the table.
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, 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['currency']));
669     $values .= ', '.$mdb2->quote($fields['decimal_mark']);
670     $values .= ', '.$mdb2->quote($fields['lang']);
671     $values .= ', '.$mdb2->quote($fields['date_format']);
672     $values .= ', '.$mdb2->quote($fields['time_format']);
673     $values .= ', '.(int)$fields['week_start'];
674     $values .= ', '.(int)$fields['tracking_mode'];
675     $values .= ', '.(int)$fields['project_required'];
676     $values .= ', '.(int)$fields['task_required'];
677     $values .= ', '.(int)$fields['record_type'];
678     $values .= ', '.$mdb2->quote($fields['bcc_email']);
679     $values .= ', '.$mdb2->quote($fields['allow_ip']);
680     $values .= ', '.$mdb2->quote($fields['password_complexity']);
681     $values .= ', '.$mdb2->quote($fields['plugins']);
682     $values .= ', '.$mdb2->quote($fields['lock_spec']);
683     $values .= ', '.(int)$fields['workday_minutes'];
684     $values .= ', '.$mdb2->quote($fields['config']);
685     $values .= ', now(), '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', '.$mdb2->quote($user->id);
686     $values .= ')';
687
688     $sql = 'insert into tt_groups '.$columns.$values;
689     $affected = $mdb2->exec($sql);
690     if (is_a($affected, 'PEAR_Error')) {
691       $this->errors->add($i18n->get('error.db'));
692       return false;
693     }
694
695     $group_id = $mdb2->lastInsertID('tt_groups', 'id');
696     return $group_id;
697   }
698
699   // insertMonthlyQuota - a helper function to insert a monthly quota.
700   private function insertMonthlyQuota($fields) {
701     $mdb2 = getConnection();
702     $group_id = (int) $fields['group_id'];
703     $org_id = (int) $fields['org_id'];
704     $year = (int) $fields['year'];
705     $month = (int) $fields['month'];
706     $minutes = (int) $fields['minutes'];
707
708     $sql = "INSERT INTO tt_monthly_quotas (group_id, org_id, year, month, minutes)".
709       " values ($group_id, $org_id, $year, $month, $minutes)";
710     $affected = $mdb2->exec($sql);
711     return (!is_a($affected, 'PEAR_Error'));
712   }
713
714   // insertPredefinedExpense - a helper function to insert a predefined expense.
715   private function insertPredefinedExpense($fields) {
716     $mdb2 = getConnection();
717     $group_id = (int) $fields['group_id'];
718     $org_id = (int) $fields['org_id'];
719     $name = $mdb2->quote($fields['name']);
720     $cost = $mdb2->quote($fields['cost']);
721
722     $sql = "INSERT INTO tt_predefined_expenses (group_id, org_id, name, cost)".
723       " values ($group_id, $org_id, $name, $cost)";
724     $affected = $mdb2->exec($sql);
725     return (!is_a($affected, 'PEAR_Error'));
726   }
727
728   // insertExpense - a helper function to insert an expense item.
729   private function insertExpense($fields) {
730     global $user;
731     $mdb2 = getConnection();
732
733     $group_id = (int) $fields['group_id'];
734     $org_id = (int) $fields['org_id'];
735     $date = $fields['date'];
736     $user_id = (int) $fields['user_id'];
737     $client_id = $fields['client_id'];
738     $project_id = $fields['project_id'];
739     $name = $fields['name'];
740     $cost = str_replace(',', '.', $fields['cost']);
741     $invoice_id = $fields['invoice_id'];
742     $status = $fields['status'];
743     $paid = (int) $fields['paid'];
744     $created = ', now(), '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', '.$mdb2->quote($user->id);
745
746     $sql = "insert into tt_expense_items".
747       " (date, user_id, group_id, org_id, client_id, project_id, name, cost, invoice_id, paid, created, created_ip, created_by, status)".
748       " values (".$mdb2->quote($date).", $user_id, $group_id, $org_id, ".$mdb2->quote($client_id).", ".$mdb2->quote($project_id).
749       ", ".$mdb2->quote($name).", ".$mdb2->quote($cost).", ".$mdb2->quote($invoice_id).", $paid $created, ".$mdb2->quote($status).")";
750     $affected = $mdb2->exec($sql);
751     return (!is_a($affected, 'PEAR_Error'));
752   }
753
754   // insertProject - a helper function to insert a project as well as project to task binds.
755   private function insertProject($fields)
756   {
757     $mdb2 = getConnection();
758
759     $group_id = (int) $fields['group_id'];
760     $org_id = (int) $fields['org_id'];
761
762     $name = $fields['name'];
763     $description = $fields['description'];
764     $tasks = $fields['tasks'];
765     $comma_separated = implode(',', $tasks); // This is a comma-separated list of associated task ids.
766     $status = $fields['status'];
767
768     $sql = "insert into tt_projects (group_id, org_id, name, description, tasks, status)
769       values ($group_id, $org_id, ".$mdb2->quote($name).", ".$mdb2->quote($description).", ".$mdb2->quote($comma_separated).", ".$mdb2->quote($status).")";
770     $affected = $mdb2->exec($sql);
771     if (is_a($affected, 'PEAR_Error'))
772       return false;
773
774     $last_id = 0;
775     $sql = "select last_insert_id() as last_insert_id";
776     $res = $mdb2->query($sql);
777     $val = $res->fetchRow();
778     $last_id = $val['last_insert_id'];
779
780     // Insert binds into tt_project_task_binds table.
781     if (is_array($tasks)) {
782       foreach ($tasks as $task_id) {
783         $sql = "insert into tt_project_task_binds (project_id, task_id, group_id, org_id)".
784           " values($last_id, $task_id, $group_id, $org_id)";
785         $affected = $mdb2->exec($sql);
786         if (is_a($affected, 'PEAR_Error'))
787           return false;
788       }
789     }
790
791     return $last_id;
792   }
793
794   // The insertClient function inserts a new client as well as client to project binds.
795   private function insertClient($fields)
796   {
797     $mdb2 = getConnection();
798
799     $group_id = (int) $fields['group_id'];
800     $org_id = (int) $fields['org_id'];
801     $name = $fields['name'];
802     $address = $fields['address'];
803     $tax = $fields['tax'];
804     $projects = $fields['projects'];
805     if ($projects)
806       $comma_separated = implode(',', $projects); // This is a comma-separated list of associated projects ids.
807     $status = $fields['status'];
808
809     $tax = str_replace(',', '.', $tax);
810     if ($tax == '') $tax = 0;
811
812     $sql = "insert into tt_clients (group_id, org_id, name, address, tax, projects, status)".
813       " values ($group_id, $org_id, ".$mdb2->quote($name).", ".$mdb2->quote($address).", $tax, ".$mdb2->quote($comma_separated).", ".$mdb2->quote($status).")";
814
815     $affected = $mdb2->exec($sql);
816     if (is_a($affected, 'PEAR_Error'))
817       return false;
818
819     $last_id = 0;
820     $sql = "select last_insert_id() as last_insert_id";
821     $res = $mdb2->query($sql);
822     $val = $res->fetchRow();
823     $last_id = $val['last_insert_id'];
824
825     if (count($projects) > 0)
826       foreach ($projects as $p_id) {
827         $sql = "insert into tt_client_project_binds (client_id, project_id, group_id, org_id) values($last_id, $p_id, $group_id, $org_id)";
828         $affected = $mdb2->exec($sql);
829         if (is_a($affected, 'PEAR_Error'))
830           return false;
831       }
832
833     return $last_id;
834   }
835
836   // insertFavReport - inserts a favorite report in database.
837   private function insertFavReport($fields) {
838     $mdb2 = getConnection();
839
840     $group_id = (int) $fields['group_id'];
841     $org_id = (int) $fields['org_id'];
842
843     $sql = "insert into tt_fav_reports".
844       " (name, user_id, group_id, org_id, client_id, cf_1_option_id, project_id, task_id,".
845       " billable, invoice, paid_status, users, period, period_start, period_end,".
846       " show_client, show_invoice, show_paid, show_ip,".
847       " show_project, show_start, show_duration, show_cost,".
848       " show_task, show_end, show_note, show_custom_field_1, show_work_units,".
849       " group_by1, group_by2, group_by3, show_totals_only)".
850       " values(".
851       $mdb2->quote($fields['name']).", ".$fields['user_id'].", $group_id, $org_id, ".
852       $mdb2->quote($fields['client']).", ".$mdb2->quote($fields['option']).", ".
853       $mdb2->quote($fields['project']).", ".$mdb2->quote($fields['task']).", ".
854       $mdb2->quote($fields['billable']).", ".$mdb2->quote($fields['invoice']).", ".
855       $mdb2->quote($fields['paid_status']).", ".
856       $mdb2->quote($fields['users']).", ".$mdb2->quote($fields['period']).", ".
857       $mdb2->quote($fields['from']).", ".$mdb2->quote($fields['to']).", ".
858       $fields['chclient'].", ".$fields['chinvoice'].", ".$fields['chpaid'].", ".$fields['chip'].", ".
859       $fields['chproject'].", ".$fields['chstart'].", ".$fields['chduration'].", ".$fields['chcost'].", ".
860       $fields['chtask'].", ".$fields['chfinish'].", ".$fields['chnote'].", ".$fields['chcf_1'].", ".$fields['chunits'].", ".
861       $mdb2->quote($fields['group_by1']).", ".$mdb2->quote($fields['group_by2']).", ".
862       $mdb2->quote($fields['group_by3']).", ".$fields['chtotalsonly'].")";
863     $affected = $mdb2->exec($sql);
864     if (is_a($affected, 'PEAR_Error'))
865       return false;
866
867     $sql = "select last_insert_id() as last_id";
868     $res = $mdb2->query($sql);
869     if (is_a($res, 'PEAR_Error'))
870       return false;
871
872     $val = $res->fetchRow();
873     return $val['last_id'];
874   }
875
876   // insertNotification function inserts a new notification into database.
877   private function insertNotification($fields)
878   {
879     $mdb2 = getConnection();
880
881     $group_id = (int) $fields['group_id'];
882     $org_id = (int) $fields['org_id'];
883     $cron_spec = $fields['cron_spec'];
884     $last = (int) $fields['last'];
885     $next = (int) $fields['next'];
886     $report_id = (int) $fields['report_id'];
887     $email = $fields['email'];
888     $cc = $fields['cc'];
889     $subject = $fields['subject'];
890     $report_condition = $fields['report_condition'];
891     $status = $fields['status'];
892
893     $sql = "insert into tt_cron".
894       " (group_id, org_id, cron_spec, last, next, report_id, email, cc, subject, report_condition, status)".
895       " 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).")";
896     $affected = $mdb2->exec($sql);
897     return (!is_a($affected, 'PEAR_Error'));
898   }
899
900   // insertUserParam - a helper function to insert a user parameter.
901   private function insertUserParam($fields) {
902     $mdb2 = getConnection();
903
904     $group_id = (int) $fields['group_id'];
905     $org_id = (int) $fields['org_id'];
906     $user_id = (int) $fields['user_id'];
907     $param_name = $fields['param_name'];
908     $param_value = $fields['param_value'];
909
910     $sql = "insert into tt_config".
911       " (user_id, group_id, org_id, param_name, param_value)".
912       " values ($user_id, $group_id, $org_id, ".$mdb2->quote($param_name).", ".$mdb2->quote($param_value).")";
913     $affected = $mdb2->exec($sql);
914     return (!is_a($affected, 'PEAR_Error'));
915   }
916
917   // insertCustomField - a helper function to insert a custom field.
918   private function insertCustomField($fields) {
919     $mdb2 = getConnection();
920
921     $group_id = (int) $fields['group_id'];
922     $org_id = (int) $fields['org_id'];
923     $type = (int) $fields['type'];
924     $label = $fields['label'];
925     $required = (int) $fields['required'];
926     $status = $fields['status'];
927
928     $sql = "insert into tt_custom_fields".
929       " (group_id, org_id, type, label, required, status)".
930       " values($group_id, $org_id, $type, ".$mdb2->quote($label).", $required, ".$mdb2->quote($status).")";
931     $affected = $mdb2->exec($sql);
932     if (is_a($affected, 'PEAR_Error'))
933       return false;
934
935     $last_id = 0;
936     $sql = "select last_insert_id() as last_insert_id";
937     $res = $mdb2->query($sql);
938     $val = $res->fetchRow();
939     $last_id = $val['last_insert_id'];
940     return $last_id;
941   }
942 }