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