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 import('ttTeamHelper');
 
  30 import('ttUserHelper');
 
  31 import('ttProjectHelper');
 
  32 import('ttTaskHelper');
 
  33 import('ttInvoiceHelper');
 
  34 import('ttTimeHelper');
 
  35 import('ttClientHelper');
 
  36 import('ttCustomFieldHelper');
 
  37 import('ttFavReportHelper');
 
  38 import('ttExpenseHelper');
 
  39 import('ttRoleHelper');
 
  41 // ttImportHelper - this class is used to import group data from a file.
 
  42 class ttImportHelper {
 
  43   var $errors         = null;    // Errors go here. Set in constructor by reference.
 
  45   var $currentElement = array(); // Current element of the XML file we are parsing.
 
  46   var $currentTag     = '';      // XML tag of the current element.
 
  48   var $canImport      = true;    // False if we cannot import data due to a login collision.
 
  49   var $groupData      = array(); // Array of group data such as group name, etc.
 
  50   var $group_id       = null;    // New group id we are importing. It is created during the import operation.
 
  51   var $roles          = array(); // Array of arrays of role properties.
 
  52   var $users          = array(); // Array of arrays of user properties.
 
  53   var $top_role_id    = null;    // Top manager role id on the new server.
 
  55   // The following arrays are maps between entity ids in the file versus the database.
 
  56   // In the file they are sequential (1,2,3...) while in the database the entities have different ids.
 
  57   var $roleMap       = array(); // Role ids.
 
  58   var $userMap       = array(); // User ids.
 
  59   var $projectMap    = array(); // Project ids.
 
  60   var $taskMap       = array(); // Task ids.
 
  61   var $clientMap     = array(); // Client ids.
 
  62   var $invoiceMap    = array(); // Invoice ids.
 
  64   var $customFieldMap       = array(); // Custom field ids.
 
  65   var $customFieldOptionMap = array(); // Custop field option ids.
 
  66   var $logMap        = array(); // Time log ids.
 
  69   function ttImportHelper(&$errors) {
 
  70     $this->errors = &$errors;
 
  73   // startElement - callback handler for opening tag of an XML element.
 
  74   // In this function we assign passed in attributes to currentElement.
 
  75   function startElement($parser, $name, $attrs) {
 
  82       || $name == 'MONTHLY_QUOTA'
 
  83       || $name == 'LOG_ITEM'
 
  84       || $name == 'CUSTOM_FIELD'
 
  85       || $name == 'CUSTOM_FIELD_OPTION'
 
  86       || $name == 'CUSTOM_FIELD_LOG_ENTRY'
 
  87       || $name == 'INVOICE_HEADER'
 
  88       || $name == 'USER_PROJECT_BIND'
 
  89       || $name == 'EXPENSE_ITEM'
 
  90       || $name == 'FAV_REPORT'
 
  92       $this->currentElement = $attrs;
 
  94     $this->currentTag = $name;
 
  97   // endElement - callback handler for the closing tag of an XML element.
 
  98   // When we are here, currentElement is an array of the element attributes (as set in startElement).
 
  99   // Here we do the actual import of data into the database.
 
 100   function endElement($parser, $name) {
 
 101     if ($name == 'GROUP') {
 
 102       $this->groupData = $this->currentElement;
 
 103       // Now groupData is an array of group properties. We'll use it later to create a group.
 
 104       // Cannot create the group here. Need to determine whether logins collide with existing logins.
 
 105       $this->currentElement = array();
 
 107     if ($name == 'ROLE') {
 
 108       $this->roles[$this->currentElement['ID']] = $this->currentElement;
 
 109       $this->currentElement = array();
 
 111     if ($name == 'USER') {
 
 112       $this->users[$this->currentElement['ID']] = $this->currentElement;
 
 113       $this->currentElement = array();
 
 115     if ($name == 'USERS') {
 
 116       foreach ($this->users as $user_item) {
 
 117         if (('' != $user_item['STATUS']) && ttUserHelper::getUserByLogin($user_item['LOGIN'])) {
 
 118           // We have a login collision, cannot import any data.
 
 119           $this->canImport = false;
 
 124       // Now we can create a group.
 
 125       if ($this->canImport) {
 
 126         $this->top_role_id = ttRoleHelper::getRoleByRank(512, 0);
 
 127         $group_id = $this->createGroup(array(
 
 128           'name' => $this->groupData['NAME'],
 
 129           'currency' => $this->groupData['CURRENCY'],
 
 130           'decimal_mark' => $this->groupData['DECIMAL_MARK'],
 
 131           'lang' => $this->groupData['LANG'],
 
 132           'date_format' => $this->groupData['DATE_FORMAT'],
 
 133           'time_format' => $this->groupData['TIME_FORMAT'],
 
 134           'week_start' => $this->groupData['WEEK_START'],
 
 135           'tracking_mode' => $this->groupData['TRACKING_MODE'],
 
 136           'project_required' => $this->groupData['PROJECT_REQUIRED'],
 
 137           'task_required' => $this->groupData['TASK_REQUIRED'],
 
 138           'record_type' => $this->groupData['RECORD_TYPE'],
 
 139           'bcc_email' => $this->groupData['BCC_EMAIL'],
 
 140           'allow_ip' => $this->groupData['ALLOW_IP'],
 
 141           'password_complexity' => $this->groupData['PASSWORD_COMPLEXITY'],
 
 142           'plugins' => $this->groupData['PLUGINS'],
 
 143           'lock_spec' => $this->groupData['LOCK_SPEC'],
 
 144           'workday_minutes' => $this->groupData['WORKDAY_MINUTES'],
 
 145           'config' => $this->groupData['CONFIG']));
 
 147           $this->group_id = $group_id;
 
 150           foreach ($this->roles as $key=>$role_item) {
 
 151             $role_id = ttRoleHelper::insert(array(
 
 152               'group_id' => $this->group_id,
 
 153               'name' => $role_item['NAME'],
 
 154               'rank' => $role_item['RANK'],
 
 155               'rights' => $role_item['RIGHTS'],
 
 156               'status' => $role_item['STATUS']));
 
 157             $this->roleMap[$role_item['ID']] = $role_id;
 
 160           foreach ($this->users as $key=>$user_item) {
 
 161             $role_id = $user_item['ROLE_ID'] === '0' ? $this->top_role_id :  $this->roleMap[$user_item['ROLE_ID']]; // 0 (not null) means top manager role.
 
 162             $user_id = ttUserHelper::insert(array(
 
 163               'group_id' => $this->group_id,
 
 164               'role_id' => $role_id,
 
 165               'client_id' => $user_item['CLIENT_ID'], // Note: NOT mapped value, replaced in CLIENT handler.
 
 166               'name' => $user_item['NAME'],
 
 167               'login' => $user_item['LOGIN'],
 
 168               'password' => $user_item['PASSWORD'],
 
 169               'rate' => $user_item['RATE'],
 
 170               'email' => $user_item['EMAIL'],
 
 171               'status' => $user_item['STATUS']), false);
 
 172             $this->userMap[$key] = $user_id;
 
 178     if ($name == 'TASK' && $this->canImport) {
 
 179       $this->taskMap[$this->currentElement['ID']] =
 
 180         ttTaskHelper::insert(array(
 
 181           'group_id' => $this->group_id,
 
 182           'name' => $this->currentElement['NAME'],
 
 183           'description' => $this->currentElement['DESCRIPTION'],
 
 184           'status' => $this->currentElement['STATUS']));
 
 186     if ($name == 'PROJECT' && $this->canImport) {
 
 187       // Prepare a list of task ids.
 
 188       $tasks = explode(',', $this->currentElement['TASKS']);
 
 189       foreach ($tasks as $id)
 
 190         $mapped_tasks[] = $this->taskMap[$id];
 
 192       // Add a new project.
 
 193       $this->projectMap[$this->currentElement['ID']] =
 
 194         ttProjectHelper::insert(array(
 
 195           'group_id' => $this->group_id,
 
 196           'name' => $this->currentElement['NAME'],
 
 197           'description' => $this->currentElement['DESCRIPTION'],
 
 198           'tasks' => $mapped_tasks,
 
 199           'status' => $this->currentElement['STATUS']));
 
 201     if ($name == 'USER_PROJECT_BIND' && $this->canImport) {
 
 202       ttUserHelper::insertBind(
 
 203         $this->userMap[$this->currentElement['USER_ID']],
 
 204         $this->projectMap[$this->currentElement['PROJECT_ID']],
 
 205         $this->currentElement['RATE'],
 
 206         $this->currentElement['STATUS']);
 
 209     if ($name == 'CLIENT' && $this->canImport) {
 
 210       // Prepare a list of project ids.
 
 211       if ($this->currentElement['PROJECTS']) {
 
 212         $projects = explode(',', $this->currentElement['PROJECTS']);
 
 213         foreach ($projects as $id)
 
 214           $mapped_projects[] = $this->projectMap[$id];
 
 217       $this->clientMap[$this->currentElement['ID']] =
 
 218         ttClientHelper::insert(array(
 
 219           'group_id' => $this->group_id,
 
 220           'name' => $this->currentElement['NAME'],
 
 221           'address' => $this->currentElement['ADDRESS'],
 
 222           'tax' => $this->currentElement['TAX'],
 
 223           'projects' => $mapped_projects,
 
 224           'status' => $this->currentElement['STATUS']));
 
 226         // Update client_id for tt_users to a mapped value.
 
 227         // We did not do it during user insertion because clientMap was not ready then.
 
 228         if ($this->currentElement['ID'] != $this->clientMap[$this->currentElement['ID']])
 
 229           ttClientHelper::setMappedClient($this->group_id, $this->currentElement['ID'], $this->clientMap[$this->currentElement['ID']]);
 
 232     if ($name == 'INVOICE' && $this->canImport) {
 
 233       $this->invoiceMap[$this->currentElement['ID']] =
 
 234         ttInvoiceHelper::insert(array(
 
 235           'group_id' => $this->group_id,
 
 236           'name' => $this->currentElement['NAME'],
 
 237           'date' => $this->currentElement['DATE'],
 
 238           'client_id' => $this->clientMap[$this->currentElement['CLIENT_ID']],
 
 239           'discount' => $this->currentElement['DISCOUNT'],
 
 240           'status' => $this->currentElement['STATUS']));
 
 243     if ($name == 'MONTHLY_QUOTA' && $this->canImport) {
 
 244       $this->insertMonthlyQuota($this->group_id, $this->currentElement['YEAR'], $this->currentElement['MONTH'], $this->currentElement['MINUTES']);
 
 247     if ($name == 'LOG_ITEM' && $this->canImport) {
 
 248       $this->logMap[$this->currentElement['ID']] =
 
 249         ttTimeHelper::insert(array(
 
 250           'user_id' => $this->userMap[$this->currentElement['USER_ID']],
 
 251           'group_id' => $this->group_id,
 
 252           'date' => $this->currentElement['DATE'],
 
 253           'start' => $this->currentElement['START'],
 
 254           'finish' => $this->currentElement['FINISH'],
 
 255           'duration' => $this->currentElement['DURATION'],
 
 256           'client' => $this->clientMap[$this->currentElement['CLIENT_ID']],
 
 257           'project' => $this->projectMap[$this->currentElement['PROJECT_ID']],
 
 258           'task' => $this->taskMap[$this->currentElement['TASK_ID']],
 
 259           'invoice' => $this->invoiceMap[$this->currentElement['INVOICE_ID']],
 
 260           'note' => (isset($this->currentElement['COMMENT']) ? $this->currentElement['COMMENT'] : ''),
 
 261           'billable' => $this->currentElement['BILLABLE'],
 
 262           'paid' => $this->currentElement['PAID'],
 
 263           'status' => $this->currentElement['STATUS']));
 
 266     if ($name == 'CUSTOM_FIELD' && $this->canImport) {
 
 267       $this->customFieldMap[$this->currentElement['ID']] =
 
 268         ttCustomFieldHelper::insertField(array(
 
 269           'group_id' => $this->group_id,
 
 270           'type' => $this->currentElement['TYPE'],
 
 271           'label' => $this->currentElement['LABEL'],
 
 272           'required' => $this->currentElement['REQUIRED'],
 
 273           'status' => $this->currentElement['STATUS']));
 
 276     if ($name == 'CUSTOM_FIELD_OPTION' && $this->canImport) {
 
 277       $this->customFieldOptionMap[$this->currentElement['ID']] =
 
 278         ttCustomFieldHelper::insertOption(array(
 
 279           'field_id' => $this->customFieldMap[$this->currentElement['FIELD_ID']],
 
 280           'value' => $this->currentElement['VALUE']));
 
 283     if ($name == 'CUSTOM_FIELD_LOG_ENTRY' && $this->canImport) {
 
 284       ttCustomFieldHelper::insertLogEntry(array(
 
 285         'log_id' => $this->logMap[$this->currentElement['LOG_ID']],
 
 286         'field_id' => $this->customFieldMap[$this->currentElement['FIELD_ID']],
 
 287         'option_id' => $this->customFieldOptionMap[$this->currentElement['OPTION_ID']],
 
 288         'value' => $this->currentElement['VALUE'],
 
 289         'status' => $this->currentElement['STATUS']));
 
 292     if ($name == 'EXPENSE_ITEM' && $this->canImport) {
 
 293       ttExpenseHelper::insert(array(
 
 294         'date' => $this->currentElement['DATE'],
 
 295         'user_id' => $this->userMap[$this->currentElement['USER_ID']],
 
 296         'group_id' => $this->group_id,
 
 297         'client_id' => $this->clientMap[$this->currentElement['CLIENT_ID']],
 
 298         'project_id' => $this->projectMap[$this->currentElement['PROJECT_ID']],
 
 299         'name' => $this->currentElement['NAME'],
 
 300         'cost' => $this->currentElement['COST'],
 
 301         'invoice_id' => $this->invoiceMap[$this->currentElement['INVOICE_ID']],
 
 302         'paid' => $this->currentElement['PAID'],
 
 303         'status' => $this->currentElement['STATUS']));
 
 306     if ($name == 'FAV_REPORT' && $this->canImport) {
 
 308       if (strlen($this->currentElement['USERS']) > 0) {
 
 309         $arr = explode(',', $this->currentElement['USERS']);
 
 311           $user_list .= (strlen($user_list) == 0 ? '' : ',').$this->userMap[$v];
 
 313       ttFavReportHelper::insertReport(array(
 
 314         'name' => $this->currentElement['NAME'],
 
 315         'user_id' => $this->userMap[$this->currentElement['USER_ID']],
 
 316         'client' => $this->clientMap[$this->currentElement['CLIENT_ID']],
 
 317         'option' => $this->customFieldOptionMap[$this->currentElement['CF_1_OPTION_ID']],
 
 318         'project' => $this->projectMap[$this->currentElement['PROJECT_ID']],
 
 319         'task' => $this->taskMap[$this->currentElement['TASK_ID']],
 
 320         'billable' => $this->currentElement['BILLABLE'],
 
 321         'users' => $user_list,
 
 322         'period' => $this->currentElement['PERIOD'],
 
 323         'from' => $this->currentElement['PERIOD_START'],
 
 324         'to' => $this->currentElement['PERIOD_END'],
 
 325         'chclient' => (int) $this->currentElement['SHOW_CLIENT'],
 
 326         'chinvoice' => (int) $this->currentElement['SHOW_INVOICE'],
 
 327         'chpaid' => (int) $this->currentElement['SHOW_PAID'],
 
 328         'chip' => (int) $this->currentElement['SHOW_IP'],
 
 329         'chproject' => (int) $this->currentElement['SHOW_PROJECT'],
 
 330         'chstart' => (int) $this->currentElement['SHOW_START'],
 
 331         'chduration' => (int) $this->currentElement['SHOW_DURATION'],
 
 332         'chcost' => (int) $this->currentElement['SHOW_COST'],
 
 333         'chtask' => (int) $this->currentElement['SHOW_TASK'],
 
 334         'chfinish' => (int) $this->currentElement['SHOW_END'],
 
 335         'chnote' => (int) $this->currentElement['SHOW_NOTE'],
 
 336         'chcf_1' => (int) $this->currentElement['SHOW_CUSTOM_FIELD_1'],
 
 337         'chunits' => (int) $this->currentElement['SHOW_WORK_UNITS'],
 
 338         'group_by1' => $this->currentElement['GROUP_BY1'],
 
 339         'group_by2' => $this->currentElement['GROUP_BY2'],
 
 340         'group_by3' => $this->currentElement['GROUP_BY3'],
 
 341         'chtotalsonly' => (int) $this->currentElement['SHOW_TOTALS_ONLY']));
 
 343     $this->currentTag = '';
 
 346   // dataElement - callback handler for text data fragments. It builds up currentElement array with text pieces from XML.
 
 347   function dataElement($parser, $data) {
 
 348     if ($this->currentTag == 'NAME'
 
 349       || $this->currentTag == 'DESCRIPTION'
 
 350       || $this->currentTag == 'LABEL'
 
 351       || $this->currentTag == 'VALUE'
 
 352       || $this->currentTag == 'COMMENT'
 
 353       || $this->currentTag == 'ADDRESS'
 
 354       || $this->currentTag == 'ALLOW_IP'
 
 355       || $this->currentTag == 'PASSWORD_COMPLEXITY') {
 
 356       if (isset($this->currentElement[$this->currentTag]))
 
 357         $this->currentElement[$this->currentTag] .= trim($data);
 
 359         $this->currentElement[$this->currentTag] = trim($data);
 
 363   // importXml - uncompresses the file, reads and parses its content. During parsing,
 
 364   // startElement, endElement, and dataElement functions are called as many times as necessary.
 
 365   // Actual import occurs in the endElement handler.
 
 366   function importXml() {
 
 369     // Do we have a compressed file?
 
 371     $file_ext = substr($_FILES['xmlfile']['name'], strrpos($_FILES['xmlfile']['name'], '.') + 1);
 
 372     if (in_array($file_ext, array('bz','tbz','bz2','tbz2'))) {
 
 376     // Create a temporary file.
 
 377     $dirName = dirname(TEMPLATE_DIR . '_c/.');
 
 378     $filename = tempnam($dirName, 'import_');
 
 380     // If the file is compressed - uncompress it.
 
 382       if (!$this->uncompress($_FILES['xmlfile']['tmp_name'], $filename)) {
 
 383         $this->errors->add($i18n->get('error.sys'));
 
 386       unlink($_FILES['xmlfile']['tmp_name']);
 
 388       if (!move_uploaded_file($_FILES['xmlfile']['tmp_name'], $filename)) {
 
 389         $this->errors->add($i18n->get('error.upload'));
 
 394     // Initialize XML parser.
 
 395     $parser = xml_parser_create();
 
 396     xml_set_object($parser, $this);
 
 397     xml_set_element_handler($parser, 'startElement', 'endElement');
 
 398     xml_set_character_data_handler($parser, 'dataElement');
 
 400     // Read and parse the content of the file. During parsing, startElement, endElement, and dataElement functions are called.
 
 401     $file = fopen($filename, 'r');
 
 402     while ($data = fread($file, 4096)) {
 
 403       if (!xml_parse($parser, $data, feof($file))) {
 
 404         $this->errors->add(sprintf("XML error: %s at line %d",
 
 405           xml_error_string(xml_get_error_code($parser)),
 
 406           xml_get_current_line_number($parser)));
 
 408       if (!$this->canImport) {
 
 409         $this->errors->add($i18n->get('error.user_exists'));
 
 413     xml_parser_free($parser);
 
 414     if ($file) fclose($file);
 
 418   // uncompress - uncompresses the content of the $in file into the $out file.
 
 419   function uncompress($in, $out) {
 
 420     // Do we have the uncompress function?
 
 421     if (!function_exists('bzopen'))
 
 424     // Initial checks of file names and permissions.
 
 425     if (!file_exists($in) || !is_readable ($in))
 
 427     if ((!file_exists($out) && !is_writable(dirname($out))) || (file_exists($out) && !is_writable($out)))
 
 430     if (!$out_file = fopen($out, 'wb'))
 
 432     if (!$in_file = bzopen ($in, 'r'))
 
 435     while (!feof($in_file)) {
 
 436       $buffer = bzread($in_file, 4096);
 
 437       fwrite($out_file, $buffer, 4096);
 
 444   // createGroup function creates a new group.
 
 445   private function createGroup($fields) {
 
 448     $mdb2 = getConnection();
 
 450     $columns = '(name, currency, decimal_mark, lang, date_format, time_format, week_start, tracking_mode'.
 
 451       ', project_required, task_required, record_type, bcc_email, allow_ip, password_complexity, plugins'.
 
 452       ', lock_spec, workday_minutes, config, created, created_ip, created_by)';
 
 454     $values = ' values ('.$mdb2->quote(trim($fields['name']));
 
 455     $values .= ', '.$mdb2->quote(trim($fields['currency']));
 
 456     $values .= ', '.$mdb2->quote($fields['decimal_mark']);
 
 457     $values .= ', '.$mdb2->quote($fields['lang']);
 
 458     $values .= ', '.$mdb2->quote($fields['date_format']);
 
 459     $values .= ', '.$mdb2->quote($fields['time_format']);
 
 460     $values .= ', '.(int)$fields['week_start'];
 
 461     $values .= ', '.(int)$fields['tracking_mode'];
 
 462     $values .= ', '.(int)$fields['project_required'];
 
 463     $values .= ', '.(int)$fields['task_required'];
 
 464     $values .= ', '.(int)$fields['record_type'];
 
 465     $values .= ', '.$mdb2->quote($fields['bcc_email']);
 
 466     $values .= ', '.$mdb2->quote($fields['allow_ip']);
 
 467     $values .= ', '.$mdb2->quote($fields['password_complexity']);
 
 468     $values .= ', '.$mdb2->quote($fields['plugins']);
 
 469     $values .= ', '.$mdb2->quote($fields['lock_spec']);
 
 470     $values .= ', '.(int)$fields['workday_minutes'];
 
 471     $values .= ', '.$mdb2->quote($fields['config']);
 
 472     $values .= ', now(), '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', '.$mdb2->quote($user->id);
 
 475     $sql = 'insert into tt_groups '.$columns.$values;
 
 476     $affected = $mdb2->exec($sql);
 
 477     if (!is_a($affected, 'PEAR_Error')) {
 
 478       $group_id = $mdb2->lastInsertID('tt_groups', 'id');
 
 484   // insertMonthlyQuota - a helper function to insert a monthly quota.
 
 485   private function insertMonthlyQuota($group_id, $year, $month, $minutes) {
 
 486     $mdb2 = getConnection();
 
 487     $sql = "INSERT INTO tt_monthly_quotas (group_id, year, month, minutes) values ($group_id, $year, $month, $minutes)";
 
 488     $affected = $mdb2->exec($sql);
 
 489     return (!is_a($affected, 'PEAR_Error'));