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