A few fixes related to tt_timesheets fields renaming.
[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   // TODO: add handling of these.
290   //`start_date` date NOT NULL,                      # timesheet start date
291   //`end_date` date NOT NULL,                        # timesheet end date
292           'submit_status' => $attrs['SUBMIT_STATUS'],
293           'approve_status' => $attrs['APPROVE_STATUS'],
294           'approve_comment' => $attrs['APPROVE_COMMENT'],
295           'status' => $attrs['STATUS']));
296         if ($timesheet_id) {
297           // Add a mapping.
298           $this->currentGroupTimesheetMap[$attrs['ID']] = $timesheet_id;
299         } else {
300           $this->errors->add($i18n->get('error.db'));
301         }
302         return;
303       }
304
305       if ($name == 'INVOICE') {
306         // We get here when processing <invoice> tags for the current group.
307         $invoice_id = $this->insertInvoice(array(
308           'group_id' => $this->current_group_id,
309           'org_id' => $this->org_id,
310           'name' => $attrs['NAME'],
311           'date' => $attrs['DATE'],
312           'client_id' => $this->currentGroupClientMap[$attrs['CLIENT_ID']],
313           'status' => $attrs['STATUS']));
314         if ($invoice_id) {
315           // Add a mapping.
316           $this->currentGroupInvoiceMap[$attrs['ID']] = $invoice_id;
317         } else {
318           $this->errors->add($i18n->get('error.db'));
319         }
320         return;
321       }
322
323       if ($name == 'LOG_ITEM') {
324         // We get here when processing <log_item> tags for the current group.
325         $log_item_id = $this->insertLogEntry(array(
326           'user_id' => $this->currentGroupUserMap[$attrs['USER_ID']],
327           'group_id' => $this->current_group_id,
328           'org_id' => $this->org_id,
329           'date' => $attrs['DATE'],
330           'start' => $attrs['START'],
331           'finish' => $attrs['FINISH'],
332           'duration' => $attrs['DURATION'],
333           'client_id' => $this->currentGroupClientMap[$attrs['CLIENT_ID']],
334           'project_id' => $this->currentGroupProjectMap[$attrs['PROJECT_ID']],
335           'task_id' => $this->currentGroupTaskMap[$attrs['TASK_ID']],
336           'timesheet_id' => $this->currentGroupTimesheetMap[$attrs['TIMESHEET_ID']],
337           'invoice_id' => $this->currentGroupInvoiceMap[$attrs['INVOICE_ID']],
338           'comment' => (isset($attrs['COMMENT']) ? $attrs['COMMENT'] : ''),
339           'billable' => $attrs['BILLABLE'],
340           'approved' => $attrs['APPROVED'],
341           'paid' => $attrs['PAID'],
342           'status' => $attrs['STATUS']));
343         if ($log_item_id) {
344           // Add a mapping.
345           $this->currentGroupLogMap[$attrs['ID']] = $log_item_id;
346         } else $this->errors->add($i18n->get('error.db'));
347         return;
348       }
349
350       if ($name == 'CUSTOM_FIELD') {
351         // We get here when processing <custom_field> tags for the current group.
352         $custom_field_id = $this->insertCustomField(array(
353           'group_id' => $this->current_group_id,
354           'org_id' => $this->org_id,
355           'type' => $attrs['TYPE'],
356           'label' => $attrs['LABEL'],
357           'required' => $attrs['REQUIRED'],
358           'status' => $attrs['STATUS']));
359         if ($custom_field_id) {
360           // Add a mapping.
361           $this->currentGroupCustomFieldMap[$attrs['ID']] = $custom_field_id;
362         } else $this->errors->add($i18n->get('error.db'));
363         return;
364       }
365
366       if ($name == 'CUSTOM_FIELD_OPTION') {
367         // We get here when processing <custom_field_option> tags for the current group.
368         $custom_field_option_id = $this->insertCustomFieldOption(array(
369           'group_id' => $this->current_group_id,
370           'org_id' => $this->org_id,
371           'field_id' => $this->currentGroupCustomFieldMap[$attrs['FIELD_ID']],
372           'value' => $attrs['VALUE']));
373         if ($custom_field_option_id) {
374           // Add a mapping.
375           $this->currentGroupCustomFieldOptionMap[$attrs['ID']] = $custom_field_option_id;
376         } else $this->errors->add($i18n->get('error.db'));
377         return;
378       }
379
380       if ($name == 'CUSTOM_FIELD_LOG_ENTRY') {
381         // We get here when processing <custom_field_log_entry> tags for the current group.
382         if (!$this->insertCustomFieldLogEntry(array(
383           'group_id' => $this->current_group_id,
384           'org_id' => $this->org_id,
385           'log_id' => $this->currentGroupLogMap[$attrs['LOG_ID']],
386           'field_id' => $this->currentGroupCustomFieldMap[$attrs['FIELD_ID']],
387           'option_id' => $this->currentGroupCustomFieldOptionMap[$attrs['OPTION_ID']],
388           'value' => $attrs['VALUE'],
389           'status' => $attrs['STATUS']))) {
390           $this->errors->add($i18n->get('error.db'));
391         }
392         return;
393       }
394
395       if ($name == 'EXPENSE_ITEM') {
396         // We get here when processing <expense_item> tags for the current group.
397         $expense_item_id = $this->insertExpense(array(
398           'date' => $attrs['DATE'],
399           'user_id' => $this->currentGroupUserMap[$attrs['USER_ID']],
400           'group_id' => $this->current_group_id,
401           'org_id' => $this->org_id,
402           'client_id' => $this->currentGroupClientMap[$attrs['CLIENT_ID']],
403           'project_id' => $this->currentGroupProjectMap[$attrs['PROJECT_ID']],
404           'timesheet_id' => $this->currentGroupTimesheetMap[$attrs['TIMESHEET_ID']],
405           'name' => $attrs['NAME'],
406           'cost' => $attrs['COST'],
407           'invoice_id' => $this->currentGroupInvoiceMap[$attrs['INVOICE_ID']],
408           'approved' => $attrs['APPROVED'],
409           'paid' => $attrs['PAID'],
410           'status' => $attrs['STATUS']));
411         if (!$expense_item_id) $this->errors->add($i18n->get('error.db'));
412         return;
413       }
414
415       if ($name == 'PREDEFINED_EXPENSE') {
416         if (!$this->insertPredefinedExpense(array(
417           'group_id' => $this->current_group_id,
418           'org_id' => $this->org_id,
419           'name' => $attrs['NAME'],
420           'cost' => $attrs['COST']))) {
421           $this->errors->add($i18n->get('error.db'));
422         }
423         return;
424       }
425
426       if ($name == 'MONTHLY_QUOTA') {
427         if (!$this->insertMonthlyQuota(array(
428           'group_id' => $this->current_group_id,
429           'org_id' => $this->org_id,
430           'year' => $attrs['YEAR'],
431           'month' => $attrs['MONTH'],
432           'minutes' => $attrs['MINUTES']))) {
433           $this->errors->add($i18n->get('error.db'));
434         }
435         return;
436       }
437
438       if ($name == 'FAV_REPORT') {
439         $user_list = '';
440         if (strlen($attrs['USERS']) > 0) {
441           $arr = explode(',', $attrs['USERS']);
442           foreach ($arr as $v)
443             $user_list .= (strlen($user_list) == 0 ? '' : ',').$this->currentGroupUserMap[$v];
444         }
445         $fav_report_id = $this->insertFavReport(array(
446           'name' => $attrs['NAME'],
447           'user_id' => $this->currentGroupUserMap[$attrs['USER_ID']],
448           'group_id' => $this->current_group_id,
449           'org_id' => $this->org_id,
450           'client' => $this->currentGroupClientMap[$attrs['CLIENT_ID']],
451           'option' => $this->currentGroupCustomFieldOptionMap[$attrs['CF_1_OPTION_ID']],
452           'project' => $this->currentGroupProjectMap[$attrs['PROJECT_ID']],
453           'task' => $this->currentGroupTaskMap[$attrs['TASK_ID']],
454           'billable' => $attrs['BILLABLE'],
455           'approved' => $attrs['APPROVED'],
456           'invoice' => $attrs['INVOICE'],
457           'timesheet' => $attrs['TIMESHEET'],
458           'paid_status' => $attrs['PAID_STATUS'],
459           'users' => $user_list,
460           'period' => $attrs['PERIOD'],
461           'from' => $attrs['PERIOD_START'],
462           'to' => $attrs['PERIOD_END'],
463           'chclient' => (int) $attrs['SHOW_CLIENT'],
464           'chinvoice' => (int) $attrs['SHOW_INVOICE'],
465           'chpaid' => (int) $attrs['SHOW_PAID'],
466           'chip' => (int) $attrs['SHOW_IP'],
467           'chproject' => (int) $attrs['SHOW_PROJECT'],
468           'chtimesheet' => (int) $attrs['SHOW_TIMESHEET'],
469           'chstart' => (int) $attrs['SHOW_START'],
470           'chduration' => (int) $attrs['SHOW_DURATION'],
471           'chcost' => (int) $attrs['SHOW_COST'],
472           'chtask' => (int) $attrs['SHOW_TASK'],
473           'chfinish' => (int) $attrs['SHOW_END'],
474           'chnote' => (int) $attrs['SHOW_NOTE'],
475           'chapproved' => (int) $attrs['SHOW_APPROVED'],
476           'chcf_1' => (int) $attrs['SHOW_CUSTOM_FIELD_1'],
477           'chunits' => (int) $attrs['SHOW_WORK_UNITS'],
478           'group_by1' => $attrs['GROUP_BY1'],
479           'group_by2' => $attrs['GROUP_BY2'],
480           'group_by3' => $attrs['GROUP_BY3'],
481           'chtotalsonly' => (int) $attrs['SHOW_TOTALS_ONLY']));
482         if ($fav_report_id) {
483           // Add a mapping.
484           $this->currentGroupFavReportMap[$attrs['ID']] = $fav_report_id;
485           } else $this->errors->add($i18n->get('error.db'));
486         return;
487       }
488
489       if ($name == 'NOTIFICATION') {
490         if (!$this->insertNotification(array(
491           'group_id' => $this->current_group_id,
492           'org_id' => $this->org_id,
493           'cron_spec' => $attrs['CRON_SPEC'],
494           'last' => $attrs['LAST'],
495           'next' => $attrs['NEXT'],
496           'report_id' => $this->currentGroupFavReportMap[$attrs['REPORT_ID']],
497           'email' => $attrs['EMAIL'],
498           'cc' => $attrs['CC'],
499           'subject' => $attrs['SUBJECT'],
500           'report_condition' => $attrs['REPORT_CONDITION'],
501           'status' => $attrs['STATUS']))) {
502           $this->errors->add($i18n->get('error.db'));
503         }
504         return;
505       }
506
507       if ($name == 'USER_PARAM') {
508         if (!$this->insertUserParam(array(
509           'group_id' => $this->current_group_id,
510           'org_id' => $this->org_id,
511           'user_id' => $this->currentGroupUserMap[$attrs['USER_ID']],
512           'param_name' => $attrs['PARAM_NAME'],
513           'param_value' => $attrs['PARAM_VALUE']))) {
514           $this->errors->add($i18n->get('error.db'));
515         }
516         return;
517       }
518     }
519   }
520
521   // endElement - callback handler for ending tags in XML.
522   // We use this only for process </group> element endings and
523   // set current_group_id to an immediate parent.
524   // This is required to import group hierarchy correctly.
525   function endElement($parser, $name) {
526     // No need to care about first or second pass, as this is used only in second pass.
527     // See 2nd xml_set_element_handler, where this handler is set.
528     if ($name == 'GROUP') {
529       // Remove self from the parent stack.
530       $self = array_pop($this->parents);
531       // Set current group id to an immediate parent.
532       $len = count($this->parents);
533       $this->current_group_id = $len ? $this->parents[$len-1] : null;
534     }
535   }
536
537   // importXml - uncompresses the file, reads and parses its content.
538   // It goes through the file 2 times.
539   //
540   // During 1st pass, it determines whether we can import data.
541   // In 1st pass, startElement function is called as many times as necessary.
542   //
543   // Actual import occurs during 2nd pass.
544   // In 2nd pass, startElement and endElement are called many times.
545   // We only use endElement to finish current group processing.
546   //
547   // The above allows us to export/import complex orgs with nested groups,
548   // while by design all data are in attributes of the elements (no CDATA).
549   //
550   // There is currently at least one problem with keeping all data in attributes:
551   // a vertical tab character 0xB anywhere breaks parsing, making import impossible.
552   // See https://github.com/sparklemotion/nokogiri/issues/1581 - looks like
553   // an XML standard thing. Apparently, other invalid characters break parsing too.
554   // This problem needs to be addressed at some point but how exactly without
555   // complicating export-import too much with CDATA and dataElement processing?
556   function importXml() {
557     global $i18n;
558
559     if (!$_FILES['xmlfile']['name']) {
560       $this->errors->add($i18n->get('error.upload'));
561       return; // There is nothing to do if we don't have a file.
562     }
563
564     // Do we have a compressed file?
565     $compressed = false;
566     $file_ext = substr($_FILES['xmlfile']['name'], strrpos($_FILES['xmlfile']['name'], '.') + 1);
567     if (in_array($file_ext, array('bz','tbz','bz2','tbz2'))) {
568       $compressed = true;
569     }
570
571     // Create a temporary file.
572     $dirName = dirname(TEMPLATE_DIR . '_c/.');
573     $filename = tempnam($dirName, 'import_');
574
575     // If the file is compressed - uncompress it.
576     if ($compressed) {
577       if (!$this->uncompress($_FILES['xmlfile']['tmp_name'], $filename)) {
578         $this->errors->add($i18n->get('error.sys'));
579         return;
580       }
581       unlink($_FILES['xmlfile']['tmp_name']);
582     } else {
583       if (!move_uploaded_file($_FILES['xmlfile']['tmp_name'], $filename)) {
584         $this->errors->add($i18n->get('error.upload'));
585         return;
586       }
587     }
588
589     // Initialize XML parser.
590     $parser = xml_parser_create();
591     xml_set_object($parser, $this);
592     xml_set_element_handler($parser, 'startElement', false); // No need to process end tags in 1st pass.
593
594     // We need to parse the file 2 times:
595     //   1) First pass: determine if import is possible.
596     //   2) Second pass: import data, one tag at a time.
597
598     // Read and parse the content of the file. During parsing, startElement is called back for each tag.
599     $file = fopen($filename, 'r');
600     while (($data = fread($file, 4096)) && $this->errors->no()) {
601       if (!xml_parse($parser, $data, feof($file))) {
602         $this->errors->add(sprintf($i18n->get('error.xml'),
603           xml_get_current_line_number($parser),
604           xml_error_string(xml_get_error_code($parser))));
605       }
606     }
607     if ($this->conflicting_logins) {
608       $this->canImport = false;
609       $this->errors->add($i18n->get('error.user_exists'));
610       $this->errors->add(sprintf($i18n->get('error.cannot_import'), $this->conflicting_logins));
611     }
612     if (!ttUserHelper::canAdd($this->num_users)) {
613       $this->canImport = false;
614       $this->errors->add($i18n->get('error.user_count'));
615     }
616
617     $this->firstPass = false; // We are done with 1st pass.
618     xml_parser_free($parser);
619     if ($file) fclose($file);
620     if ($this->errors->yes()) {
621       // Remove the file and exit if we have errors.
622       unlink($filename);
623       return;
624     }
625
626     // Now we can do a second pass, where real work is done.
627     $parser = xml_parser_create();
628     xml_set_object($parser, $this);
629     xml_set_element_handler($parser, 'startElement', 'endElement'); // Need to process ending tags too.
630
631     // Read and parse the content of the file. During parsing, startElement and endElement are called back for each tag.
632     $file = fopen($filename, 'r');
633     while (($data = fread($file, 4096)) && $this->errors->no()) {
634       if (!xml_parse($parser, $data, feof($file))) {
635         $this->errors->add(sprintf($i18n->get('error.xml'),
636           xml_get_current_line_number($parser),
637           xml_error_string(xml_get_error_code($parser))));
638       }
639     }
640     xml_parser_free($parser);
641     if ($file) fclose($file);
642     unlink($filename);
643   }
644
645   // uncompress - uncompresses the content of the $in file into the $out file.
646   function uncompress($in, $out) {
647     // Do we have the uncompress function?
648     if (!function_exists('bzopen'))
649       return false;
650
651     // Initial checks of file names and permissions.
652     if (!file_exists($in) || !is_readable ($in))
653       return false;
654     if ((!file_exists($out) && !is_writable(dirname($out))) || (file_exists($out) && !is_writable($out)))
655       return false;
656
657     if (!$out_file = fopen($out, 'wb'))
658       return false;
659     if (!$in_file = bzopen ($in, 'r'))
660       return false;
661
662     while (!feof($in_file)) {
663       $buffer = bzread($in_file, 4096);
664       fwrite($out_file, $buffer, 4096);
665     }
666     bzclose($in_file);
667     fclose ($out_file);
668     return true;
669   }
670
671   // createGroup function creates a new group.
672   private function createGroup($fields) {
673     global $user;
674     global $i18n;
675     $mdb2 = getConnection();
676
677     $columns = '(parent_id, org_id, name, description, currency, decimal_mark, lang, date_format, time_format'.
678       ', week_start, tracking_mode, project_required, task_required, record_type, bcc_email'.
679       ', allow_ip, password_complexity, plugins, lock_spec'.
680       ', workday_minutes, config, created, created_ip, created_by)';
681
682     $values = ' values (';
683     $values .= $mdb2->quote($fields['parent_id']);
684     $values .= ', '.$mdb2->quote($fields['org_id']);
685     $values .= ', '.$mdb2->quote(trim($fields['name']));
686     $values .= ', '.$mdb2->quote(trim($fields['description']));
687     $values .= ', '.$mdb2->quote(trim($fields['currency']));
688     $values .= ', '.$mdb2->quote($fields['decimal_mark']);
689     $values .= ', '.$mdb2->quote($fields['lang']);
690     $values .= ', '.$mdb2->quote($fields['date_format']);
691     $values .= ', '.$mdb2->quote($fields['time_format']);
692     $values .= ', '.(int)$fields['week_start'];
693     $values .= ', '.(int)$fields['tracking_mode'];
694     $values .= ', '.(int)$fields['project_required'];
695     $values .= ', '.(int)$fields['task_required'];
696     $values .= ', '.(int)$fields['record_type'];
697     $values .= ', '.$mdb2->quote($fields['bcc_email']);
698     $values .= ', '.$mdb2->quote($fields['allow_ip']);
699     $values .= ', '.$mdb2->quote($fields['password_complexity']);
700     $values .= ', '.$mdb2->quote($fields['plugins']);
701     $values .= ', '.$mdb2->quote($fields['lock_spec']);
702     $values .= ', '.(int)$fields['workday_minutes'];
703     $values .= ', '.$mdb2->quote($fields['config']);
704     $values .= ', now(), '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', '.$user->id;
705     $values .= ')';
706
707     $sql = 'insert into tt_groups '.$columns.$values;
708     $affected = $mdb2->exec($sql);
709     if (is_a($affected, 'PEAR_Error')) {
710       $this->errors->add($i18n->get('error.db'));
711       return false;
712     }
713
714     $group_id = $mdb2->lastInsertID('tt_groups', 'id');
715     return $group_id;
716   }
717
718   // insertMonthlyQuota - a helper function to insert a monthly quota.
719   private function insertMonthlyQuota($fields) {
720     $mdb2 = getConnection();
721
722     $group_id = (int) $fields['group_id'];
723     $org_id = (int) $fields['org_id'];
724     $year = (int) $fields['year'];
725     $month = (int) $fields['month'];
726     $minutes = (int) $fields['minutes'];
727
728     $sql = "INSERT INTO tt_monthly_quotas (group_id, org_id, year, month, minutes)".
729       " values ($group_id, $org_id, $year, $month, $minutes)";
730     $affected = $mdb2->exec($sql);
731     return (!is_a($affected, 'PEAR_Error'));
732   }
733
734   // insertPredefinedExpense - a helper function to insert a predefined expense.
735   private function insertPredefinedExpense($fields) {
736     $mdb2 = getConnection();
737
738     $group_id = (int) $fields['group_id'];
739     $org_id = (int) $fields['org_id'];
740     $name = $mdb2->quote($fields['name']);
741     $cost = $mdb2->quote($fields['cost']);
742
743     $sql = "INSERT INTO tt_predefined_expenses (group_id, org_id, name, cost)".
744       " values ($group_id, $org_id, $name, $cost)";
745     $affected = $mdb2->exec($sql);
746     return (!is_a($affected, 'PEAR_Error'));
747   }
748
749   // insertExpense - a helper function to insert an expense item.
750   private function insertExpense($fields) {
751     global $user;
752     $mdb2 = getConnection();
753
754     $group_id = (int) $fields['group_id'];
755     $org_id = (int) $fields['org_id'];
756     $date = $fields['date'];
757     $user_id = (int) $fields['user_id'];
758     $client_id = $fields['client_id'];
759     $project_id = $fields['project_id'];
760     $timesheet_id = $fields['timesheet_id'];
761     $name = $fields['name'];
762     $cost = str_replace(',', '.', $fields['cost']);
763     $invoice_id = $fields['invoice_id'];
764     $status = $fields['status'];
765     $approved = (int) $fields['approved'];
766     $paid = (int) $fields['paid'];
767     $created = ', now(), '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', '.$user->id;
768
769     $sql = "insert into tt_expense_items".
770       " (date, user_id, group_id, org_id, client_id, project_id, timesheet_id, name,".
771       " cost, invoice_id, approved, paid, created, created_ip, created_by, status)".
772       " values (".$mdb2->quote($date).", $user_id, $group_id, $org_id, ".$mdb2->quote($client_id).", ".$mdb2->quote($project_id).
773       ", ".$mdb2->quote($timesheet_id).", ".$mdb2->quote($name).", ".$mdb2->quote($cost).", ".$mdb2->quote($invoice_id).
774       ", $approved, $paid $created, ".$mdb2->quote($status).")";
775     $affected = $mdb2->exec($sql);
776     return (!is_a($affected, 'PEAR_Error'));
777   }
778
779   // insertTask function inserts a new task into database.
780   private function insertTask($fields)
781   {
782     $mdb2 = getConnection();
783
784     $group_id = (int) $fields['group_id'];
785     $org_id = (int) $fields['org_id'];
786     $name = $fields['name'];
787     $description = $fields['description'];
788     $projects = $fields['projects'];
789     $status = $fields['status'];
790
791     $sql = "insert into tt_tasks (group_id, org_id, name, description, status)
792       values ($group_id, $org_id, ".$mdb2->quote($name).", ".$mdb2->quote($description).", ".$mdb2->quote($status).")";
793     $affected = $mdb2->exec($sql);
794     $last_id = 0;
795     if (is_a($affected, 'PEAR_Error'))
796       return false;
797
798     $last_id = $mdb2->lastInsertID('tt_tasks', 'id');
799     return $last_id;
800   }
801
802   // insertUserProjectBind - inserts a user to project bind into tt_user_project_binds table.
803   private function insertUserProjectBind($fields) {
804     $mdb2 = getConnection();
805
806     $group_id = (int) $fields['group_id'];
807     $org_id = (int) $fields['org_id'];
808     $user_id = (int) $fields['user_id'];
809     $project_id = (int) $fields['project_id'];
810     $rate = $mdb2->quote($fields['rate']);
811     $status = $mdb2->quote($fields['status']);
812
813     $sql = "insert into tt_user_project_binds (user_id, project_id, group_id, org_id, rate, status)".
814       " values($user_id, $project_id, $group_id, $org_id, $rate, $status)";
815     $affected = $mdb2->exec($sql);
816     return (!is_a($affected, 'PEAR_Error'));
817   }
818
819   // insertUser - inserts a user into database.
820   private function insertUser($fields) {
821     global $user;
822     $mdb2 = getConnection();
823
824     $group_id = (int) $fields['group_id'];
825     $org_id = (int) $fields['org_id'];
826
827     $columns = '(login, password, name, group_id, org_id, role_id, client_id, rate, quota_percent, email, created, created_ip, created_by, status)';
828
829     $values = 'values (';
830     $values .= $mdb2->quote($fields['login']);
831     $values .= ', '.$mdb2->quote($fields['password']);
832     $values .= ', '.$mdb2->quote($fields['name']);
833     $values .= ', '.$group_id;
834     $values .= ', '.$org_id;
835     $values .= ', '.(int)$fields['role_id'];
836     $values .= ', '.$mdb2->quote($fields['client_id']);
837     $values .= ', '.$mdb2->quote($fields['rate']);
838     $values .= ', '.$mdb2->quote($fields['quota_percent']);
839     $values .= ', '.$mdb2->quote($fields['email']);
840     $values .= ', now(), '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', '.$user->id;
841     $values .= ', '.$mdb2->quote($fields['status']);
842     $values .= ')';
843
844     $sql = "insert into tt_users $columns $values";
845     $affected = $mdb2->exec($sql);
846     if (is_a($affected, 'PEAR_Error')) return false;
847
848     $last_id = $mdb2->lastInsertID('tt_users', 'id');
849     return $last_id;
850   }
851
852   // insertProject - a helper function to insert a project as well as project to task binds.
853   private function insertProject($fields)
854   {
855     $mdb2 = getConnection();
856
857     $group_id = (int) $fields['group_id'];
858     $org_id = (int) $fields['org_id'];
859     $name = $fields['name'];
860     $description = $fields['description'];
861     $tasks = $fields['tasks'];
862     $comma_separated = implode(',', $tasks); // This is a comma-separated list of associated task ids.
863     $status = $fields['status'];
864
865     $sql = "insert into tt_projects (group_id, org_id, name, description, tasks, status)
866       values ($group_id, $org_id, ".$mdb2->quote($name).", ".$mdb2->quote($description).", ".$mdb2->quote($comma_separated).", ".$mdb2->quote($status).")";
867     $affected = $mdb2->exec($sql);
868     if (is_a($affected, 'PEAR_Error'))
869       return false;
870
871     $last_id = $mdb2->lastInsertID('tt_projects', 'id');
872
873     // Insert binds into tt_project_task_binds table.
874     if (is_array($tasks)) {
875       foreach ($tasks as $task_id) {
876         $sql = "insert into tt_project_task_binds (project_id, task_id, group_id, org_id)".
877           " values($last_id, $task_id, $group_id, $org_id)";
878         $affected = $mdb2->exec($sql);
879         if (is_a($affected, 'PEAR_Error'))
880           return false;
881       }
882     }
883
884     return $last_id;
885   }
886
887   // insertRole - inserts a role into tt_roles table.
888   private function insertRole($fields)
889   {
890     $mdb2 = getConnection();
891
892     $group_id = (int) $fields['group_id'];
893     $org_id = (int) $fields['org_id'];
894     $name = $fields['name'];
895     $rank = (int) $fields['rank'];
896     $description = $fields['description'];
897     $rights = $fields['rights'];
898     $status = $fields['status'];
899
900     $sql = "insert into tt_roles (group_id, org_id, name, rank, description, rights, status)
901       values ($group_id, $org_id, ".$mdb2->quote($name).", $rank, ".$mdb2->quote($description).", ".$mdb2->quote($rights).", ".$mdb2->quote($status).")";
902     $affected = $mdb2->exec($sql);
903     if (is_a($affected, 'PEAR_Error'))
904       return false;
905
906     $last_id = $mdb2->lastInsertID('tt_roles', 'id');
907     return $last_id;
908   }
909
910   // insertTimesheet - inserts a timesheet in database.
911   private function insertTimesheet($fields)
912   {
913     $mdb2 = getConnection();
914
915     $user_id = (int) $fields['user_id'];
916     $group_id = (int) $fields['group_id'];
917     $org_id = (int) $fields['org_id'];
918     $client_id = $fields['client_id'];
919     $name = $fields['name'];
920     $submit_status = $fields['submit_status'];
921     $submitter_comment = $fields['submitter_comment'];
922     $approval_status = $fields['approval_status'];
923     $manager_comment = $fields['manager_comment'];
924     $status = $fields['status'];
925
926     // Insert a new timesheet record.
927     $sql = "insert into tt_timesheets (user_id, group_id, org_id, client_id, name,".
928       " submit_status, submitter_comment, approval_status, manager_comment, status)".
929       " values($user_id, $group_id, $org_id, ".$mdb2->quote($client_id).", ".$mdb2->quote($name).", ".
930       $mdb2->quote($fields['submit_status']).", ".$mdb2->quote($fields['submiter_comment']).", ".
931       $mdb2->quote($fields['approval_status']).", ".$mdb2->quote($fields['manager_comment']).", ".$mdb2->quote($fields['status']).")";
932     $affected = $mdb2->exec($sql);
933     if (is_a($affected, 'PEAR_Error')) return false;
934
935     $last_id = $mdb2->lastInsertID('tt_timesheets', 'id');
936     return $last_id;
937   }
938
939   // insertInvoice - inserts an invoice in database.
940   private function insertInvoice($fields)
941   {
942     $mdb2 = getConnection();
943
944     $group_id = (int) $fields['group_id'];
945     $org_id = (int) $fields['org_id'];
946     $name = $fields['name'];
947     $client_id = (int) $fields['client_id'];
948     $date = $fields['date'];
949     $status = $fields['status'];
950
951     // Insert a new invoice record.
952     $sql = "insert into tt_invoices (group_id, org_id, name, date, client_id, status)".
953       " values($group_id, $org_id, ".$mdb2->quote($name).", ".$mdb2->quote($date).", $client_id, ".$mdb2->quote($fields['status']).")";
954     $affected = $mdb2->exec($sql);
955     if (is_a($affected, 'PEAR_Error')) return false;
956
957     $last_id = $mdb2->lastInsertID('tt_invoices', 'id');
958     return $last_id;
959   }
960
961   // The insertClient function inserts a new client as well as client to project binds.
962   private function insertClient($fields)
963   {
964     $mdb2 = getConnection();
965
966     $group_id = (int) $fields['group_id'];
967     $org_id = (int) $fields['org_id'];
968     $name = $fields['name'];
969     $address = $fields['address'];
970     $tax = $fields['tax'];
971     $projects = $fields['projects'];
972     if ($projects)
973       $comma_separated = implode(',', $projects); // This is a comma-separated list of associated projects ids.
974     $status = $fields['status'];
975
976     $tax = str_replace(',', '.', $tax);
977     if ($tax == '') $tax = 0;
978
979     $sql = "insert into tt_clients (group_id, org_id, name, address, tax, projects, status)".
980       " values ($group_id, $org_id, ".$mdb2->quote($name).", ".$mdb2->quote($address).", $tax, ".$mdb2->quote($comma_separated).", ".$mdb2->quote($status).")";
981
982     $affected = $mdb2->exec($sql);
983     if (is_a($affected, 'PEAR_Error'))
984       return false;
985
986     $last_id = $mdb2->lastInsertID('tt_clients', 'id');
987
988     if (count($projects) > 0)
989       foreach ($projects as $p_id) {
990         $sql = "insert into tt_client_project_binds (client_id, project_id, group_id, org_id) values($last_id, $p_id, $group_id, $org_id)";
991         $affected = $mdb2->exec($sql);
992         if (is_a($affected, 'PEAR_Error'))
993           return false;
994       }
995
996     return $last_id;
997   }
998
999   // insertFavReport - inserts a favorite report in database.
1000   private function insertFavReport($fields) {
1001     $mdb2 = getConnection();
1002
1003     $group_id = (int) $fields['group_id'];
1004     $org_id = (int) $fields['org_id'];
1005
1006     $sql = "insert into tt_fav_reports".
1007       " (name, user_id, group_id, org_id, client_id, cf_1_option_id, project_id, task_id,".
1008       " billable, approved, invoice, timesheet, paid_status, users, period, period_start, period_end,".
1009       " show_client, show_invoice, show_paid, show_ip,".
1010       " show_project, show_timesheet, show_start, show_duration, show_cost,".
1011       " show_task, show_end, show_note, show_approved, show_custom_field_1, show_work_units,".
1012       " group_by1, group_by2, group_by3, show_totals_only)".
1013       " values(".
1014       $mdb2->quote($fields['name']).", ".$fields['user_id'].", $group_id, $org_id, ".
1015       $mdb2->quote($fields['client']).", ".$mdb2->quote($fields['option']).", ".
1016       $mdb2->quote($fields['project']).", ".$mdb2->quote($fields['task']).", ".
1017       $mdb2->quote($fields['billable']).", ".$mdb2->quote($fields['approved']).", ".
1018       $mdb2->quote($fields['invoice']).", ".$mdb2->quote($fields['timesheet']).", ".
1019       $mdb2->quote($fields['paid_status']).", ".
1020       $mdb2->quote($fields['users']).", ".$mdb2->quote($fields['period']).", ".
1021       $mdb2->quote($fields['from']).", ".$mdb2->quote($fields['to']).", ".
1022       $fields['chclient'].", ".$fields['chinvoice'].", ".$fields['chpaid'].", ".$fields['chip'].", ".
1023       $fields['chproject'].", ".$fields['chtimesheet'].", ".$fields['chstart'].", ".$fields['chduration'].", ".
1024       $fields['chcost'].", ".$fields['chtask'].", ".$fields['chfinish'].", ".$fields['chnote'].", ".
1025       $fields['chapproved'].", ".$fields['chcf_1'].", ".$fields['chunits'].", ".
1026       $mdb2->quote($fields['group_by1']).", ".$mdb2->quote($fields['group_by2']).", ".
1027       $mdb2->quote($fields['group_by3']).", ".$fields['chtotalsonly'].")";
1028     $affected = $mdb2->exec($sql);
1029     if (is_a($affected, 'PEAR_Error'))
1030       return false;
1031
1032     $last_id = $mdb2->lastInsertID('tt_fav_reports', 'id');
1033     return $last_id;
1034   }
1035
1036   // insertNotification function inserts a new notification into database.
1037   private function insertNotification($fields)
1038   {
1039     $mdb2 = getConnection();
1040
1041     $group_id = (int) $fields['group_id'];
1042     $org_id = (int) $fields['org_id'];
1043     $cron_spec = $fields['cron_spec'];
1044     $last = (int) $fields['last'];
1045     $next = (int) $fields['next'];
1046     $report_id = (int) $fields['report_id'];
1047     $email = $fields['email'];
1048     $cc = $fields['cc'];
1049     $subject = $fields['subject'];
1050     $report_condition = $fields['report_condition'];
1051     $status = $fields['status'];
1052
1053     $sql = "insert into tt_cron".
1054       " (group_id, org_id, cron_spec, last, next, report_id, email, cc, subject, report_condition, status)".
1055       " 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).")";
1056     $affected = $mdb2->exec($sql);
1057     return (!is_a($affected, 'PEAR_Error'));
1058   }
1059
1060   // insertUserParam - a helper function to insert a user parameter.
1061   private function insertUserParam($fields) {
1062     $mdb2 = getConnection();
1063
1064     $group_id = (int) $fields['group_id'];
1065     $org_id = (int) $fields['org_id'];
1066     $user_id = (int) $fields['user_id'];
1067     $param_name = $fields['param_name'];
1068     $param_value = $fields['param_value'];
1069
1070     $sql = "insert into tt_config".
1071       " (user_id, group_id, org_id, param_name, param_value)".
1072       " values ($user_id, $group_id, $org_id, ".$mdb2->quote($param_name).", ".$mdb2->quote($param_value).")";
1073     $affected = $mdb2->exec($sql);
1074     return (!is_a($affected, 'PEAR_Error'));
1075   }
1076
1077   // insertCustomField - a helper function to insert a custom field.
1078   private function insertCustomField($fields) {
1079     $mdb2 = getConnection();
1080
1081     $group_id = (int) $fields['group_id'];
1082     $org_id = (int) $fields['org_id'];
1083     $type = (int) $fields['type'];
1084     $label = $fields['label'];
1085     $required = (int) $fields['required'];
1086     $status = $fields['status'];
1087
1088     $sql = "insert into tt_custom_fields".
1089       " (group_id, org_id, type, label, required, status)".
1090       " values($group_id, $org_id, $type, ".$mdb2->quote($label).", $required, ".$mdb2->quote($status).")";
1091     $affected = $mdb2->exec($sql);
1092     if (is_a($affected, 'PEAR_Error'))
1093       return false;
1094
1095     $last_id = $mdb2->lastInsertID('tt_custom_fields', 'id');
1096     return $last_id;
1097   }
1098
1099   // insertCustomFieldOption - a helper function to insert a custom field option.
1100   private function insertCustomFieldOption($fields) {
1101     $mdb2 = getConnection();
1102
1103     $group_id = (int) $fields['group_id'];
1104     $org_id = (int) $fields['org_id'];
1105     $field_id = (int) $fields['field_id'];
1106     $value = $fields['value'];
1107
1108     $sql = "insert into tt_custom_field_options (group_id, org_id, field_id, value)".
1109       " values ($group_id, $org_id, $field_id, ".$mdb2->quote($value).")";
1110     $affected = $mdb2->exec($sql);
1111     if (is_a($affected, 'PEAR_Error'))
1112       return false;
1113
1114     $last_id = $mdb2->lastInsertID('tt_custom_field_options', 'id');
1115     return $last_id;
1116   }
1117
1118   // insertLogEntry - a helper function to insert a time log entry.
1119   private function insertLogEntry($fields) {
1120     global $user;
1121     $mdb2 = getConnection();
1122
1123     $group_id = (int) $fields['group_id'];
1124     $org_id = (int) $fields['org_id'];
1125     $user_id = (int) $fields['user_id'];
1126     $date = $fields['date'];
1127     $start = $fields['start'];
1128     $duration = $fields['duration'];
1129     $client_id = $fields['client_id'];
1130     $project_id = $fields['project_id'];
1131     $task_id = $fields['task_id'];
1132     $timesheet_id = $fields['timesheet_id'];
1133     $invoice_id = $fields['invoice_id'];
1134     $comment = $fields['comment'];
1135     $billable = (int) $fields['billable'];
1136     $approved = (int) $fields['approved'];
1137     $paid = (int) $fields['paid'];
1138     $status = $fields['status'];
1139
1140     $sql = "insert into tt_log".
1141       " (user_id, group_id, org_id, date, start, duration, client_id, project_id, task_id, timesheet_id, invoice_id, comment".
1142       ", billable, approved, paid, created, created_ip, created_by, status)".
1143       " values ($user_id, $group_id, $org_id".
1144       ", ".$mdb2->quote($date).
1145       ", ".$mdb2->quote($start).
1146       ", ".$mdb2->quote($duration).
1147       ", ".$mdb2->quote($client_id).
1148       ", ".$mdb2->quote($project_id).
1149       ", ".$mdb2->quote($task_id).
1150       ", ".$mdb2->quote($timesheet_id).
1151       ", ".$mdb2->quote($invoice_id).
1152       ", ".$mdb2->quote($comment).
1153       ", $billable, $approved, $paid".
1154       ", now(), ".$mdb2->quote($_SERVER['REMOTE_ADDR']).", ".$user->id.
1155       ", ". $mdb2->quote($status).")";
1156     $affected = $mdb2->exec($sql);
1157     if (is_a($affected, 'PEAR_Error')) {
1158       $this->errors->add($i18n->get('error.db')); // TODO: review whether or not to add error here in all insert calls.
1159       return false;
1160     }
1161
1162     $log_id = $mdb2->lastInsertID('tt_log', 'id');
1163     return $log_id;
1164   }
1165
1166   // insertCustomFieldLogEntry - a helper function to insert a custom field log entry.
1167   private function insertCustomFieldLogEntry($fields) {
1168     $mdb2 = getConnection();
1169
1170     $group_id = (int) $fields['group_id'];
1171     $org_id = (int) $fields['org_id'];
1172     $log_id = (int) $fields['log_id'];
1173     $field_id = (int) $fields['field_id'];
1174     $option_id = $fields['option_id'];
1175     $value = $fields['value'];
1176     $status = $fields['status'];
1177
1178     $sql = "insert into tt_custom_field_log (group_id, org_id, log_id, field_id, option_id, value, status)".
1179       " values ($group_id, $org_id, $log_id, $field_id, ".$mdb2->quote($option_id).", ".$mdb2->quote($value).", ".$mdb2->quote($status).")";
1180     $affected = $mdb2->exec($sql);
1181     return (!is_a($affected, 'PEAR_Error'));
1182   }
1183
1184   // getTopRole returns top role id.
1185   private function getTopRole() {
1186     $mdb2 = getConnection();
1187
1188     $sql = "select id from tt_roles where group_id = 0 and rank = ".MAX_RANK." and status = 1";
1189     $res = $mdb2->query($sql);
1190
1191     if (!is_a($res, 'PEAR_Error')) {
1192       $val = $res->fetchRow();
1193       if ($val['id'])
1194         return $val['id'];
1195     }
1196     return false;
1197   }
1198
1199   // The loginExists function detrmines if a login already exists.
1200   private function loginExists($login) {
1201     $mdb2 = getConnection();
1202
1203     $sql = "select id from tt_users where login = ".$mdb2->quote($login)." and (status = 1 or status = 0)";
1204     $res = $mdb2->query($sql);
1205     if (!is_a($res, 'PEAR_Error')) {
1206       if ($val = $res->fetchRow()) {
1207         return true;
1208       }
1209     }
1210     return false;
1211   }
1212 }