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 team 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 $teamData       = array(); // Array of team data such as team name, etc.
 
  50   var $team_id        = null;    // New team 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 == 'TEAM') {
 
 102       $this->teamData = $this->currentElement;
 
 103       // Now teamData is an array of team properties. We'll use it later to create a team.
 
 104       // Cannot create the team 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 team.
 
 125       if ($this->canImport) {
 
 126         $this->top_role_id = ttRoleHelper::getRoleByRank(512, 0);
 
 127         $team_id = ttTeamHelper::insert(array(
 
 128           'name' => $this->teamData['NAME'],
 
 129           'currency' => $this->teamData['CURRENCY'],
 
 130           'decimal_mark' => $this->teamData['DECIMAL_MARK'],
 
 131           'lang' => $this->teamData['LANG'],
 
 132           'date_format' => $this->teamData['DATE_FORMAT'],
 
 133           'time_format' => $this->teamData['TIME_FORMAT'],
 
 134           'week_start' => $this->teamData['WEEK_START'],
 
 135           'tracking_mode' => $this->teamData['TRACKING_MODE'],
 
 136           'project_required' => $this->teamData['PROJECT_REQUIRED'],
 
 137           'task_required' => $this->teamData['TASK_REQUIRED'],
 
 138           'record_type' => $this->teamData['RECORD_TYPE'],
 
 139           'bcc_email' => $this->teamData['BCC_EMAIL'],
 
 140           'plugins' => $this->teamData['PLUGINS'],
 
 141           'lock_spec' => $this->teamData['LOCK_SPEC'],
 
 142           'workday_minutes' => $this->teamData['WORKDAY_MINUTES'],
 
 143           'config' => $this->teamData['CONFIG']));
 
 145           $this->team_id = $team_id;
 
 148           foreach ($this->roles as $key=>$role_item) {
 
 149             $role_id = ttRoleHelper::insert(array(
 
 150               'team_id' => $this->team_id,
 
 151               'name' => $role_item['NAME'],
 
 152               'rank' => $role_item['RANK'],
 
 153               'rights' => $role_item['RIGHTS'],
 
 154               'status' => $role_item['STATUS']));
 
 155             $this->roleMap[$role_item['ID']] = $role_id;
 
 158           foreach ($this->users as $key=>$user_item) {
 
 159             $role_id = $user_item['ROLE_ID'] === '0' ? $this->top_role_id :  $this->roleMap[$user_item['ROLE_ID']]; // 0 (not null) means top manager role.
 
 160             $user_id = ttUserHelper::insert(array(
 
 161               'team_id' => $this->team_id,
 
 162               'role_id' => $role_id,
 
 163               'client_id' => $user_item['CLIENT_ID'], // Note: NOT mapped value, replaced in CLIENT handler.
 
 164               'name' => $user_item['NAME'],
 
 165               'login' => $user_item['LOGIN'],
 
 166               'password' => $user_item['PASSWORD'],
 
 167               'rate' => $user_item['RATE'],
 
 168               'email' => $user_item['EMAIL'],
 
 169               'status' => $user_item['STATUS']), false);
 
 170             $this->userMap[$key] = $user_id;
 
 176     if ($name == 'TASK' && $this->canImport) {
 
 177       $this->taskMap[$this->currentElement['ID']] =
 
 178         ttTaskHelper::insert(array(
 
 179           'team_id' => $this->team_id,
 
 180           'name' => $this->currentElement['NAME'],
 
 181           'description' => $this->currentElement['DESCRIPTION'],
 
 182           'status' => $this->currentElement['STATUS']));
 
 184     if ($name == 'PROJECT' && $this->canImport) {
 
 185       // Prepare a list of task ids.
 
 186       $tasks = explode(',', $this->currentElement['TASKS']);
 
 187       foreach ($tasks as $id)
 
 188         $mapped_tasks[] = $this->taskMap[$id];
 
 190       // Add a new project.
 
 191       $this->projectMap[$this->currentElement['ID']] =
 
 192         ttProjectHelper::insert(array(
 
 193           'team_id' => $this->team_id,
 
 194           'name' => $this->currentElement['NAME'],
 
 195           'description' => $this->currentElement['DESCRIPTION'],
 
 196           'tasks' => $mapped_tasks,
 
 197           'status' => $this->currentElement['STATUS']));
 
 199     if ($name == 'USER_PROJECT_BIND' && $this->canImport) {
 
 200       ttUserHelper::insertBind(
 
 201         $this->userMap[$this->currentElement['USER_ID']],
 
 202         $this->projectMap[$this->currentElement['PROJECT_ID']],
 
 203         $this->currentElement['RATE'],
 
 204         $this->currentElement['STATUS']);
 
 207     if ($name == 'CLIENT' && $this->canImport) {
 
 208       // Prepare a list of project ids.
 
 209       if ($this->currentElement['PROJECTS']) {
 
 210         $projects = explode(',', $this->currentElement['PROJECTS']);
 
 211         foreach ($projects as $id)
 
 212           $mapped_projects[] = $this->projectMap[$id];
 
 215       $this->clientMap[$this->currentElement['ID']] =
 
 216         ttClientHelper::insert(array(
 
 217           'team_id' => $this->team_id,
 
 218           'name' => $this->currentElement['NAME'],
 
 219           'address' => $this->currentElement['ADDRESS'],
 
 220           'tax' => $this->currentElement['TAX'],
 
 221           'projects' => $mapped_projects,
 
 222           'status' => $this->currentElement['STATUS']));
 
 224         // Update client_id for tt_users to a mapped value.
 
 225         // We did not do it during user insertion because clientMap was not ready then.
 
 226         if ($this->currentElement['ID'] != $this->clientMap[$this->currentElement['ID']])
 
 227           ttClientHelper::setMappedClient($this->team_id, $this->currentElement['ID'], $this->clientMap[$this->currentElement['ID']]);
 
 230     if ($name == 'INVOICE' && $this->canImport) {
 
 231       $this->invoiceMap[$this->currentElement['ID']] =
 
 232         ttInvoiceHelper::insert(array(
 
 233           'team_id' => $this->team_id,
 
 234           'name' => $this->currentElement['NAME'],
 
 235           'date' => $this->currentElement['DATE'],
 
 236           'client_id' => $this->clientMap[$this->currentElement['CLIENT_ID']],
 
 237           'discount' => $this->currentElement['DISCOUNT'],
 
 238           'status' => $this->currentElement['STATUS']));
 
 241     if ($name == 'MONTHLY_QUOTA' && $this->canImport) {
 
 242       $this->insertMonthlyQuota($this->team_id, $this->currentElement['YEAR'], $this->currentElement['MONTH'], $this->currentElement['MINUTES']);
 
 245     if ($name == 'LOG_ITEM' && $this->canImport) {
 
 246       $this->logMap[$this->currentElement['ID']] =
 
 247         ttTimeHelper::insert(array(
 
 248           'user_id' => $this->userMap[$this->currentElement['USER_ID']],
 
 249           'date' => $this->currentElement['DATE'],
 
 250           'start' => $this->currentElement['START'],
 
 251           'finish' => $this->currentElement['FINISH'],
 
 252           'duration' => $this->currentElement['DURATION'],
 
 253           'client' => $this->clientMap[$this->currentElement['CLIENT_ID']],
 
 254           'project' => $this->projectMap[$this->currentElement['PROJECT_ID']],
 
 255           'task' => $this->taskMap[$this->currentElement['TASK_ID']],
 
 256           'invoice' => $this->invoiceMap[$this->currentElement['INVOICE_ID']],
 
 257           'note' => (isset($this->currentElement['COMMENT']) ? $this->currentElement['COMMENT'] : ''),
 
 258           'billable' => $this->currentElement['BILLABLE'],
 
 259           'paid' => $this->currentElement['PAID'],
 
 260           'status' => $this->currentElement['STATUS']));
 
 263     if ($name == 'CUSTOM_FIELD' && $this->canImport) {
 
 264       $this->customFieldMap[$this->currentElement['ID']] =
 
 265         ttCustomFieldHelper::insertField(array(
 
 266           'team_id' => $this->team_id,
 
 267           'type' => $this->currentElement['TYPE'],
 
 268           'label' => $this->currentElement['LABEL'],
 
 269           'required' => $this->currentElement['REQUIRED'],
 
 270           'status' => $this->currentElement['STATUS']));
 
 273     if ($name == 'CUSTOM_FIELD_OPTION' && $this->canImport) {
 
 274       $this->customFieldOptionMap[$this->currentElement['ID']] =
 
 275         ttCustomFieldHelper::insertOption(array(
 
 276           'field_id' => $this->customFieldMap[$this->currentElement['FIELD_ID']],
 
 277           'value' => $this->currentElement['VALUE']));
 
 280     if ($name == 'CUSTOM_FIELD_LOG_ENTRY' && $this->canImport) {
 
 281       ttCustomFieldHelper::insertLogEntry(array(
 
 282         'log_id' => $this->logMap[$this->currentElement['LOG_ID']],
 
 283         'field_id' => $this->customFieldMap[$this->currentElement['FIELD_ID']],
 
 284         'option_id' => $this->customFieldOptionMap[$this->currentElement['OPTION_ID']],
 
 285         'value' => $this->currentElement['VALUE'],
 
 286         'status' => $this->currentElement['STATUS']));
 
 289     if ($name == 'EXPENSE_ITEM' && $this->canImport) {
 
 290       ttExpenseHelper::insert(array(
 
 291         'date' => $this->currentElement['DATE'],
 
 292         'user_id' => $this->userMap[$this->currentElement['USER_ID']],
 
 293         'client_id' => $this->clientMap[$this->currentElement['CLIENT_ID']],
 
 294         'project_id' => $this->projectMap[$this->currentElement['PROJECT_ID']],
 
 295         'name' => $this->currentElement['NAME'],
 
 296         'cost' => $this->currentElement['COST'],
 
 297         'invoice_id' => $this->invoiceMap[$this->currentElement['INVOICE_ID']],
 
 298         'paid' => $this->currentElement['PAID'],
 
 299         'status' => $this->currentElement['STATUS']));
 
 302     if ($name == 'FAV_REPORT' && $this->canImport) {
 
 304       if (strlen($this->currentElement['USERS']) > 0) {
 
 305         $arr = explode(',', $this->currentElement['USERS']);
 
 307           $user_list .= (strlen($user_list) == 0 ? '' : ',').$this->userMap[$v];
 
 309       ttFavReportHelper::insertReport(array(
 
 310         'name' => $this->currentElement['NAME'],
 
 311         'user_id' => $this->userMap[$this->currentElement['USER_ID']],
 
 312         'client' => $this->clientMap[$this->currentElement['CLIENT_ID']],
 
 313         'option' => $this->customFieldOptionMap[$this->currentElement['CF_1_OPTION_ID']],
 
 314         'project' => $this->projectMap[$this->currentElement['PROJECT_ID']],
 
 315         'task' => $this->taskMap[$this->currentElement['TASK_ID']],
 
 316         'billable' => $this->currentElement['BILLABLE'],
 
 317         'users' => $user_list,
 
 318         'period' => $this->currentElement['PERIOD'],
 
 319         'from' => $this->currentElement['PERIOD_START'],
 
 320         'to' => $this->currentElement['PERIOD_END'],
 
 321         'chclient' => (int) $this->currentElement['SHOW_CLIENT'],
 
 322         'chinvoice' => (int) $this->currentElement['SHOW_INVOICE'],
 
 323         'chpaid' => (int) $this->currentElement['SHOW_PAID'],
 
 324         'chip' => (int) $this->currentElement['SHOW_IP'],
 
 325         'chproject' => (int) $this->currentElement['SHOW_PROJECT'],
 
 326         'chstart' => (int) $this->currentElement['SHOW_START'],
 
 327         'chduration' => (int) $this->currentElement['SHOW_DURATION'],
 
 328         'chcost' => (int) $this->currentElement['SHOW_COST'],
 
 329         'chtask' => (int) $this->currentElement['SHOW_TASK'],
 
 330         'chfinish' => (int) $this->currentElement['SHOW_END'],
 
 331         'chnote' => (int) $this->currentElement['SHOW_NOTE'],
 
 332         'chcf_1' => (int) $this->currentElement['SHOW_CUSTOM_FIELD_1'],
 
 333         'group_by' => $this->currentElement['GROUP_BY'],
 
 334         'chtotalsonly' => (int) $this->currentElement['SHOW_TOTALS_ONLY']));
 
 336     $this->currentTag = '';
 
 339   // dataElement - callback handler for text data fragments. It builds up currentElement array with text pieces from XML.
 
 340   function dataElement($parser, $data) {
 
 341     if ($this->currentTag == 'NAME'
 
 342       || $this->currentTag == 'DESCRIPTION'
 
 343       || $this->currentTag == 'LABEL'
 
 344       || $this->currentTag == 'VALUE'
 
 345       || $this->currentTag == 'COMMENT'
 
 346       || $this->currentTag == 'ADDRESS') {
 
 347       if (isset($this->currentElement[$this->currentTag]))
 
 348         $this->currentElement[$this->currentTag] .= trim($data);
 
 350         $this->currentElement[$this->currentTag] = trim($data);
 
 354   // importXml - uncompresses the file, reads and parses its content. During parsing,
 
 355   // startElement, endElement, and dataElement functions are called as many times as necessary.
 
 356   // Actual import occurs in the endElement handler.
 
 357   function importXml() {
 
 360     // Do we have a compressed file?
 
 362     $file_ext = substr($_FILES['xmlfile']['name'], strrpos($_FILES['xmlfile']['name'], '.') + 1);
 
 363     if (in_array($file_ext, array('bz','tbz','bz2','tbz2'))) {
 
 367     // Create a temporary file.
 
 368     $dirName = dirname(TEMPLATE_DIR . '_c/.');
 
 369     $filename = tempnam($dirName, 'import_');
 
 371     // If the file is compressed - uncompress it.
 
 373       if (!$this->uncompress($_FILES['xmlfile']['tmp_name'], $filename)) {
 
 374         $this->errors->add($i18n->getKey('error.sys'));
 
 377       unlink($_FILES['xmlfile']['tmp_name']);
 
 379       if (!move_uploaded_file($_FILES['xmlfile']['tmp_name'], $filename)) {
 
 380         $this->errors->add($i18n->getKey('error.upload'));
 
 385     // Initialize XML parser.
 
 386     $parser = xml_parser_create();
 
 387     xml_set_object($parser, $this);
 
 388     xml_set_element_handler($parser, 'startElement', 'endElement');
 
 389     xml_set_character_data_handler($parser, 'dataElement');
 
 391     // Read and parse the content of the file. During parsing, startElement, endElement, and dataElement functions are called.
 
 392     $file = fopen($filename, 'r');
 
 393     while ($data = fread($file, 4096)) {
 
 394       if (!xml_parse($parser, $data, feof($file))) {
 
 395         $this->errors->add(sprintf("XML error: %s at line %d",
 
 396           xml_error_string(xml_get_error_code($parser)),
 
 397           xml_get_current_line_number($parser)));
 
 399       if (!$this->canImport) {
 
 400         $this->errors->add($i18n->getKey('error.user_exists'));
 
 404     xml_parser_free($parser);
 
 405     if ($file) fclose($file);
 
 409   // uncompress - uncompresses the content of the $in file into the $out file.
 
 410   function uncompress($in, $out) {
 
 411     // Do we have the uncompress function?
 
 412     if (!function_exists('bzopen'))
 
 415     // Initial checks of file names and permissions.
 
 416     if (!file_exists($in) || !is_readable ($in))
 
 418     if ((!file_exists($out) && !is_writable(dirname($out))) || (file_exists($out) && !is_writable($out)))
 
 421     if (!$out_file = fopen($out, 'wb'))
 
 423     if (!$in_file = bzopen ($in, 'r'))
 
 426     while (!feof($in_file)) {
 
 427       $buffer = bzread($in_file, 4096);
 
 428       fwrite($out_file, $buffer, 4096);
 
 435   // insertMonthlyQuota - a helper function to insert a monthly quota.
 
 436   private function insertMonthlyQuota($team_id, $year, $month, $minutes) {
 
 437     $mdb2 = getConnection();
 
 438     $sql = "INSERT INTO tt_monthly_quotas (team_id, year, month, minutes) values ($team_id, $year, $month, $minutes)";
 
 439     $affected = $mdb2->exec($sql);
 
 440     return (!is_a($affected, 'PEAR_Error'));