Fixed import for subgroups.
[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 $parents        = array(); // A stack of parent group ids for current group all the way to the root including self.
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_group_id, // Note: after insert current_group_id changes.
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         // Add self to parent stack.
139         array_push($this->parents, $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   // endElement - callback handler for ending tags in XML.
545   // We use this only for process </group> element endings and
546   // set current_group_id to an immediate parent.
547   // This is required to import group hierarchy correctly.
548   function endElement($parser, $name) {
549     // No need to care about first or second pass, as this is used only in second pass.
550     // See 2nd xml_set_element_handler, where this handler is set.
551     if ($name == 'GROUP') {
552       // Remove self from the parent stack.
553       $self = array_pop($this->parents);
554       // Set current group id to an immediate parent.
555       $len = count($this->parents);
556       $this->current_group_id = $len ? $this->parents[$len-1] : null;
557     }
558   }
559
560   // importXml - uncompresses the file, reads and parses its content. During parsing,
561   // startElement, endElement, and dataElement functions are called as many times as necessary.
562   // Actual import occurs in the endElement handler.
563   function importXml() {
564     global $i18n;
565
566     // Do we have a compressed file?
567     $compressed = false;
568     $file_ext = substr($_FILES['xmlfile']['name'], strrpos($_FILES['xmlfile']['name'], '.') + 1);
569     if (in_array($file_ext, array('bz','tbz','bz2','tbz2'))) {
570       $compressed = true;
571     }
572
573     // Create a temporary file.
574     $dirName = dirname(TEMPLATE_DIR . '_c/.');
575     $filename = tempnam($dirName, 'import_');
576
577     // If the file is compressed - uncompress it.
578     if ($compressed) {
579       if (!$this->uncompress($_FILES['xmlfile']['tmp_name'], $filename)) {
580         $this->errors->add($i18n->get('error.sys'));
581         return;
582       }
583       unlink($_FILES['xmlfile']['tmp_name']);
584     } else {
585       if (!move_uploaded_file($_FILES['xmlfile']['tmp_name'], $filename)) {
586         $this->errors->add($i18n->get('error.upload'));
587         return;
588       }
589     }
590
591     // Initialize XML parser.
592     $parser = xml_parser_create();
593     xml_set_object($parser, $this);
594     xml_set_element_handler($parser, 'startElement', false); // No need to process end tags in 1st pass.
595
596     // We need to parse the file 2 times:
597     //   1) First pass: determine if import is possible.
598     //   2) Second pass: import data, one tag at a time.
599
600     // Read and parse the content of the file. During parsing, startElement is called back for each tag.
601     $file = fopen($filename, 'r');
602     while (($data = fread($file, 4096)) && $this->errors->no()) {
603       if (!xml_parse($parser, $data, feof($file))) {
604         $this->errors->add(sprintf($i18n->get('error.xml'),
605           xml_get_current_line_number($parser),
606           xml_error_string(xml_get_error_code($parser))));
607       }
608     }
609     if ($this->conflicting_logins) {
610       $this->canImport = false;
611       $this->errors->add($i18n->get('error.user_exists'));
612       $this->errors->add(sprintf($i18n->get('error.cannot_import'), $this->conflicting_logins));
613     }
614
615     $this->firstPass = false; // We are done with 1st pass.
616     xml_parser_free($parser);
617     if ($file) fclose($file);
618     if (!$this->canImport) {
619       unlink($filename);
620       return;
621     }
622     if ($this->errors->yes()) return; // Exit if we have errors.
623
624     // Now we can do a second pass, where real work is done.
625     $parser = xml_parser_create();
626     xml_set_object($parser, $this);
627     xml_set_element_handler($parser, 'startElement', 'endElement'); // Need to process ending tags too.
628
629     // Read and parse the content of the file. During parsing, startElement and endElement are called back for each tag.
630     $file = fopen($filename, 'r');
631     while (($data = fread($file, 4096)) && $this->errors->no()) {
632       if (!xml_parse($parser, $data, feof($file))) {
633         $this->errors->add(sprintf($i18n->get('error.xml'),
634           xml_get_current_line_number($parser),
635           xml_error_string(xml_get_error_code($parser))));
636       }
637     }
638     xml_parser_free($parser);
639     if ($file) fclose($file);
640     unlink($filename);
641   }
642
643   // uncompress - uncompresses the content of the $in file into the $out file.
644   function uncompress($in, $out) {
645     // Do we have the uncompress function?
646     if (!function_exists('bzopen'))
647       return false;
648
649     // Initial checks of file names and permissions.
650     if (!file_exists($in) || !is_readable ($in))
651       return false;
652     if ((!file_exists($out) && !is_writable(dirname($out))) || (file_exists($out) && !is_writable($out)))
653       return false;
654
655     if (!$out_file = fopen($out, 'wb'))
656       return false;
657     if (!$in_file = bzopen ($in, 'r'))
658       return false;
659
660     while (!feof($in_file)) {
661       $buffer = bzread($in_file, 4096);
662       fwrite($out_file, $buffer, 4096);
663     }
664     bzclose($in_file);
665     fclose ($out_file);
666     return true;
667   }
668
669   // createGroup function creates a new group.
670   private function createGroup($fields) {
671     global $user;
672     global $i18n;
673     $mdb2 = getConnection();
674
675     $columns = '(parent_id, org_id, name, description, currency, decimal_mark, lang, date_format, time_format'.
676       ', week_start, tracking_mode, project_required, task_required, record_type, bcc_email'.
677       ', allow_ip, password_complexity, plugins, lock_spec'.
678       ', workday_minutes, config, created, created_ip, created_by)';
679
680     $values = ' values (';
681     $values .= $mdb2->quote($fields['parent_id']);
682     $values .= ', '.$mdb2->quote($fields['org_id']);
683     $values .= ', '.$mdb2->quote(trim($fields['name']));
684     $values .= ', '.$mdb2->quote(trim($fields['description']));
685     $values .= ', '.$mdb2->quote(trim($fields['currency']));
686     $values .= ', '.$mdb2->quote($fields['decimal_mark']);
687     $values .= ', '.$mdb2->quote($fields['lang']);
688     $values .= ', '.$mdb2->quote($fields['date_format']);
689     $values .= ', '.$mdb2->quote($fields['time_format']);
690     $values .= ', '.(int)$fields['week_start'];
691     $values .= ', '.(int)$fields['tracking_mode'];
692     $values .= ', '.(int)$fields['project_required'];
693     $values .= ', '.(int)$fields['task_required'];
694     $values .= ', '.(int)$fields['record_type'];
695     $values .= ', '.$mdb2->quote($fields['bcc_email']);
696     $values .= ', '.$mdb2->quote($fields['allow_ip']);
697     $values .= ', '.$mdb2->quote($fields['password_complexity']);
698     $values .= ', '.$mdb2->quote($fields['plugins']);
699     $values .= ', '.$mdb2->quote($fields['lock_spec']);
700     $values .= ', '.(int)$fields['workday_minutes'];
701     $values .= ', '.$mdb2->quote($fields['config']);
702     $values .= ', now(), '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', '.$mdb2->quote($user->id);
703     $values .= ')';
704
705     $sql = 'insert into tt_groups '.$columns.$values;
706     $affected = $mdb2->exec($sql);
707     if (is_a($affected, 'PEAR_Error')) {
708       $this->errors->add($i18n->get('error.db'));
709       return false;
710     }
711
712     $group_id = $mdb2->lastInsertID('tt_groups', 'id');
713     return $group_id;
714   }
715
716   // insertMonthlyQuota - a helper function to insert a monthly quota.
717   private function insertMonthlyQuota($fields) {
718     $mdb2 = getConnection();
719     $group_id = (int) $fields['group_id'];
720     $org_id = (int) $fields['org_id'];
721     $year = (int) $fields['year'];
722     $month = (int) $fields['month'];
723     $minutes = (int) $fields['minutes'];
724
725     $sql = "INSERT INTO tt_monthly_quotas (group_id, org_id, year, month, minutes)".
726       " values ($group_id, $org_id, $year, $month, $minutes)";
727     $affected = $mdb2->exec($sql);
728     return (!is_a($affected, 'PEAR_Error'));
729   }
730
731   // insertPredefinedExpense - a helper function to insert a predefined expense.
732   private function insertPredefinedExpense($fields) {
733     $mdb2 = getConnection();
734     $group_id = (int) $fields['group_id'];
735     $org_id = (int) $fields['org_id'];
736     $name = $mdb2->quote($fields['name']);
737     $cost = $mdb2->quote($fields['cost']);
738
739     $sql = "INSERT INTO tt_predefined_expenses (group_id, org_id, name, cost)".
740       " values ($group_id, $org_id, $name, $cost)";
741     $affected = $mdb2->exec($sql);
742     return (!is_a($affected, 'PEAR_Error'));
743   }
744
745   // insertExpense - a helper function to insert an expense item.
746   private function insertExpense($fields) {
747     global $user;
748     $mdb2 = getConnection();
749
750     $group_id = (int) $fields['group_id'];
751     $org_id = (int) $fields['org_id'];
752     $date = $fields['date'];
753     $user_id = (int) $fields['user_id'];
754     $client_id = $fields['client_id'];
755     $project_id = $fields['project_id'];
756     $name = $fields['name'];
757     $cost = str_replace(',', '.', $fields['cost']);
758     $invoice_id = $fields['invoice_id'];
759     $status = $fields['status'];
760     $paid = (int) $fields['paid'];
761     $created = ', now(), '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', '.$mdb2->quote($user->id);
762
763     $sql = "insert into tt_expense_items".
764       " (date, user_id, group_id, org_id, client_id, project_id, name, cost, invoice_id, paid, created, created_ip, created_by, status)".
765       " values (".$mdb2->quote($date).", $user_id, $group_id, $org_id, ".$mdb2->quote($client_id).", ".$mdb2->quote($project_id).
766       ", ".$mdb2->quote($name).", ".$mdb2->quote($cost).", ".$mdb2->quote($invoice_id).", $paid $created, ".$mdb2->quote($status).")";
767     $affected = $mdb2->exec($sql);
768     return (!is_a($affected, 'PEAR_Error'));
769   }
770
771   // insertProject - a helper function to insert a project as well as project to task binds.
772   private function insertProject($fields)
773   {
774     $mdb2 = getConnection();
775
776     $group_id = (int) $fields['group_id'];
777     $org_id = (int) $fields['org_id'];
778
779     $name = $fields['name'];
780     $description = $fields['description'];
781     $tasks = $fields['tasks'];
782     $comma_separated = implode(',', $tasks); // This is a comma-separated list of associated task ids.
783     $status = $fields['status'];
784
785     $sql = "insert into tt_projects (group_id, org_id, name, description, tasks, status)
786       values ($group_id, $org_id, ".$mdb2->quote($name).", ".$mdb2->quote($description).", ".$mdb2->quote($comma_separated).", ".$mdb2->quote($status).")";
787     $affected = $mdb2->exec($sql);
788     if (is_a($affected, 'PEAR_Error'))
789       return false;
790
791     $last_id = 0;
792     $sql = "select last_insert_id() as last_insert_id";
793     $res = $mdb2->query($sql);
794     $val = $res->fetchRow();
795     $last_id = $val['last_insert_id'];
796
797     // Insert binds into tt_project_task_binds table.
798     if (is_array($tasks)) {
799       foreach ($tasks as $task_id) {
800         $sql = "insert into tt_project_task_binds (project_id, task_id, group_id, org_id)".
801           " values($last_id, $task_id, $group_id, $org_id)";
802         $affected = $mdb2->exec($sql);
803         if (is_a($affected, 'PEAR_Error'))
804           return false;
805       }
806     }
807
808     return $last_id;
809   }
810
811   // The insertClient function inserts a new client as well as client to project binds.
812   private function insertClient($fields)
813   {
814     $mdb2 = getConnection();
815
816     $group_id = (int) $fields['group_id'];
817     $org_id = (int) $fields['org_id'];
818     $name = $fields['name'];
819     $address = $fields['address'];
820     $tax = $fields['tax'];
821     $projects = $fields['projects'];
822     if ($projects)
823       $comma_separated = implode(',', $projects); // This is a comma-separated list of associated projects ids.
824     $status = $fields['status'];
825
826     $tax = str_replace(',', '.', $tax);
827     if ($tax == '') $tax = 0;
828
829     $sql = "insert into tt_clients (group_id, org_id, name, address, tax, projects, status)".
830       " values ($group_id, $org_id, ".$mdb2->quote($name).", ".$mdb2->quote($address).", $tax, ".$mdb2->quote($comma_separated).", ".$mdb2->quote($status).")";
831
832     $affected = $mdb2->exec($sql);
833     if (is_a($affected, 'PEAR_Error'))
834       return false;
835
836     $last_id = 0;
837     $sql = "select last_insert_id() as last_insert_id";
838     $res = $mdb2->query($sql);
839     $val = $res->fetchRow();
840     $last_id = $val['last_insert_id'];
841
842     if (count($projects) > 0)
843       foreach ($projects as $p_id) {
844         $sql = "insert into tt_client_project_binds (client_id, project_id, group_id, org_id) values($last_id, $p_id, $group_id, $org_id)";
845         $affected = $mdb2->exec($sql);
846         if (is_a($affected, 'PEAR_Error'))
847           return false;
848       }
849
850     return $last_id;
851   }
852
853   // insertFavReport - inserts a favorite report in database.
854   private function insertFavReport($fields) {
855     $mdb2 = getConnection();
856
857     $group_id = (int) $fields['group_id'];
858     $org_id = (int) $fields['org_id'];
859
860     $sql = "insert into tt_fav_reports".
861       " (name, user_id, group_id, org_id, client_id, cf_1_option_id, project_id, task_id,".
862       " billable, invoice, paid_status, users, period, period_start, period_end,".
863       " show_client, show_invoice, show_paid, show_ip,".
864       " show_project, show_start, show_duration, show_cost,".
865       " show_task, show_end, show_note, show_custom_field_1, show_work_units,".
866       " group_by1, group_by2, group_by3, show_totals_only)".
867       " values(".
868       $mdb2->quote($fields['name']).", ".$fields['user_id'].", $group_id, $org_id, ".
869       $mdb2->quote($fields['client']).", ".$mdb2->quote($fields['option']).", ".
870       $mdb2->quote($fields['project']).", ".$mdb2->quote($fields['task']).", ".
871       $mdb2->quote($fields['billable']).", ".$mdb2->quote($fields['invoice']).", ".
872       $mdb2->quote($fields['paid_status']).", ".
873       $mdb2->quote($fields['users']).", ".$mdb2->quote($fields['period']).", ".
874       $mdb2->quote($fields['from']).", ".$mdb2->quote($fields['to']).", ".
875       $fields['chclient'].", ".$fields['chinvoice'].", ".$fields['chpaid'].", ".$fields['chip'].", ".
876       $fields['chproject'].", ".$fields['chstart'].", ".$fields['chduration'].", ".$fields['chcost'].", ".
877       $fields['chtask'].", ".$fields['chfinish'].", ".$fields['chnote'].", ".$fields['chcf_1'].", ".$fields['chunits'].", ".
878       $mdb2->quote($fields['group_by1']).", ".$mdb2->quote($fields['group_by2']).", ".
879       $mdb2->quote($fields['group_by3']).", ".$fields['chtotalsonly'].")";
880     $affected = $mdb2->exec($sql);
881     if (is_a($affected, 'PEAR_Error'))
882       return false;
883
884     $sql = "select last_insert_id() as last_id";
885     $res = $mdb2->query($sql);
886     if (is_a($res, 'PEAR_Error'))
887       return false;
888
889     $val = $res->fetchRow();
890     return $val['last_id'];
891   }
892
893   // insertNotification function inserts a new notification into database.
894   private function insertNotification($fields)
895   {
896     $mdb2 = getConnection();
897
898     $group_id = (int) $fields['group_id'];
899     $org_id = (int) $fields['org_id'];
900     $cron_spec = $fields['cron_spec'];
901     $last = (int) $fields['last'];
902     $next = (int) $fields['next'];
903     $report_id = (int) $fields['report_id'];
904     $email = $fields['email'];
905     $cc = $fields['cc'];
906     $subject = $fields['subject'];
907     $report_condition = $fields['report_condition'];
908     $status = $fields['status'];
909
910     $sql = "insert into tt_cron".
911       " (group_id, org_id, cron_spec, last, next, report_id, email, cc, subject, report_condition, status)".
912       " 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).")";
913     $affected = $mdb2->exec($sql);
914     return (!is_a($affected, 'PEAR_Error'));
915   }
916
917   // insertUserParam - a helper function to insert a user parameter.
918   private function insertUserParam($fields) {
919     $mdb2 = getConnection();
920
921     $group_id = (int) $fields['group_id'];
922     $org_id = (int) $fields['org_id'];
923     $user_id = (int) $fields['user_id'];
924     $param_name = $fields['param_name'];
925     $param_value = $fields['param_value'];
926
927     $sql = "insert into tt_config".
928       " (user_id, group_id, org_id, param_name, param_value)".
929       " values ($user_id, $group_id, $org_id, ".$mdb2->quote($param_name).", ".$mdb2->quote($param_value).")";
930     $affected = $mdb2->exec($sql);
931     return (!is_a($affected, 'PEAR_Error'));
932   }
933
934   // insertCustomField - a helper function to insert a custom field.
935   private function insertCustomField($fields) {
936     $mdb2 = getConnection();
937
938     $group_id = (int) $fields['group_id'];
939     $org_id = (int) $fields['org_id'];
940     $type = (int) $fields['type'];
941     $label = $fields['label'];
942     $required = (int) $fields['required'];
943     $status = $fields['status'];
944
945     $sql = "insert into tt_custom_fields".
946       " (group_id, org_id, type, label, required, status)".
947       " values($group_id, $org_id, $type, ".$mdb2->quote($label).", $required, ".$mdb2->quote($status).")";
948     $affected = $mdb2->exec($sql);
949     if (is_a($affected, 'PEAR_Error'))
950       return false;
951
952     $last_id = 0;
953     $sql = "select last_insert_id() as last_insert_id";
954     $res = $mdb2->query($sql);
955     $val = $res->fetchRow();
956     $last_id = $val['last_insert_id'];
957     return $last_id;
958   }
959
960   // insertCustomFieldOption - a helper function to insert a custom field option.
961   private function insertCustomFieldOption($fields) {
962     $mdb2 = getConnection();
963
964     $group_id = (int) $fields['group_id'];
965     $org_id = (int) $fields['org_id'];
966     $field_id = (int) $fields['field_id'];
967     $value = $fields['value'];
968
969     $sql = "insert into tt_custom_field_options (group_id, org_id, field_id, value)".
970       " values ($group_id, $org_id, $field_id, ".$mdb2->quote($value).")";
971     $affected = $mdb2->exec($sql);
972     if (is_a($affected, 'PEAR_Error'))
973       return false;
974
975     $last_id = 0;
976     $sql = "select last_insert_id() as last_insert_id";
977     $res = $mdb2->query($sql);
978     $val = $res->fetchRow();
979     $last_id = $val['last_insert_id'];
980     return $last_id;
981   }
982
983   // insertCustomFieldLogEntry - a helper function to insert a custom field log entry.
984   private function insertCustomFieldLogEntry($fields) {
985     $mdb2 = getConnection();
986
987     $group_id = (int) $fields['group_id'];
988     $org_id = (int) $fields['org_id'];
989     $log_id = (int) $fields['log_id'];
990     $field_id = (int) $fields['field_id'];
991     $option_id = $fields['option_id'];
992     $value = $fields['value'];
993     $status = $fields['status'];
994
995     $sql = "insert into tt_custom_field_log (group_id, org_id, log_id, field_id, option_id, value, status)".
996       " values ($group_id, $org_id, $log_id, $field_id, ".$mdb2->quote($option_id).", ".$mdb2->quote($value).", ".$mdb2->quote($status).")";
997     $affected = $mdb2->exec($sql);
998     return (!is_a($affected, 'PEAR_Error'));
999   }
1000 }