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.
 
  11 // | There are only two ways to violate the license:
 
  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).
 
  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).
 
  21 // | This license applies to this document only, not any other software
 
  22 // | that it may be combined with.
 
  24 // +----------------------------------------------------------------------+
 
  26 // | https://www.anuko.com/time_tracker/credits.htm
 
  27 // +----------------------------------------------------------------------+
 
  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.
 
  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();
 
  57   function __construct(&$errors) {
 
  58     $this->errors = &$errors;
 
  59     $this->top_role_id = $this->getTopRole();
 
  62   // startElement - callback handler for opening tags in XML.
 
  63   function startElement($parser, $name, $attrs) {
 
  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'));
 
  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.
 
  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();
 
  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']));
 
 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);
 
 132         // Add self to parent stack.
 
 133         array_push($this->parents, $this->current_group_id);
 
 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();
 
 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']));
 
 163           $this->currentGroupRoleMap[$attrs['ID']] = $role_id;
 
 165           $this->errors->add($i18n->get('error.db'));
 
 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']));
 
 180           $this->currentGroupTaskMap[$attrs['ID']] = $task_id;
 
 182           $this->errors->add($i18n->get('error.db'));
 
 187       if ($name == 'PROJECT') {
 
 188         // We get here when processing <project> tags for the current group.
 
 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];
 
 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']));
 
 206           $this->currentGroupProjectMap[$attrs['ID']] = $project_id;
 
 208           $this->errors->add($i18n->get('error.db'));
 
 213       if ($name == 'CLIENT') {
 
 214         // We get here when processing <client> tags for the current group.
 
 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];
 
 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']));
 
 233           $this->currentGroupClientMap[$attrs['ID']] = $client_id;
 
 235           $this->errors->add($i18n->get('error.db'));
 
 240       if ($name == 'USER') {
 
 241         // We get here when processing <user> tags for the current group.
 
 243         $role_id = $attrs['ROLE_ID'] === '0' ? $this->top_role_id :  $this->currentGroupRoleMap[$attrs['ROLE_ID']]; // 0 (not null) means top manager role.
 
 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);
 
 259           $this->currentGroupUserMap[$attrs['ID']] = $user_id;
 
 261           $this->errors->add($i18n->get('error.db'));
 
 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'));
 
 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']));
 
 294           $this->currentGroupTimesheetMap[$attrs['ID']] = $timesheet_id;
 
 296           $this->errors->add($i18n->get('error.db'));
 
 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']));
 
 312           $this->currentGroupInvoiceMap[$attrs['ID']] = $invoice_id;
 
 314           $this->errors->add($i18n->get('error.db'));
 
 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']));
 
 341           $this->currentGroupLogMap[$attrs['ID']] = $log_item_id;
 
 342         } else $this->errors->add($i18n->get('error.db'));
 
 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) {
 
 357           $this->currentGroupCustomFieldMap[$attrs['ID']] = $custom_field_id;
 
 358         } else $this->errors->add($i18n->get('error.db'));
 
 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) {
 
 371           $this->currentGroupCustomFieldOptionMap[$attrs['ID']] = $custom_field_option_id;
 
 372         } else $this->errors->add($i18n->get('error.db'));
 
 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'));
 
 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'));
 
 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'));
 
 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'));
 
 434       if ($name == 'FAV_REPORT') {
 
 436         if (strlen($attrs['USERS']) > 0) {
 
 437           $arr = explode(',', $attrs['USERS']);
 
 439             $user_list .= (strlen($user_list) == 0 ? '' : ',').$this->currentGroupUserMap[$v];
 
 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           'users' => $user_list,
 
 452           'period' => $attrs['PERIOD'],
 
 453           'from' => $attrs['PERIOD_START'],
 
 454           'to' => $attrs['PERIOD_END'],
 
 455           'chclient' => (int) $attrs['SHOW_CLIENT'],
 
 456           'chinvoice' => (int) $attrs['SHOW_INVOICE'],
 
 457           'chpaid' => (int) $attrs['SHOW_PAID'],
 
 458           'chip' => (int) $attrs['SHOW_IP'],
 
 459           'chproject' => (int) $attrs['SHOW_PROJECT'],
 
 460           'chstart' => (int) $attrs['SHOW_START'],
 
 461           'chduration' => (int) $attrs['SHOW_DURATION'],
 
 462           'chcost' => (int) $attrs['SHOW_COST'],
 
 463           'chtask' => (int) $attrs['SHOW_TASK'],
 
 464           'chfinish' => (int) $attrs['SHOW_END'],
 
 465           'chnote' => (int) $attrs['SHOW_NOTE'],
 
 466           'chcf_1' => (int) $attrs['SHOW_CUSTOM_FIELD_1'],
 
 467           'chunits' => (int) $attrs['SHOW_WORK_UNITS'],
 
 468           'group_by1' => $attrs['GROUP_BY1'],
 
 469           'group_by2' => $attrs['GROUP_BY2'],
 
 470           'group_by3' => $attrs['GROUP_BY3'],
 
 471           'chtotalsonly' => (int) $attrs['SHOW_TOTALS_ONLY']));
 
 472         if ($fav_report_id) {
 
 474           $this->currentGroupFavReportMap[$attrs['ID']] = $fav_report_id;
 
 475           } else $this->errors->add($i18n->get('error.db'));
 
 479       if ($name == 'NOTIFICATION') {
 
 480         if (!$this->insertNotification(array(
 
 481           'group_id' => $this->current_group_id,
 
 482           'org_id' => $this->org_id,
 
 483           'cron_spec' => $attrs['CRON_SPEC'],
 
 484           'last' => $attrs['LAST'],
 
 485           'next' => $attrs['NEXT'],
 
 486           'report_id' => $this->currentGroupFavReportMap[$attrs['REPORT_ID']],
 
 487           'email' => $attrs['EMAIL'],
 
 488           'cc' => $attrs['CC'],
 
 489           'subject' => $attrs['SUBJECT'],
 
 490           'report_condition' => $attrs['REPORT_CONDITION'],
 
 491           'status' => $attrs['STATUS']))) {
 
 492           $this->errors->add($i18n->get('error.db'));
 
 497       if ($name == 'USER_PARAM') {
 
 498         if (!$this->insertUserParam(array(
 
 499           'group_id' => $this->current_group_id,
 
 500           'org_id' => $this->org_id,
 
 501           'user_id' => $this->currentGroupUserMap[$attrs['USER_ID']],
 
 502           'param_name' => $attrs['PARAM_NAME'],
 
 503           'param_value' => $attrs['PARAM_VALUE']))) {
 
 504           $this->errors->add($i18n->get('error.db'));
 
 511   // endElement - callback handler for ending tags in XML.
 
 512   // We use this only for process </group> element endings and
 
 513   // set current_group_id to an immediate parent.
 
 514   // This is required to import group hierarchy correctly.
 
 515   function endElement($parser, $name) {
 
 516     // No need to care about first or second pass, as this is used only in second pass.
 
 517     // See 2nd xml_set_element_handler, where this handler is set.
 
 518     if ($name == 'GROUP') {
 
 519       // Remove self from the parent stack.
 
 520       $self = array_pop($this->parents);
 
 521       // Set current group id to an immediate parent.
 
 522       $len = count($this->parents);
 
 523       $this->current_group_id = $len ? $this->parents[$len-1] : null;
 
 527   // importXml - uncompresses the file, reads and parses its content.
 
 528   // It goes through the file 2 times.
 
 530   // During 1st pass, it determines whether we can import data.
 
 531   // In 1st pass, startElement function is called as many times as necessary.
 
 533   // Actual import occurs during 2nd pass.
 
 534   // In 2nd pass, startElement and endElement are called many times.
 
 535   // We only use endElement to finish current group processing.
 
 537   // The above allows us to export/import complex orgs with nested groups,
 
 538   // while by design all data are in attributes of the elements (no CDATA).
 
 540   // There is currently at least one problem with keeping all data in attributes:
 
 541   // a vertical tab character 0xB anywhere breaks parsing, making import impossible.
 
 542   // See https://github.com/sparklemotion/nokogiri/issues/1581 - looks like
 
 543   // an XML standard thing. Apparently, other invalid characters break parsing too.
 
 544   // This problem needs to be addressed at some point but how exactly without
 
 545   // complicating export-import too much with CDATA and dataElement processing?
 
 546   function importXml() {
 
 549     if (!$_FILES['xmlfile']['name']) {
 
 550       $this->errors->add($i18n->get('error.upload'));
 
 551       return; // There is nothing to do if we don't have a file.
 
 554     // Do we have a compressed file?
 
 556     $file_ext = substr($_FILES['xmlfile']['name'], strrpos($_FILES['xmlfile']['name'], '.') + 1);
 
 557     if (in_array($file_ext, array('bz','tbz','bz2','tbz2'))) {
 
 561     // Create a temporary file.
 
 562     $dirName = dirname(TEMPLATE_DIR . '_c/.');
 
 563     $filename = tempnam($dirName, 'import_');
 
 565     // If the file is compressed - uncompress it.
 
 567       if (!$this->uncompress($_FILES['xmlfile']['tmp_name'], $filename)) {
 
 568         $this->errors->add($i18n->get('error.sys'));
 
 571       unlink($_FILES['xmlfile']['tmp_name']);
 
 573       if (!move_uploaded_file($_FILES['xmlfile']['tmp_name'], $filename)) {
 
 574         $this->errors->add($i18n->get('error.upload'));
 
 579     // Initialize XML parser.
 
 580     $parser = xml_parser_create();
 
 581     xml_set_object($parser, $this);
 
 582     xml_set_element_handler($parser, 'startElement', false); // No need to process end tags in 1st pass.
 
 584     // We need to parse the file 2 times:
 
 585     //   1) First pass: determine if import is possible.
 
 586     //   2) Second pass: import data, one tag at a time.
 
 588     // Read and parse the content of the file. During parsing, startElement is called back for each tag.
 
 589     $file = fopen($filename, 'r');
 
 590     while (($data = fread($file, 4096)) && $this->errors->no()) {
 
 591       if (!xml_parse($parser, $data, feof($file))) {
 
 592         $this->errors->add(sprintf($i18n->get('error.xml'),
 
 593           xml_get_current_line_number($parser),
 
 594           xml_error_string(xml_get_error_code($parser))));
 
 597     if ($this->conflicting_logins) {
 
 598       $this->canImport = false;
 
 599       $this->errors->add($i18n->get('error.user_exists'));
 
 600       $this->errors->add(sprintf($i18n->get('error.cannot_import'), $this->conflicting_logins));
 
 602     if (!ttUserHelper::canAdd($this->num_users)) {
 
 603       $this->canImport = false;
 
 604       $this->errors->add($i18n->get('error.user_count'));
 
 607     $this->firstPass = false; // We are done with 1st pass.
 
 608     xml_parser_free($parser);
 
 609     if ($file) fclose($file);
 
 610     if ($this->errors->yes()) {
 
 611       // Remove the file and exit if we have errors.
 
 616     // Now we can do a second pass, where real work is done.
 
 617     $parser = xml_parser_create();
 
 618     xml_set_object($parser, $this);
 
 619     xml_set_element_handler($parser, 'startElement', 'endElement'); // Need to process ending tags too.
 
 621     // Read and parse the content of the file. During parsing, startElement and endElement are called back for each tag.
 
 622     $file = fopen($filename, 'r');
 
 623     while (($data = fread($file, 4096)) && $this->errors->no()) {
 
 624       if (!xml_parse($parser, $data, feof($file))) {
 
 625         $this->errors->add(sprintf($i18n->get('error.xml'),
 
 626           xml_get_current_line_number($parser),
 
 627           xml_error_string(xml_get_error_code($parser))));
 
 630     xml_parser_free($parser);
 
 631     if ($file) fclose($file);
 
 635   // uncompress - uncompresses the content of the $in file into the $out file.
 
 636   function uncompress($in, $out) {
 
 637     // Do we have the uncompress function?
 
 638     if (!function_exists('bzopen'))
 
 641     // Initial checks of file names and permissions.
 
 642     if (!file_exists($in) || !is_readable ($in))
 
 644     if ((!file_exists($out) && !is_writable(dirname($out))) || (file_exists($out) && !is_writable($out)))
 
 647     if (!$out_file = fopen($out, 'wb'))
 
 649     if (!$in_file = bzopen ($in, 'r'))
 
 652     while (!feof($in_file)) {
 
 653       $buffer = bzread($in_file, 4096);
 
 654       fwrite($out_file, $buffer, 4096);
 
 661   // createGroup function creates a new group.
 
 662   private function createGroup($fields) {
 
 665     $mdb2 = getConnection();
 
 667     $columns = '(parent_id, org_id, name, description, currency, decimal_mark, lang, date_format, time_format'.
 
 668       ', week_start, tracking_mode, project_required, task_required, record_type, bcc_email'.
 
 669       ', allow_ip, password_complexity, plugins, lock_spec'.
 
 670       ', workday_minutes, config, created, created_ip, created_by)';
 
 672     $values = ' values (';
 
 673     $values .= $mdb2->quote($fields['parent_id']);
 
 674     $values .= ', '.$mdb2->quote($fields['org_id']);
 
 675     $values .= ', '.$mdb2->quote(trim($fields['name']));
 
 676     $values .= ', '.$mdb2->quote(trim($fields['description']));
 
 677     $values .= ', '.$mdb2->quote(trim($fields['currency']));
 
 678     $values .= ', '.$mdb2->quote($fields['decimal_mark']);
 
 679     $values .= ', '.$mdb2->quote($fields['lang']);
 
 680     $values .= ', '.$mdb2->quote($fields['date_format']);
 
 681     $values .= ', '.$mdb2->quote($fields['time_format']);
 
 682     $values .= ', '.(int)$fields['week_start'];
 
 683     $values .= ', '.(int)$fields['tracking_mode'];
 
 684     $values .= ', '.(int)$fields['project_required'];
 
 685     $values .= ', '.(int)$fields['task_required'];
 
 686     $values .= ', '.(int)$fields['record_type'];
 
 687     $values .= ', '.$mdb2->quote($fields['bcc_email']);
 
 688     $values .= ', '.$mdb2->quote($fields['allow_ip']);
 
 689     $values .= ', '.$mdb2->quote($fields['password_complexity']);
 
 690     $values .= ', '.$mdb2->quote($fields['plugins']);
 
 691     $values .= ', '.$mdb2->quote($fields['lock_spec']);
 
 692     $values .= ', '.(int)$fields['workday_minutes'];
 
 693     $values .= ', '.$mdb2->quote($fields['config']);
 
 694     $values .= ', now(), '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', '.$user->id;
 
 697     $sql = 'insert into tt_groups '.$columns.$values;
 
 698     $affected = $mdb2->exec($sql);
 
 699     if (is_a($affected, 'PEAR_Error')) {
 
 700       $this->errors->add($i18n->get('error.db'));
 
 704     $group_id = $mdb2->lastInsertID('tt_groups', 'id');
 
 708   // insertMonthlyQuota - a helper function to insert a monthly quota.
 
 709   private function insertMonthlyQuota($fields) {
 
 710     $mdb2 = getConnection();
 
 712     $group_id = (int) $fields['group_id'];
 
 713     $org_id = (int) $fields['org_id'];
 
 714     $year = (int) $fields['year'];
 
 715     $month = (int) $fields['month'];
 
 716     $minutes = (int) $fields['minutes'];
 
 718     $sql = "INSERT INTO tt_monthly_quotas (group_id, org_id, year, month, minutes)".
 
 719       " values ($group_id, $org_id, $year, $month, $minutes)";
 
 720     $affected = $mdb2->exec($sql);
 
 721     return (!is_a($affected, 'PEAR_Error'));
 
 724   // insertPredefinedExpense - a helper function to insert a predefined expense.
 
 725   private function insertPredefinedExpense($fields) {
 
 726     $mdb2 = getConnection();
 
 728     $group_id = (int) $fields['group_id'];
 
 729     $org_id = (int) $fields['org_id'];
 
 730     $name = $mdb2->quote($fields['name']);
 
 731     $cost = $mdb2->quote($fields['cost']);
 
 733     $sql = "INSERT INTO tt_predefined_expenses (group_id, org_id, name, cost)".
 
 734       " values ($group_id, $org_id, $name, $cost)";
 
 735     $affected = $mdb2->exec($sql);
 
 736     return (!is_a($affected, 'PEAR_Error'));
 
 739   // insertExpense - a helper function to insert an expense item.
 
 740   private function insertExpense($fields) {
 
 742     $mdb2 = getConnection();
 
 744     $group_id = (int) $fields['group_id'];
 
 745     $org_id = (int) $fields['org_id'];
 
 746     $date = $fields['date'];
 
 747     $user_id = (int) $fields['user_id'];
 
 748     $client_id = $fields['client_id'];
 
 749     $project_id = $fields['project_id'];
 
 750     $timesheet_id = $fields['timesheet_id'];
 
 751     $name = $fields['name'];
 
 752     $cost = str_replace(',', '.', $fields['cost']);
 
 753     $invoice_id = $fields['invoice_id'];
 
 754     $status = $fields['status'];
 
 755     $approved = (int) $fields['approved'];
 
 756     $paid = (int) $fields['paid'];
 
 757     $created = ', now(), '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', '.$user->id;
 
 759     $sql = "insert into tt_expense_items".
 
 760       " (date, user_id, group_id, org_id, client_id, project_id, timesheet_id, name,".
 
 761       " cost, invoice_id, approved, paid, created, created_ip, created_by, status)".
 
 762       " values (".$mdb2->quote($date).", $user_id, $group_id, $org_id, ".$mdb2->quote($client_id).", ".$mdb2->quote($project_id).
 
 763       ", ".$mdb2->quote($timesheet_id).", ".$mdb2->quote($name).", ".$mdb2->quote($cost).", ".$mdb2->quote($invoice_id).
 
 764       ", $approved, $paid $created, ".$mdb2->quote($status).")";
 
 765     $affected = $mdb2->exec($sql);
 
 766     return (!is_a($affected, 'PEAR_Error'));
 
 769   // insertTask function inserts a new task into database.
 
 770   private function insertTask($fields)
 
 772     $mdb2 = getConnection();
 
 774     $group_id = (int) $fields['group_id'];
 
 775     $org_id = (int) $fields['org_id'];
 
 776     $name = $fields['name'];
 
 777     $description = $fields['description'];
 
 778     $projects = $fields['projects'];
 
 779     $status = $fields['status'];
 
 781     $sql = "insert into tt_tasks (group_id, org_id, name, description, status)
 
 782       values ($group_id, $org_id, ".$mdb2->quote($name).", ".$mdb2->quote($description).", ".$mdb2->quote($status).")";
 
 783     $affected = $mdb2->exec($sql);
 
 785     if (is_a($affected, 'PEAR_Error'))
 
 788     $last_id = $mdb2->lastInsertID('tt_tasks', 'id');
 
 792   // insertUserProjectBind - inserts a user to project bind into tt_user_project_binds table.
 
 793   private function insertUserProjectBind($fields) {
 
 794     $mdb2 = getConnection();
 
 796     $group_id = (int) $fields['group_id'];
 
 797     $org_id = (int) $fields['org_id'];
 
 798     $user_id = (int) $fields['user_id'];
 
 799     $project_id = (int) $fields['project_id'];
 
 800     $rate = $mdb2->quote($fields['rate']);
 
 801     $status = $mdb2->quote($fields['status']);
 
 803     $sql = "insert into tt_user_project_binds (user_id, project_id, group_id, org_id, rate, status)".
 
 804       " values($user_id, $project_id, $group_id, $org_id, $rate, $status)";
 
 805     $affected = $mdb2->exec($sql);
 
 806     return (!is_a($affected, 'PEAR_Error'));
 
 809   // insertUser - inserts a user into database.
 
 810   private function insertUser($fields) {
 
 812     $mdb2 = getConnection();
 
 814     $group_id = (int) $fields['group_id'];
 
 815     $org_id = (int) $fields['org_id'];
 
 817     $columns = '(login, password, name, group_id, org_id, role_id, client_id, rate, quota_percent, email, created, created_ip, created_by, status)';
 
 819     $values = 'values (';
 
 820     $values .= $mdb2->quote($fields['login']);
 
 821     $values .= ', '.$mdb2->quote($fields['password']);
 
 822     $values .= ', '.$mdb2->quote($fields['name']);
 
 823     $values .= ', '.$group_id;
 
 824     $values .= ', '.$org_id;
 
 825     $values .= ', '.(int)$fields['role_id'];
 
 826     $values .= ', '.$mdb2->quote($fields['client_id']);
 
 827     $values .= ', '.$mdb2->quote($fields['rate']);
 
 828     $values .= ', '.$mdb2->quote($fields['quota_percent']);
 
 829     $values .= ', '.$mdb2->quote($fields['email']);
 
 830     $values .= ', now(), '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', '.$user->id;
 
 831     $values .= ', '.$mdb2->quote($fields['status']);
 
 834     $sql = "insert into tt_users $columns $values";
 
 835     $affected = $mdb2->exec($sql);
 
 836     if (is_a($affected, 'PEAR_Error')) return false;
 
 838     $last_id = $mdb2->lastInsertID('tt_users', 'id');
 
 842   // insertProject - a helper function to insert a project as well as project to task binds.
 
 843   private function insertProject($fields)
 
 845     $mdb2 = getConnection();
 
 847     $group_id = (int) $fields['group_id'];
 
 848     $org_id = (int) $fields['org_id'];
 
 849     $name = $fields['name'];
 
 850     $description = $fields['description'];
 
 851     $tasks = $fields['tasks'];
 
 852     $comma_separated = implode(',', $tasks); // This is a comma-separated list of associated task ids.
 
 853     $status = $fields['status'];
 
 855     $sql = "insert into tt_projects (group_id, org_id, name, description, tasks, status)
 
 856       values ($group_id, $org_id, ".$mdb2->quote($name).", ".$mdb2->quote($description).", ".$mdb2->quote($comma_separated).", ".$mdb2->quote($status).")";
 
 857     $affected = $mdb2->exec($sql);
 
 858     if (is_a($affected, 'PEAR_Error'))
 
 861     $last_id = $mdb2->lastInsertID('tt_projects', 'id');
 
 863     // Insert binds into tt_project_task_binds table.
 
 864     if (is_array($tasks)) {
 
 865       foreach ($tasks as $task_id) {
 
 866         $sql = "insert into tt_project_task_binds (project_id, task_id, group_id, org_id)".
 
 867           " values($last_id, $task_id, $group_id, $org_id)";
 
 868         $affected = $mdb2->exec($sql);
 
 869         if (is_a($affected, 'PEAR_Error'))
 
 877   // insertRole - inserts a role into tt_roles table.
 
 878   private function insertRole($fields)
 
 880     $mdb2 = getConnection();
 
 882     $group_id = (int) $fields['group_id'];
 
 883     $org_id = (int) $fields['org_id'];
 
 884     $name = $fields['name'];
 
 885     $rank = (int) $fields['rank'];
 
 886     $description = $fields['description'];
 
 887     $rights = $fields['rights'];
 
 888     $status = $fields['status'];
 
 890     $sql = "insert into tt_roles (group_id, org_id, name, rank, description, rights, status)
 
 891       values ($group_id, $org_id, ".$mdb2->quote($name).", $rank, ".$mdb2->quote($description).", ".$mdb2->quote($rights).", ".$mdb2->quote($status).")";
 
 892     $affected = $mdb2->exec($sql);
 
 893     if (is_a($affected, 'PEAR_Error'))
 
 896     $last_id = $mdb2->lastInsertID('tt_roles', 'id');
 
 900   // insertTimesheet - inserts a timesheet in database.
 
 901   private function insertTimesheet($fields)
 
 903     $mdb2 = getConnection();
 
 905     $user_id = (int) $fields['user_id'];
 
 906     $group_id = (int) $fields['group_id'];
 
 907     $org_id = (int) $fields['org_id'];
 
 908     $client_id = $fields['client_id'];
 
 909     $name = $fields['name'];
 
 910     $submit_status = $fields['submit_status'];
 
 911     $submitter_comment = $fields['submitter_comment'];
 
 912     $approval_status = $fields['approval_status'];
 
 913     $manager_comment = $fields['manager_comment'];
 
 914     $status = $fields['status'];
 
 916     // Insert a new timesheet record.
 
 917     $sql = "insert into tt_timesheets (user_id, group_id, org_id, client_id, name,".
 
 918       " submit_status, submitter_comment, approval_status, manager_comment, status)".
 
 919       " values($user_id, $group_id, $org_id, ".$mdb2->quote($client_id).", ".$mdb2->quote($name).", ".
 
 920       $mdb2->quote($fields['submit_status']).", ".$mdb2->quote($fields['submiter_comment']).", ".
 
 921       $mdb2->quote($fields['approval_status']).", ".$mdb2->quote($fields['manager_comment']).", ".$mdb2->quote($fields['status']).")";
 
 922     $affected = $mdb2->exec($sql);
 
 923     if (is_a($affected, 'PEAR_Error')) return false;
 
 925     $last_id = $mdb2->lastInsertID('tt_timesheets', 'id');
 
 929   // insertInvoice - inserts an invoice in database.
 
 930   private function insertInvoice($fields)
 
 932     $mdb2 = getConnection();
 
 934     $group_id = (int) $fields['group_id'];
 
 935     $org_id = (int) $fields['org_id'];
 
 936     $name = $fields['name'];
 
 937     $client_id = (int) $fields['client_id'];
 
 938     $date = $fields['date'];
 
 939     $status = $fields['status'];
 
 941     // Insert a new invoice record.
 
 942     $sql = "insert into tt_invoices (group_id, org_id, name, date, client_id, status)".
 
 943       " values($group_id, $org_id, ".$mdb2->quote($name).", ".$mdb2->quote($date).", $client_id, ".$mdb2->quote($fields['status']).")";
 
 944     $affected = $mdb2->exec($sql);
 
 945     if (is_a($affected, 'PEAR_Error')) return false;
 
 947     $last_id = $mdb2->lastInsertID('tt_invoices', 'id');
 
 951   // The insertClient function inserts a new client as well as client to project binds.
 
 952   private function insertClient($fields)
 
 954     $mdb2 = getConnection();
 
 956     $group_id = (int) $fields['group_id'];
 
 957     $org_id = (int) $fields['org_id'];
 
 958     $name = $fields['name'];
 
 959     $address = $fields['address'];
 
 960     $tax = $fields['tax'];
 
 961     $projects = $fields['projects'];
 
 963       $comma_separated = implode(',', $projects); // This is a comma-separated list of associated projects ids.
 
 964     $status = $fields['status'];
 
 966     $tax = str_replace(',', '.', $tax);
 
 967     if ($tax == '') $tax = 0;
 
 969     $sql = "insert into tt_clients (group_id, org_id, name, address, tax, projects, status)".
 
 970       " values ($group_id, $org_id, ".$mdb2->quote($name).", ".$mdb2->quote($address).", $tax, ".$mdb2->quote($comma_separated).", ".$mdb2->quote($status).")";
 
 972     $affected = $mdb2->exec($sql);
 
 973     if (is_a($affected, 'PEAR_Error'))
 
 976     $last_id = $mdb2->lastInsertID('tt_clients', 'id');
 
 978     if (count($projects) > 0)
 
 979       foreach ($projects as $p_id) {
 
 980         $sql = "insert into tt_client_project_binds (client_id, project_id, group_id, org_id) values($last_id, $p_id, $group_id, $org_id)";
 
 981         $affected = $mdb2->exec($sql);
 
 982         if (is_a($affected, 'PEAR_Error'))
 
 989   // insertFavReport - inserts a favorite report in database.
 
 990   private function insertFavReport($fields) {
 
 991     $mdb2 = getConnection();
 
 993     $group_id = (int) $fields['group_id'];
 
 994     $org_id = (int) $fields['org_id'];
 
 996     $sql = "insert into tt_fav_reports".
 
 997       " (name, user_id, group_id, org_id, client_id, cf_1_option_id, project_id, task_id,".
 
 998       " billable, invoice, paid_status, users, period, period_start, period_end,".
 
 999       " show_client, show_invoice, show_paid, show_ip,".
 
1000       " show_project, show_start, show_duration, show_cost,".
 
1001       " show_task, show_end, show_note, show_custom_field_1, show_work_units,".
 
1002       " group_by1, group_by2, group_by3, show_totals_only)".
 
1004       $mdb2->quote($fields['name']).", ".$fields['user_id'].", $group_id, $org_id, ".
 
1005       $mdb2->quote($fields['client']).", ".$mdb2->quote($fields['option']).", ".
 
1006       $mdb2->quote($fields['project']).", ".$mdb2->quote($fields['task']).", ".
 
1007       $mdb2->quote($fields['billable']).", ".$mdb2->quote($fields['invoice']).", ".
 
1008       $mdb2->quote($fields['paid_status']).", ".
 
1009       $mdb2->quote($fields['users']).", ".$mdb2->quote($fields['period']).", ".
 
1010       $mdb2->quote($fields['from']).", ".$mdb2->quote($fields['to']).", ".
 
1011       $fields['chclient'].", ".$fields['chinvoice'].", ".$fields['chpaid'].", ".$fields['chip'].", ".
 
1012       $fields['chproject'].", ".$fields['chstart'].", ".$fields['chduration'].", ".$fields['chcost'].", ".
 
1013       $fields['chtask'].", ".$fields['chfinish'].", ".$fields['chnote'].", ".$fields['chcf_1'].", ".$fields['chunits'].", ".
 
1014       $mdb2->quote($fields['group_by1']).", ".$mdb2->quote($fields['group_by2']).", ".
 
1015       $mdb2->quote($fields['group_by3']).", ".$fields['chtotalsonly'].")";
 
1016     $affected = $mdb2->exec($sql);
 
1017     if (is_a($affected, 'PEAR_Error'))
 
1020     $last_id = $mdb2->lastInsertID('tt_fav_reports', 'id');
 
1024   // insertNotification function inserts a new notification into database.
 
1025   private function insertNotification($fields)
 
1027     $mdb2 = getConnection();
 
1029     $group_id = (int) $fields['group_id'];
 
1030     $org_id = (int) $fields['org_id'];
 
1031     $cron_spec = $fields['cron_spec'];
 
1032     $last = (int) $fields['last'];
 
1033     $next = (int) $fields['next'];
 
1034     $report_id = (int) $fields['report_id'];
 
1035     $email = $fields['email'];
 
1036     $cc = $fields['cc'];
 
1037     $subject = $fields['subject'];
 
1038     $report_condition = $fields['report_condition'];
 
1039     $status = $fields['status'];
 
1041     $sql = "insert into tt_cron".
 
1042       " (group_id, org_id, cron_spec, last, next, report_id, email, cc, subject, report_condition, status)".
 
1043       " 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).")";
 
1044     $affected = $mdb2->exec($sql);
 
1045     return (!is_a($affected, 'PEAR_Error'));
 
1048   // insertUserParam - a helper function to insert a user parameter.
 
1049   private function insertUserParam($fields) {
 
1050     $mdb2 = getConnection();
 
1052     $group_id = (int) $fields['group_id'];
 
1053     $org_id = (int) $fields['org_id'];
 
1054     $user_id = (int) $fields['user_id'];
 
1055     $param_name = $fields['param_name'];
 
1056     $param_value = $fields['param_value'];
 
1058     $sql = "insert into tt_config".
 
1059       " (user_id, group_id, org_id, param_name, param_value)".
 
1060       " values ($user_id, $group_id, $org_id, ".$mdb2->quote($param_name).", ".$mdb2->quote($param_value).")";
 
1061     $affected = $mdb2->exec($sql);
 
1062     return (!is_a($affected, 'PEAR_Error'));
 
1065   // insertCustomField - a helper function to insert a custom field.
 
1066   private function insertCustomField($fields) {
 
1067     $mdb2 = getConnection();
 
1069     $group_id = (int) $fields['group_id'];
 
1070     $org_id = (int) $fields['org_id'];
 
1071     $type = (int) $fields['type'];
 
1072     $label = $fields['label'];
 
1073     $required = (int) $fields['required'];
 
1074     $status = $fields['status'];
 
1076     $sql = "insert into tt_custom_fields".
 
1077       " (group_id, org_id, type, label, required, status)".
 
1078       " values($group_id, $org_id, $type, ".$mdb2->quote($label).", $required, ".$mdb2->quote($status).")";
 
1079     $affected = $mdb2->exec($sql);
 
1080     if (is_a($affected, 'PEAR_Error'))
 
1083     $last_id = $mdb2->lastInsertID('tt_custom_fields', 'id');
 
1087   // insertCustomFieldOption - a helper function to insert a custom field option.
 
1088   private function insertCustomFieldOption($fields) {
 
1089     $mdb2 = getConnection();
 
1091     $group_id = (int) $fields['group_id'];
 
1092     $org_id = (int) $fields['org_id'];
 
1093     $field_id = (int) $fields['field_id'];
 
1094     $value = $fields['value'];
 
1096     $sql = "insert into tt_custom_field_options (group_id, org_id, field_id, value)".
 
1097       " values ($group_id, $org_id, $field_id, ".$mdb2->quote($value).")";
 
1098     $affected = $mdb2->exec($sql);
 
1099     if (is_a($affected, 'PEAR_Error'))
 
1102     $last_id = $mdb2->lastInsertID('tt_custom_field_options', 'id');
 
1106   // insertLogEntry - a helper function to insert a time log entry.
 
1107   private function insertLogEntry($fields) {
 
1109     $mdb2 = getConnection();
 
1111     $group_id = (int) $fields['group_id'];
 
1112     $org_id = (int) $fields['org_id'];
 
1113     $user_id = (int) $fields['user_id'];
 
1114     $date = $fields['date'];
 
1115     $start = $fields['start'];
 
1116     $duration = $fields['duration'];
 
1117     $client_id = $fields['client_id'];
 
1118     $project_id = $fields['project_id'];
 
1119     $task_id = $fields['task_id'];
 
1120     $timesheet_id = $fields['timesheet_id'];
 
1121     $invoice_id = $fields['invoice_id'];
 
1122     $comment = $fields['comment'];
 
1123     $billable = (int) $fields['billable'];
 
1124     $approved = (int) $fields['approved'];
 
1125     $paid = (int) $fields['paid'];
 
1126     $status = $fields['status'];
 
1128     $sql = "insert into tt_log".
 
1129       " (user_id, group_id, org_id, date, start, duration, client_id, project_id, task_id, timesheet_id, invoice_id, comment".
 
1130       ", billable, approved, paid, created, created_ip, created_by, status)".
 
1131       " values ($user_id, $group_id, $org_id".
 
1132       ", ".$mdb2->quote($date).
 
1133       ", ".$mdb2->quote($start).
 
1134       ", ".$mdb2->quote($duration).
 
1135       ", ".$mdb2->quote($client_id).
 
1136       ", ".$mdb2->quote($project_id).
 
1137       ", ".$mdb2->quote($task_id).
 
1138       ", ".$mdb2->quote($timesheet_id).
 
1139       ", ".$mdb2->quote($invoice_id).
 
1140       ", ".$mdb2->quote($comment).
 
1141       ", $billable, $approved, $paid".
 
1142       ", now(), ".$mdb2->quote($_SERVER['REMOTE_ADDR']).", ".$user->id.
 
1143       ", ". $mdb2->quote($status).")";
 
1144     $affected = $mdb2->exec($sql);
 
1145     if (is_a($affected, 'PEAR_Error')) {
 
1146       $this->errors->add($i18n->get('error.db')); // TODO: review whether or not to add error here in all insert calls.
 
1150     $log_id = $mdb2->lastInsertID('tt_log', 'id');
 
1154   // insertCustomFieldLogEntry - a helper function to insert a custom field log entry.
 
1155   private function insertCustomFieldLogEntry($fields) {
 
1156     $mdb2 = getConnection();
 
1158     $group_id = (int) $fields['group_id'];
 
1159     $org_id = (int) $fields['org_id'];
 
1160     $log_id = (int) $fields['log_id'];
 
1161     $field_id = (int) $fields['field_id'];
 
1162     $option_id = $fields['option_id'];
 
1163     $value = $fields['value'];
 
1164     $status = $fields['status'];
 
1166     $sql = "insert into tt_custom_field_log (group_id, org_id, log_id, field_id, option_id, value, status)".
 
1167       " values ($group_id, $org_id, $log_id, $field_id, ".$mdb2->quote($option_id).", ".$mdb2->quote($value).", ".$mdb2->quote($status).")";
 
1168     $affected = $mdb2->exec($sql);
 
1169     return (!is_a($affected, 'PEAR_Error'));
 
1172   // getTopRole returns top role id.
 
1173   private function getTopRole() {
 
1174     $mdb2 = getConnection();
 
1176     $sql = "select id from tt_roles where group_id = 0 and rank = ".MAX_RANK." and status = 1";
 
1177     $res = $mdb2->query($sql);
 
1179     if (!is_a($res, 'PEAR_Error')) {
 
1180       $val = $res->fetchRow();
 
1187   // The loginExists function detrmines if a login already exists.
 
1188   private function loginExists($login) {
 
1189     $mdb2 = getConnection();
 
1191     $sql = "select id from tt_users where login = ".$mdb2->quote($login)." and (status = 1 or status = 0)";
 
1192     $res = $mdb2->query($sql);
 
1193     if (!is_a($res, 'PEAR_Error')) {
 
1194       if ($val = $res->fetchRow()) {