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