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