Improved handlng of 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     if (!$_FILES['xmlfile']['name']) {
503       $this->errors->add($i18n->get('error.upload'));
504       return; // There is nothing to do if we don't have a file.
505     }
506
507     // Do we have a compressed file?
508     $compressed = false;
509     $file_ext = substr($_FILES['xmlfile']['name'], strrpos($_FILES['xmlfile']['name'], '.') + 1);
510     if (in_array($file_ext, array('bz','tbz','bz2','tbz2'))) {
511       $compressed = true;
512     }
513
514     // Create a temporary file.
515     $dirName = dirname(TEMPLATE_DIR . '_c/.');
516     $filename = tempnam($dirName, 'import_');
517
518     // If the file is compressed - uncompress it.
519     if ($compressed) {
520       if (!$this->uncompress($_FILES['xmlfile']['tmp_name'], $filename)) {
521         $this->errors->add($i18n->get('error.sys'));
522         return;
523       }
524       unlink($_FILES['xmlfile']['tmp_name']);
525     } else {
526       if (!move_uploaded_file($_FILES['xmlfile']['tmp_name'], $filename)) {
527         $this->errors->add($i18n->get('error.upload'));
528         return;
529       }
530     }
531
532     // Initialize XML parser.
533     $parser = xml_parser_create();
534     xml_set_object($parser, $this);
535     xml_set_element_handler($parser, 'startElement', false); // No need to process end tags in 1st pass.
536
537     // We need to parse the file 2 times:
538     //   1) First pass: determine if import is possible.
539     //   2) Second pass: import data, one tag at a time.
540
541     // Read and parse the content of the file. During parsing, startElement is called back for each tag.
542     $file = fopen($filename, 'r');
543     while (($data = fread($file, 4096)) && $this->errors->no()) {
544       if (!xml_parse($parser, $data, feof($file))) {
545         $this->errors->add(sprintf($i18n->get('error.xml'),
546           xml_get_current_line_number($parser),
547           xml_error_string(xml_get_error_code($parser))));
548       }
549     }
550     if ($this->conflicting_logins) {
551       $this->canImport = false;
552       $this->errors->add($i18n->get('error.user_exists'));
553       $this->errors->add(sprintf($i18n->get('error.cannot_import'), $this->conflicting_logins));
554     }
555
556     $this->firstPass = false; // We are done with 1st pass.
557     xml_parser_free($parser);
558     if ($file) fclose($file);
559     if ($this->errors->yes()) {
560       // Remove the file and exit if we have errors.
561       unlink($filename);
562       return;
563     }
564
565     // Now we can do a second pass, where real work is done.
566     $parser = xml_parser_create();
567     xml_set_object($parser, $this);
568     xml_set_element_handler($parser, 'startElement', 'endElement'); // Need to process ending tags too.
569
570     // Read and parse the content of the file. During parsing, startElement and endElement are called back for each tag.
571     $file = fopen($filename, 'r');
572     while (($data = fread($file, 4096)) && $this->errors->no()) {
573       if (!xml_parse($parser, $data, feof($file))) {
574         $this->errors->add(sprintf($i18n->get('error.xml'),
575           xml_get_current_line_number($parser),
576           xml_error_string(xml_get_error_code($parser))));
577       }
578     }
579     xml_parser_free($parser);
580     if ($file) fclose($file);
581     unlink($filename);
582   }
583
584   // uncompress - uncompresses the content of the $in file into the $out file.
585   function uncompress($in, $out) {
586     // Do we have the uncompress function?
587     if (!function_exists('bzopen'))
588       return false;
589
590     // Initial checks of file names and permissions.
591     if (!file_exists($in) || !is_readable ($in))
592       return false;
593     if ((!file_exists($out) && !is_writable(dirname($out))) || (file_exists($out) && !is_writable($out)))
594       return false;
595
596     if (!$out_file = fopen($out, 'wb'))
597       return false;
598     if (!$in_file = bzopen ($in, 'r'))
599       return false;
600
601     while (!feof($in_file)) {
602       $buffer = bzread($in_file, 4096);
603       fwrite($out_file, $buffer, 4096);
604     }
605     bzclose($in_file);
606     fclose ($out_file);
607     return true;
608   }
609
610   // createGroup function creates a new group.
611   private function createGroup($fields) {
612     global $user;
613     global $i18n;
614     $mdb2 = getConnection();
615
616     $columns = '(parent_id, org_id, name, description, currency, decimal_mark, lang, date_format, time_format'.
617       ', week_start, tracking_mode, project_required, task_required, record_type, bcc_email'.
618       ', allow_ip, password_complexity, plugins, lock_spec'.
619       ', workday_minutes, config, created, created_ip, created_by)';
620
621     $values = ' values (';
622     $values .= $mdb2->quote($fields['parent_id']);
623     $values .= ', '.$mdb2->quote($fields['org_id']);
624     $values .= ', '.$mdb2->quote(trim($fields['name']));
625     $values .= ', '.$mdb2->quote(trim($fields['description']));
626     $values .= ', '.$mdb2->quote(trim($fields['currency']));
627     $values .= ', '.$mdb2->quote($fields['decimal_mark']);
628     $values .= ', '.$mdb2->quote($fields['lang']);
629     $values .= ', '.$mdb2->quote($fields['date_format']);
630     $values .= ', '.$mdb2->quote($fields['time_format']);
631     $values .= ', '.(int)$fields['week_start'];
632     $values .= ', '.(int)$fields['tracking_mode'];
633     $values .= ', '.(int)$fields['project_required'];
634     $values .= ', '.(int)$fields['task_required'];
635     $values .= ', '.(int)$fields['record_type'];
636     $values .= ', '.$mdb2->quote($fields['bcc_email']);
637     $values .= ', '.$mdb2->quote($fields['allow_ip']);
638     $values .= ', '.$mdb2->quote($fields['password_complexity']);
639     $values .= ', '.$mdb2->quote($fields['plugins']);
640     $values .= ', '.$mdb2->quote($fields['lock_spec']);
641     $values .= ', '.(int)$fields['workday_minutes'];
642     $values .= ', '.$mdb2->quote($fields['config']);
643     $values .= ', now(), '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', '.$user->id;
644     $values .= ')';
645
646     $sql = 'insert into tt_groups '.$columns.$values;
647     $affected = $mdb2->exec($sql);
648     if (is_a($affected, 'PEAR_Error')) {
649       $this->errors->add($i18n->get('error.db'));
650       return false;
651     }
652
653     $group_id = $mdb2->lastInsertID('tt_groups', 'id');
654     return $group_id;
655   }
656
657   // insertMonthlyQuota - a helper function to insert a monthly quota.
658   private function insertMonthlyQuota($fields) {
659     $mdb2 = getConnection();
660
661     $group_id = (int) $fields['group_id'];
662     $org_id = (int) $fields['org_id'];
663     $year = (int) $fields['year'];
664     $month = (int) $fields['month'];
665     $minutes = (int) $fields['minutes'];
666
667     $sql = "INSERT INTO tt_monthly_quotas (group_id, org_id, year, month, minutes)".
668       " values ($group_id, $org_id, $year, $month, $minutes)";
669     $affected = $mdb2->exec($sql);
670     return (!is_a($affected, 'PEAR_Error'));
671   }
672
673   // insertPredefinedExpense - a helper function to insert a predefined expense.
674   private function insertPredefinedExpense($fields) {
675     $mdb2 = getConnection();
676
677     $group_id = (int) $fields['group_id'];
678     $org_id = (int) $fields['org_id'];
679     $name = $mdb2->quote($fields['name']);
680     $cost = $mdb2->quote($fields['cost']);
681
682     $sql = "INSERT INTO tt_predefined_expenses (group_id, org_id, name, cost)".
683       " values ($group_id, $org_id, $name, $cost)";
684     $affected = $mdb2->exec($sql);
685     return (!is_a($affected, 'PEAR_Error'));
686   }
687
688   // insertExpense - a helper function to insert an expense item.
689   private function insertExpense($fields) {
690     global $user;
691     $mdb2 = getConnection();
692
693     $group_id = (int) $fields['group_id'];
694     $org_id = (int) $fields['org_id'];
695     $date = $fields['date'];
696     $user_id = (int) $fields['user_id'];
697     $client_id = $fields['client_id'];
698     $project_id = $fields['project_id'];
699     $name = $fields['name'];
700     $cost = str_replace(',', '.', $fields['cost']);
701     $invoice_id = $fields['invoice_id'];
702     $status = $fields['status'];
703     $paid = (int) $fields['paid'];
704     $created = ', now(), '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', '.$user->id;
705
706     $sql = "insert into tt_expense_items".
707       " (date, user_id, group_id, org_id, client_id, project_id, name, cost, invoice_id, paid, created, created_ip, created_by, status)".
708       " values (".$mdb2->quote($date).", $user_id, $group_id, $org_id, ".$mdb2->quote($client_id).", ".$mdb2->quote($project_id).
709       ", ".$mdb2->quote($name).", ".$mdb2->quote($cost).", ".$mdb2->quote($invoice_id).", $paid $created, ".$mdb2->quote($status).")";
710     $affected = $mdb2->exec($sql);
711     return (!is_a($affected, 'PEAR_Error'));
712   }
713
714   // insertTask function inserts a new task into database.
715   private function insertTask($fields)
716   {
717     $mdb2 = getConnection();
718
719     $group_id = (int) $fields['group_id'];
720     $org_id = (int) $fields['org_id'];
721     $name = $fields['name'];
722     $description = $fields['description'];
723     $projects = $fields['projects'];
724     $status = $fields['status'];
725
726     $sql = "insert into tt_tasks (group_id, org_id, name, description, status)
727       values ($group_id, $org_id, ".$mdb2->quote($name).", ".$mdb2->quote($description).", ".$mdb2->quote($status).")";
728     $affected = $mdb2->exec($sql);
729     $last_id = 0;
730     if (is_a($affected, 'PEAR_Error'))
731       return false;
732
733     $last_id = $mdb2->lastInsertID('tt_tasks', 'id');
734     return $last_id;
735   }
736
737   // insertUserProjectBind - inserts a user to project bind into tt_user_project_binds table.
738   private function insertUserProjectBind($fields) {
739     $mdb2 = getConnection();
740
741     $group_id = (int) $fields['group_id'];
742     $org_id = (int) $fields['org_id'];
743     $user_id = (int) $fields['user_id'];
744     $project_id = (int) $fields['project_id'];
745     $rate = $mdb2->quote($fields['rate']);
746     $status = $mdb2->quote($fields['status']);
747
748     $sql = "insert into tt_user_project_binds (user_id, project_id, group_id, org_id, rate, status)".
749       " values($user_id, $project_id, $group_id, $org_id, $rate, $status)";
750     $affected = $mdb2->exec($sql);
751     return (!is_a($affected, 'PEAR_Error'));
752   }
753
754   // insertUser - inserts a user into database.
755   private function insertUser($fields) {
756     global $user;
757     $mdb2 = getConnection();
758
759     $group_id = (int) $fields['group_id'];
760     $org_id = (int) $fields['org_id'];
761
762     $columns = '(login, password, name, group_id, org_id, role_id, client_id, rate, email, created, created_ip, created_by, status)';
763
764     $values = 'values (';
765     $values .= $mdb2->quote($fields['login']);
766     $values .= ', '.$mdb2->quote($fields['password']);
767     $values .= ', '.$mdb2->quote($fields['name']);
768     $values .= ', '.$group_id;
769     $values .= ', '.$org_id;
770     $values .= ', '.(int)$fields['role_id'];
771     $values .= ', '.$mdb2->quote($fields['client_id']);
772     $values .= ', '.$mdb2->quote($fields['rate']);
773     $values .= ', '.$mdb2->quote($fields['email']);
774     $values .= ', now(), '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', '.$user->id;
775     $values .= ', '.$mdb2->quote($fields['status']);
776     $values .= ')';
777
778     $sql = "insert into tt_users $columns $values";
779     $affected = $mdb2->exec($sql);
780     if (is_a($affected, 'PEAR_Error')) return false;
781
782     $last_id = $mdb2->lastInsertID('tt_users', 'id');
783     return $last_id;
784   }
785
786   // insertProject - a helper function to insert a project as well as project to task binds.
787   private function insertProject($fields)
788   {
789     $mdb2 = getConnection();
790
791     $group_id = (int) $fields['group_id'];
792     $org_id = (int) $fields['org_id'];
793     $name = $fields['name'];
794     $description = $fields['description'];
795     $tasks = $fields['tasks'];
796     $comma_separated = implode(',', $tasks); // This is a comma-separated list of associated task ids.
797     $status = $fields['status'];
798
799     $sql = "insert into tt_projects (group_id, org_id, name, description, tasks, status)
800       values ($group_id, $org_id, ".$mdb2->quote($name).", ".$mdb2->quote($description).", ".$mdb2->quote($comma_separated).", ".$mdb2->quote($status).")";
801     $affected = $mdb2->exec($sql);
802     if (is_a($affected, 'PEAR_Error'))
803       return false;
804
805     $last_id = $mdb2->lastInsertID('tt_projects', 'id');
806
807     // Insert binds into tt_project_task_binds table.
808     if (is_array($tasks)) {
809       foreach ($tasks as $task_id) {
810         $sql = "insert into tt_project_task_binds (project_id, task_id, group_id, org_id)".
811           " values($last_id, $task_id, $group_id, $org_id)";
812         $affected = $mdb2->exec($sql);
813         if (is_a($affected, 'PEAR_Error'))
814           return false;
815       }
816     }
817
818     return $last_id;
819   }
820
821   // insertRole - inserts a role into tt_roles table.
822   private function insertRole($fields)
823   {
824     $mdb2 = getConnection();
825
826     $group_id = (int) $fields['group_id'];
827     $org_id = (int) $fields['org_id'];
828     $name = $fields['name'];
829     $rank = (int) $fields['rank'];
830     $description = $fields['description'];
831     $rights = $fields['rights'];
832     $status = $fields['status'];
833
834     $sql = "insert into tt_roles (group_id, org_id, name, rank, description, rights, status)
835       values ($group_id, $org_id, ".$mdb2->quote($name).", $rank, ".$mdb2->quote($description).", ".$mdb2->quote($rights).", ".$mdb2->quote($status).")";
836     $affected = $mdb2->exec($sql);
837     if (is_a($affected, 'PEAR_Error'))
838       return false;
839
840     $last_id = $mdb2->lastInsertID('tt_roles', 'id');
841     return $last_id;
842   }
843
844   // insertInvoice - inserts an invoice in database.
845   private function insertInvoice($fields)
846   {
847     $mdb2 = getConnection();
848
849     $group_id = (int) $fields['group_id'];
850     $org_id = (int) $fields['org_id'];
851     $name = $fields['name'];
852     $client_id = (int) $fields['client_id'];
853     $date = $fields['date'];
854     $status = $fields['status'];
855
856     // Insert a new invoice record.
857     $sql = "insert into tt_invoices (group_id, org_id, name, date, client_id, status)".
858       " values($group_id, $org_id, ".$mdb2->quote($name).", ".$mdb2->quote($date).", $client_id, ".$mdb2->quote($fields['status']).")";
859     $affected = $mdb2->exec($sql);
860     if (is_a($affected, 'PEAR_Error')) return false;
861
862     $last_id = $mdb2->lastInsertID('tt_invoices', 'id');
863     return $last_id;
864   }
865
866   // The insertClient function inserts a new client as well as client to project binds.
867   private function insertClient($fields)
868   {
869     $mdb2 = getConnection();
870
871     $group_id = (int) $fields['group_id'];
872     $org_id = (int) $fields['org_id'];
873     $name = $fields['name'];
874     $address = $fields['address'];
875     $tax = $fields['tax'];
876     $projects = $fields['projects'];
877     if ($projects)
878       $comma_separated = implode(',', $projects); // This is a comma-separated list of associated projects ids.
879     $status = $fields['status'];
880
881     $tax = str_replace(',', '.', $tax);
882     if ($tax == '') $tax = 0;
883
884     $sql = "insert into tt_clients (group_id, org_id, name, address, tax, projects, status)".
885       " values ($group_id, $org_id, ".$mdb2->quote($name).", ".$mdb2->quote($address).", $tax, ".$mdb2->quote($comma_separated).", ".$mdb2->quote($status).")";
886
887     $affected = $mdb2->exec($sql);
888     if (is_a($affected, 'PEAR_Error'))
889       return false;
890
891     $last_id = $mdb2->lastInsertID('tt_clients', 'id');
892
893     if (count($projects) > 0)
894       foreach ($projects as $p_id) {
895         $sql = "insert into tt_client_project_binds (client_id, project_id, group_id, org_id) values($last_id, $p_id, $group_id, $org_id)";
896         $affected = $mdb2->exec($sql);
897         if (is_a($affected, 'PEAR_Error'))
898           return false;
899       }
900
901     return $last_id;
902   }
903
904   // insertFavReport - inserts a favorite report in database.
905   private function insertFavReport($fields) {
906     $mdb2 = getConnection();
907
908     $group_id = (int) $fields['group_id'];
909     $org_id = (int) $fields['org_id'];
910
911     $sql = "insert into tt_fav_reports".
912       " (name, user_id, group_id, org_id, client_id, cf_1_option_id, project_id, task_id,".
913       " billable, invoice, paid_status, users, period, period_start, period_end,".
914       " show_client, show_invoice, show_paid, show_ip,".
915       " show_project, show_start, show_duration, show_cost,".
916       " show_task, show_end, show_note, show_custom_field_1, show_work_units,".
917       " group_by1, group_by2, group_by3, show_totals_only)".
918       " values(".
919       $mdb2->quote($fields['name']).", ".$fields['user_id'].", $group_id, $org_id, ".
920       $mdb2->quote($fields['client']).", ".$mdb2->quote($fields['option']).", ".
921       $mdb2->quote($fields['project']).", ".$mdb2->quote($fields['task']).", ".
922       $mdb2->quote($fields['billable']).", ".$mdb2->quote($fields['invoice']).", ".
923       $mdb2->quote($fields['paid_status']).", ".
924       $mdb2->quote($fields['users']).", ".$mdb2->quote($fields['period']).", ".
925       $mdb2->quote($fields['from']).", ".$mdb2->quote($fields['to']).", ".
926       $fields['chclient'].", ".$fields['chinvoice'].", ".$fields['chpaid'].", ".$fields['chip'].", ".
927       $fields['chproject'].", ".$fields['chstart'].", ".$fields['chduration'].", ".$fields['chcost'].", ".
928       $fields['chtask'].", ".$fields['chfinish'].", ".$fields['chnote'].", ".$fields['chcf_1'].", ".$fields['chunits'].", ".
929       $mdb2->quote($fields['group_by1']).", ".$mdb2->quote($fields['group_by2']).", ".
930       $mdb2->quote($fields['group_by3']).", ".$fields['chtotalsonly'].")";
931     $affected = $mdb2->exec($sql);
932     if (is_a($affected, 'PEAR_Error'))
933       return false;
934
935     $last_id = $mdb2->lastInsertID('tt_fav_reports', 'id');
936     return $last_id;
937   }
938
939   // insertNotification function inserts a new notification into database.
940   private function insertNotification($fields)
941   {
942     $mdb2 = getConnection();
943
944     $group_id = (int) $fields['group_id'];
945     $org_id = (int) $fields['org_id'];
946     $cron_spec = $fields['cron_spec'];
947     $last = (int) $fields['last'];
948     $next = (int) $fields['next'];
949     $report_id = (int) $fields['report_id'];
950     $email = $fields['email'];
951     $cc = $fields['cc'];
952     $subject = $fields['subject'];
953     $report_condition = $fields['report_condition'];
954     $status = $fields['status'];
955
956     $sql = "insert into tt_cron".
957       " (group_id, org_id, cron_spec, last, next, report_id, email, cc, subject, report_condition, status)".
958       " 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).")";
959     $affected = $mdb2->exec($sql);
960     return (!is_a($affected, 'PEAR_Error'));
961   }
962
963   // insertUserParam - a helper function to insert a user parameter.
964   private function insertUserParam($fields) {
965     $mdb2 = getConnection();
966
967     $group_id = (int) $fields['group_id'];
968     $org_id = (int) $fields['org_id'];
969     $user_id = (int) $fields['user_id'];
970     $param_name = $fields['param_name'];
971     $param_value = $fields['param_value'];
972
973     $sql = "insert into tt_config".
974       " (user_id, group_id, org_id, param_name, param_value)".
975       " values ($user_id, $group_id, $org_id, ".$mdb2->quote($param_name).", ".$mdb2->quote($param_value).")";
976     $affected = $mdb2->exec($sql);
977     return (!is_a($affected, 'PEAR_Error'));
978   }
979
980   // insertCustomField - a helper function to insert a custom field.
981   private function insertCustomField($fields) {
982     $mdb2 = getConnection();
983
984     $group_id = (int) $fields['group_id'];
985     $org_id = (int) $fields['org_id'];
986     $type = (int) $fields['type'];
987     $label = $fields['label'];
988     $required = (int) $fields['required'];
989     $status = $fields['status'];
990
991     $sql = "insert into tt_custom_fields".
992       " (group_id, org_id, type, label, required, status)".
993       " values($group_id, $org_id, $type, ".$mdb2->quote($label).", $required, ".$mdb2->quote($status).")";
994     $affected = $mdb2->exec($sql);
995     if (is_a($affected, 'PEAR_Error'))
996       return false;
997
998     $last_id = $mdb2->lastInsertID('tt_custom_fields', 'id');
999     return $last_id;
1000   }
1001
1002   // insertCustomFieldOption - a helper function to insert a custom field option.
1003   private function insertCustomFieldOption($fields) {
1004     $mdb2 = getConnection();
1005
1006     $group_id = (int) $fields['group_id'];
1007     $org_id = (int) $fields['org_id'];
1008     $field_id = (int) $fields['field_id'];
1009     $value = $fields['value'];
1010
1011     $sql = "insert into tt_custom_field_options (group_id, org_id, field_id, value)".
1012       " values ($group_id, $org_id, $field_id, ".$mdb2->quote($value).")";
1013     $affected = $mdb2->exec($sql);
1014     if (is_a($affected, 'PEAR_Error'))
1015       return false;
1016
1017     $last_id = $mdb2->lastInsertID('tt_custom_field_options', 'id');
1018     return $last_id;
1019   }
1020
1021   // insertLogEntry - a helper function to insert a time log entry.
1022   private function insertLogEntry($fields) {
1023     global $user;
1024     $mdb2 = getConnection();
1025
1026     $group_id = (int) $fields['group_id'];
1027     $org_id = (int) $fields['org_id'];
1028     $user_id = (int) $fields['user_id'];
1029     $date = $fields['date'];
1030     $start = $fields['start'];
1031     $duration = $fields['duration'];
1032     $client_id = $fields['client_id'];
1033     $project_id = $fields['project_id'];
1034     $task_id = $fields['task_id'];
1035     $invoice_id = $fields['invoice_id'];
1036     $comment = $fields['comment'];
1037     $billable = (int) $fields['billable'];
1038     $paid = (int) $fields['paid'];
1039     $status = $fields['status'];
1040
1041     $sql = "insert into tt_log".
1042       " (user_id, group_id, org_id, date, start, duration, client_id, project_id, task_id, invoice_id, comment".
1043       ", billable, paid, created, created_ip, created_by, status)".
1044       " values ($user_id, $group_id, $org_id".
1045       ", ".$mdb2->quote($date).
1046       ", ".$mdb2->quote($start).
1047       ", ".$mdb2->quote($duration).
1048       ", ".$mdb2->quote($client_id).
1049       ", ".$mdb2->quote($project_id).
1050       ", ".$mdb2->quote($task_id).
1051       ", ".$mdb2->quote($invoice_id).
1052       ", ".$mdb2->quote($comment).
1053       ", $billable, $paid".
1054       ", now(), ".$mdb2->quote($_SERVER['REMOTE_ADDR']).", ".$user->id.
1055       ", ". $mdb2->quote($status).")";
1056     $affected = $mdb2->exec($sql);
1057     if (is_a($affected, 'PEAR_Error')) {
1058       $this->errors->add($i18n->get('error.db')); // TODO: review whether or not to add error here in all insert calls.
1059       return false;
1060     }
1061
1062     $log_id = $mdb2->lastInsertID('tt_log', 'id');
1063     return $log_id;
1064   }
1065
1066   // insertCustomFieldLogEntry - a helper function to insert a custom field log entry.
1067   private function insertCustomFieldLogEntry($fields) {
1068     $mdb2 = getConnection();
1069
1070     $group_id = (int) $fields['group_id'];
1071     $org_id = (int) $fields['org_id'];
1072     $log_id = (int) $fields['log_id'];
1073     $field_id = (int) $fields['field_id'];
1074     $option_id = $fields['option_id'];
1075     $value = $fields['value'];
1076     $status = $fields['status'];
1077
1078     $sql = "insert into tt_custom_field_log (group_id, org_id, log_id, field_id, option_id, value, status)".
1079       " values ($group_id, $org_id, $log_id, $field_id, ".$mdb2->quote($option_id).", ".$mdb2->quote($value).", ".$mdb2->quote($status).")";
1080     $affected = $mdb2->exec($sql);
1081     return (!is_a($affected, 'PEAR_Error'));
1082   }
1083
1084   // getTopRole returns top role id.
1085   private function getTopRole() {
1086     $mdb2 = getConnection();
1087
1088     $sql = "select id from tt_roles where group_id = 0 and rank = ".MAX_RANK." and status = 1";
1089     $res = $mdb2->query($sql);
1090
1091     if (!is_a($res, 'PEAR_Error')) {
1092       $val = $res->fetchRow();
1093       if ($val['id'])
1094         return $val['id'];
1095     }
1096     return false;
1097   }
1098
1099   // The loginExists function detrmines if a login already exists.
1100   private function loginExists($login) {
1101     $mdb2 = getConnection();
1102
1103     $sql = "select id from tt_users where login = ".$mdb2->quote($login)." and (status = 1 or status = 0)";
1104     $res = $mdb2->query($sql);
1105     if (!is_a($res, 'PEAR_Error')) {
1106       if ($val = $res->fetchRow()) {
1107         return true;
1108       }
1109     }
1110     return false;
1111   }
1112 }