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