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');
 
  40 // ttImportHelper - this class is used to import team data from a file.
 
  41 class ttImportHelper {
 
  42   var $errors         = null;    // Errors go here. Set in constructor by reference.
 
  44   var $currentElement = array(); // Current element of the XML file we are parsing.
 
  45   var $currentTag     = '';      // XML tag of the current element.  
 
  47   var $canImport      = true;    // False if we cannot import data due to a login collision.
 
  48   var $teamData       = array(); // Array of team data such as team name, etc.
 
  49   var $team_id        = null;    // New team id we are importing. It is created during the import operation.
 
  50   var $users          = array(); // Array of arrays of user properties.
 
  52   // The following arrays are maps between entity ids in the file versus the database.
 
  53   // In the file they are sequential (1,2,3...) while in the database the entities have different ids.
 
  54   var $userMap       = array(); // User ids.
 
  55   var $projectMap    = array(); // Project ids.
 
  56   var $taskMap       = array(); // Task ids.
 
  57   var $clientMap     = array(); // Client ids.
 
  58   var $invoiceMap    = array(); // Invoice ids.
 
  60   var $customFieldMap       = array(); // Custom field ids.
 
  61   var $customFieldOptionMap = array(); // Custop field option ids.
 
  62   var $logMap        = array(); // Time log ids.
 
  65   function ttImportHelper(&$errors) {
 
  66     $this->errors = &$errors;
 
  69   // startElement - callback handler for opening tag of an XML element.
 
  70   // In this function we assign passed in attributes to currentElement.
 
  71   function startElement($parser, $name, $attrs) {
 
  78           || $name == 'LOG_ITEM'
 
  79           || $name == 'CUSTOM_FIELD'
 
  80           || $name == 'CUSTOM_FIELD_OPTION'
 
  81           || $name == 'CUSTOM_FIELD_LOG_ENTRY'
 
  82           || $name == 'INVOICE_HEADER'
 
  83           || $name == 'USER_PROJECT_BIND'
 
  84           || $name == 'EXPENSE_ITEM'
 
  85           || $name == 'FAV_REPORT') {
 
  86           $this->currentElement = $attrs;
 
  88         $this->currentTag = $name;
 
  91   // endElement - callback handler for the closing tag of an XML element.
 
  92   // When we are here, currentElement is an array of the element attributes (as set in startElement).
 
  93   // Here we do the actual import of data into the database.
 
  94   function endElement($parser, $name)   {
 
  95     if ($name == 'TEAM') {
 
  96       $this->teamData = $this->currentElement;
 
  97       // Now teamData is an array of team properties. We'll use it later to create a team.
 
  98       // Cannot create the team here. Need to determine whether logins collide with existing logins.
 
  99       $this->currentElement = array();
 
 101     if ($name == 'USER') {
 
 102       $this->users[$this->currentElement['ID']] = $this->currentElement;
 
 103       $this->currentElement = array();
 
 105     if ($name == 'USERS') {
 
 106       foreach ($this->users as $user_item) {
 
 107         if (('' != $user_item['STATUS']) && ttUserHelper::getUserByLogin($user_item['LOGIN'])) {
 
 108           // We have a login collision, cannot import any data.
 
 109           $this->canImport = false;
 
 114       // Now we can create a team.
 
 115       if ($this->canImport) {
 
 116         $team_id = ttTeamHelper::insert(array(
 
 117           'name' => $this->teamData['NAME'],
 
 118           'address' => $this->teamData['ADDRESS'],
 
 119           'currency' => $this->teamData['CURRENCY'],
 
 120           'lock_interval' => $this->teamData['LOCK_INTERVAL'],
 
 121           'lang' => $this->teamData['LANG'],
 
 122           'decimal_mark' => $this->teamData['DECIMAL_MARK'],
 
 123           'date_format' => $this->teamData['DATE_FORMAT'],
 
 124           'time_format' => $this->teamData['TIME_FORMAT'],
 
 125           'week_start' => $this->teamData['WEEK_START'],
 
 126           'plugins' => $this->teamData['PLUGINS'],
 
 127           'tracking_mode' => $this->teamData['TRACKING_MODE'],
 
 128           'record_type' => $this->teamData['RECORD_TYPE']));
 
 130           $this->team_id = $team_id;
 
 131           foreach ($this->users as $key=>$user_item) {
 
 132             $user_id = ttUserHelper::insert(array(
 
 133               'team_id' => $this->team_id,
 
 134               'role' => $user_item['ROLE'],
 
 135               'client_id' => $user_item['CLIENT_ID'], // Note: NOT mapped value, replaced in CLIENT handler. 
 
 136               'name' => $user_item['NAME'],
 
 137               'login' => $user_item['LOGIN'],
 
 138               'password' => $user_item['PASSWORD'],
 
 139               'rate' => $user_item['RATE'],
 
 140               'email' => $user_item['EMAIL'],
 
 141               'status' => $user_item['STATUS']), false);
 
 142             $this->userMap[$key] = $user_id;
 
 147         if ($name == 'TASK' && $this->canImport) {
 
 148       $this->taskMap[$this->currentElement['ID']] =
 
 149         ttTaskHelper::insert(array(
 
 150           'team_id' => $this->team_id,
 
 151           'name' => $this->currentElement['NAME'],
 
 152           'description' => $this->currentElement['DESCRIPTION'],
 
 153           'status' => $this->currentElement['STATUS']));
 
 155     if ($name == 'PROJECT' && $this->canImport) {
 
 156       // Prepare a list of task ids.
 
 157       $tasks = explode(',', $this->currentElement['TASKS']);
 
 158       foreach ($tasks as $id)
 
 159         $mapped_tasks[] = $this->taskMap[$id];
 
 161       // Add a new project.
 
 162       $this->projectMap[$this->currentElement['ID']] =
 
 163         ttProjectHelper::insert(array(
 
 164           'team_id' => $this->team_id,
 
 165           'name' => $this->currentElement['NAME'],
 
 166           'description' => $this->currentElement['DESCRIPTION'],
 
 167           'tasks' => $mapped_tasks,
 
 168           'status' => $this->currentElement['STATUS']));
 
 170     if ($name == 'USER_PROJECT_BIND' && $this->canImport) {
 
 171       ttUserHelper::insertBind(
 
 172         $this->userMap[$this->currentElement['USER_ID']],
 
 173         $this->projectMap[$this->currentElement['PROJECT_ID']],
 
 174         $this->currentElement['RATE'],
 
 175         $this->currentElement['STATUS']);
 
 178     if ($name == 'CLIENT' && $this->canImport) {
 
 179       // Prepare a list of project ids.
 
 180       if ($this->currentElement['PROJECTS']) {
 
 181         $projects = explode(',', $this->currentElement['PROJECTS']);
 
 182         foreach ($projects as $id)
 
 183           $mapped_projects[] = $this->projectMap[$id];
 
 186       $this->clientMap[$this->currentElement['ID']] =
 
 187         ttClientHelper::insert(array(
 
 188           'team_id' => $this->team_id,
 
 189           'name' => $this->currentElement['NAME'],
 
 190           'address' => $this->currentElement['ADDRESS'],
 
 191           'tax' => $this->currentElement['TAX'],
 
 192           'projects' => $mapped_projects,
 
 193           'status' => $this->currentElement['STATUS']));
 
 195         // Update client_id for tt_users to a mapped value.
 
 196         // We did not do it during user insertion because clientMap was not ready then.
 
 197         if ($this->currentElement['ID'] != $this->clientMap[$this->currentElement['ID']])
 
 198           ttClientHelper::setMappedClient($this->team_id, $this->currentElement['ID'], $this->clientMap[$this->currentElement['ID']]);
 
 200         if ($name == 'INVOICE' && $this->canImport) {
 
 201       $this->invoiceMap[$this->currentElement['ID']] =
 
 202         ttInvoiceHelper::insert(array(
 
 203           'team_id' => $this->team_id,
 
 204           'name' => $this->currentElement['NAME'],
 
 205           'date' => $this->currentElement['DATE'],
 
 206           'client_id' => $this->clientMap[$this->currentElement['CLIENT_ID']],
 
 207           'discount' => $this->currentElement['DISCOUNT'],
 
 208           'status' => $this->currentElement['STATUS']));
 
 210     if ($name == 'LOG_ITEM' && $this->canImport) {
 
 211       $this->logMap[$this->currentElement['ID']] =
 
 212         ttTimeHelper::insert(array(
 
 213           'timestamp' => $this->currentElement['TIMESTAMP'],
 
 214           'user_id' => $this->userMap[$this->currentElement['USER_ID']],
 
 215           'date' => $this->currentElement['DATE'],
 
 216           'start' => $this->currentElement['START'],
 
 217           'finish' => $this->currentElement['FINISH'],
 
 218           'duration' => $this->currentElement['DURATION'],
 
 219           'client' => $this->clientMap[$this->currentElement['CLIENT_ID']],
 
 220           'project' => $this->projectMap[$this->currentElement['PROJECT_ID']],
 
 221           'task' => $this->taskMap[$this->currentElement['TASK_ID']],
 
 222           'invoice' => $this->invoiceMap[$this->currentElement['INVOICE_ID']],
 
 223           'note' => (isset($this->currentElement['COMMENT']) ? $this->currentElement['COMMENT'] : ''),
 
 224           'billable' => $this->currentElement['BILLABLE'],
 
 225           'status' => $this->currentElement['STATUS']));
 
 227     if ($name == 'CUSTOM_FIELD' && $this->canImport) {
 
 228       $this->customFieldMap[$this->currentElement['ID']] =
 
 229         ttCustomFieldHelper::insertField(array(
 
 230           'team_id' => $this->team_id,
 
 231           'type' => $this->currentElement['TYPE'],
 
 232           'label' => $this->currentElement['LABEL'],
 
 233           'required' => $this->currentElement['REQUIRED'],
 
 234           'status' => $this->currentElement['STATUS']));
 
 236     if ($name == 'CUSTOM_FIELD_OPTION' && $this->canImport) {
 
 237       $this->customFieldOptionMap[$this->currentElement['ID']] =
 
 238         ttCustomFieldHelper::insertOption(array(
 
 239           'field_id' => $this->customFieldMap[$this->currentElement['FIELD_ID']],
 
 240           'value' => $this->currentElement['VALUE']));
 
 242     if ($name == 'CUSTOM_FIELD_LOG_ENTRY' && $this->canImport) {
 
 243       ttCustomFieldHelper::insertLogEntry(array(
 
 244         'log_id' => $this->logMap[$this->currentElement['LOG_ID']],
 
 245         'field_id' => $this->customFieldMap[$this->currentElement['FIELD_ID']],
 
 246         'option_id' => $this->customFieldOptionMap[$this->currentElement['OPTION_ID']],
 
 247         'value' => $this->currentElement['VALUE'],
 
 248         'status' => $this->currentElement['STATUS']));
 
 250     if ($name == 'EXPENSE_ITEM' && $this->canImport) {
 
 251       ttExpenseHelper::insert(array(
 
 252         'date' => $this->currentElement['DATE'],
 
 253         'user_id' => $this->userMap[$this->currentElement['USER_ID']],
 
 254         'client_id' => $this->clientMap[$this->currentElement['CLIENT_ID']],
 
 255         'project_id' => $this->projectMap[$this->currentElement['PROJECT_ID']],
 
 256         'name' => $this->currentElement['NAME'],
 
 257         'cost' => $this->currentElement['COST'],
 
 258         'invoice_id' => $this->invoiceMap[$this->currentElement['INVOICE_ID']],
 
 259         'status' => $this->currentElement['STATUS']));
 
 261     if ($name == 'FAV_REPORT' && $this->canImport) {
 
 263       if (strlen($this->currentElement['USERS']) > 0) {
 
 264         $arr = explode(',', $this->currentElement['USERS']);
 
 266                   $user_list .= (strlen($user_list) == 0 ? '' : ',').$this->userMap[$v];
 
 268       ttFavReportHelper::insertReport(array(
 
 269         'name' => $this->currentElement['NAME'],
 
 270         'user_id' => $this->userMap[$this->currentElement['USER_ID']],
 
 271         'client' => $this->clientMap[$this->currentElement['CLIENT_ID']],
 
 272         'option' => $this->customFieldOptionMap[$this->currentElement['CF_1_OPTION_ID']],
 
 273         'project' => $this->projectMap[$this->currentElement['PROJECT_ID']],
 
 274         'task' => $this->taskMap[$this->currentElement['TASK_ID']],
 
 275         'billable' => $this->currentElement['BILLABLE'],
 
 276         'users' => $user_list,
 
 277         'period' => $this->currentElement['PERIOD'],
 
 278         'from' => $this->currentElement['PERIOD_START'],
 
 279         'to' => $this->currentElement['PERIOD_END'],
 
 280         'chclient' => $this->currentElement['SHOW_CLIENT'],
 
 281         'chinvoice' => $this->currentElement['SHOW_INVOICE'],
 
 282         'chproject' => $this->currentElement['SHOW_PROJECT'],
 
 283         'chstart' => $this->currentElement['SHOW_START'],
 
 284         'chduration' => $this->currentElement['SHOW_DURATION'],
 
 285         'chcost' => $this->currentElement['SHOW_COST'],
 
 286         'chtask' => $this->currentElement['SHOW_TASK'],
 
 287         'chfinish' => $this->currentElement['SHOW_END'],
 
 288         'chnote' => $this->currentElement['SHOW_NOTE'],
 
 289         'chcf_1' => $this->currentElement['SHOW_CUSTOM_FIELD_1'],
 
 290         'group_by' => $this->currentElement['GROUP_BY'],
 
 291         'chtotalsonly' => $this->currentElement['SHOW_TOTALS_ONLY']));
 
 292         //'sortby' => $this->currentElement['SORT_BY'],
 
 293         //'chemptydays' => $this->currentElement['SHOW_EMPTY_DAYS']));
 
 295     $this->currentTag = '';
 
 298   // dataElement - callback handler for text data fragments. It builds up currentElement array with text pieces from XML.
 
 299   function dataElement($parser, $data) {
 
 300     if ($this->currentTag == 'NAME'
 
 301       || $this->currentTag == 'DESCRIPTION'
 
 302       || $this->currentTag == 'LABEL'
 
 303       || $this->currentTag == 'VALUE'
 
 304       || $this->currentTag == 'COMMENT'
 
 305       || $this->currentTag == 'ADDRESS'
 
 306       || $this->currentTag == 'CLIENT_NAME'
 
 307       || $this->currentTag == 'CLIENT_ADDRESS') {
 
 308       if (isset($this->currentElement[$this->currentTag]))
 
 309         $this->currentElement[$this->currentTag] .= trim($data);
 
 311         $this->currentElement[$this->currentTag] = trim($data);
 
 315   // importXml - uncomresses the file, reads and parses its content. During parsing,
 
 316   // startElement, endElement, and dataElement functions are called as many times as necessary.
 
 317   // Actual import occurs in the endElement handler.
 
 318   function importXml() {
 
 319         // Do we have a compressed file?
 
 321         $file_ext = substr($_FILES['xmlfile']['name'], strrpos($_FILES['xmlfile']['name'], '.') + 1);
 
 322     if (in_array($file_ext, array('bz','tbz','bz2','tbz2'))) {
 
 326     // Create a temporary file.
 
 327         $dirName = dirname(TEMPLATE_DIR . '_c/.');
 
 328     $filename = tempnam($dirName, 'import_');
 
 330     // If the file is compressed - uncompress it.
 
 332       if (!$this->uncompress($_FILES['xmlfile']['tmp_name'], $filename)) {
 
 333         $this->errors->add($GLOBALS['I18N']->getKey('error.sys'));
 
 336       unlink($_FILES['xmlfile']['tmp_name']);
 
 338       if (!move_uploaded_file($_FILES['xmlfile']['tmp_name'], $filename)) {
 
 339         $this->errors->add($GLOBALS['I18N']->getKey('error.upload'));
 
 344     // Initialize XML parser.
 
 345     $parser = xml_parser_create();
 
 346     xml_set_object($parser, $this);
 
 347     xml_set_element_handler($parser, 'startElement', 'endElement');
 
 348     xml_set_character_data_handler($parser, 'dataElement');
 
 350     // Read and parse the content of the file. During parsing, startElement, endElement, and dataElement functions are called.
 
 351     $file = fopen($filename, 'r');
 
 352     while ($data = fread($file, 4096)) {
 
 353       if (!xml_parse($parser, $data, feof($file))) {
 
 354         $this->errors->add(sprintf("XML error: %s at line %d",
 
 355           xml_error_string(xml_get_error_code($parser)),
 
 356           xml_get_current_line_number($parser)));
 
 358           if (!$this->canImport) {
 
 359                 $this->errors->add($GLOBALS['I18N']->getKey('error.user_exists'));
 
 363         xml_parser_free($parser);
 
 364         if ($file) fclose($file);
 
 368   // uncompress - uncompresses the content of the $in file into the $out file.
 
 369   function uncompress($in, $out) {
 
 370     // Do we have the uncompress function?
 
 371     if (!function_exists('bzopen'))
 
 374     // Initial checks of file names and permissions.
 
 375     if (!file_exists($in) || !is_readable ($in))
 
 377     if ((!file_exists($out) && !is_writable(dirname($out))) || (file_exists($out) && !is_writable($out)))
 
 380     if (!$out_file = fopen($out, 'wb'))
 
 382     if (!$in_file = bzopen ($in, 'r'))
 
 385     while (!feof($in_file)) {
 
 386       $buffer = bzread($in_file, 4096);
 
 387       fwrite($out_file, $buffer, 4096);