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