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