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 == 'MONTHLY_QUOTA'
 
  79       || $name == 'LOG_ITEM'
 
  80       || $name == 'CUSTOM_FIELD'
 
  81       || $name == 'CUSTOM_FIELD_OPTION'
 
  82       || $name == 'CUSTOM_FIELD_LOG_ENTRY'
 
  83       || $name == 'INVOICE_HEADER'
 
  84       || $name == 'USER_PROJECT_BIND'
 
  85       || $name == 'EXPENSE_ITEM'
 
  86       || $name == 'FAV_REPORT') {
 
  87       $this->currentElement = $attrs;
 
  89     $this->currentTag = $name;
 
  92   // endElement - callback handler for the closing tag of an XML element.
 
  93   // When we are here, currentElement is an array of the element attributes (as set in startElement).
 
  94   // Here we do the actual import of data into the database.
 
  95   function endElement($parser, $name) {
 
  96     if ($name == 'TEAM') {
 
  97       $this->teamData = $this->currentElement;
 
  98       // Now teamData is an array of team properties. We'll use it later to create a team.
 
  99       // Cannot create the team here. Need to determine whether logins collide with existing logins.
 
 100       $this->currentElement = array();
 
 102     if ($name == 'USER') {
 
 103       $this->users[$this->currentElement['ID']] = $this->currentElement;
 
 104       $this->currentElement = array();
 
 106     if ($name == 'USERS') {
 
 107       foreach ($this->users as $user_item) {
 
 108         if (('' != $user_item['STATUS']) && ttUserHelper::getUserByLogin($user_item['LOGIN'])) {
 
 109           // We have a login collision, cannot import any data.
 
 110           $this->canImport = false;
 
 115       // Now we can create a team.
 
 116       if ($this->canImport) {
 
 117         $team_id = ttTeamHelper::insert(array(
 
 118           'name' => $this->teamData['NAME'],
 
 119           'address' => $this->teamData['ADDRESS'],
 
 120           'currency' => $this->teamData['CURRENCY'],
 
 121           'lock_spec' => $this->teamData['LOCK_SPEC'],
 
 122           'workday_hours' => $this->teamData['WORKDAY_HOURS'],
 
 123           'lang' => $this->teamData['LANG'],
 
 124           'decimal_mark' => $this->teamData['DECIMAL_MARK'],
 
 125           'date_format' => $this->teamData['DATE_FORMAT'],
 
 126           'time_format' => $this->teamData['TIME_FORMAT'],
 
 127           'week_start' => $this->teamData['WEEK_START'],
 
 128           'plugins' => $this->teamData['PLUGINS'],
 
 129           'tracking_mode' => $this->teamData['TRACKING_MODE'],
 
 130           'task_required' => $this->teamData['TASK_REQUIRED'],
 
 131           'record_type' => $this->teamData['RECORD_TYPE']));
 
 133           $this->team_id = $team_id;
 
 134           foreach ($this->users as $key=>$user_item) {
 
 135             $user_id = ttUserHelper::insert(array(
 
 136               'team_id' => $this->team_id,
 
 137               'role' => $user_item['ROLE'],
 
 138               'client_id' => $user_item['CLIENT_ID'], // Note: NOT mapped value, replaced in CLIENT handler.
 
 139               'name' => $user_item['NAME'],
 
 140               'login' => $user_item['LOGIN'],
 
 141               'password' => $user_item['PASSWORD'],
 
 142               'rate' => $user_item['RATE'],
 
 143               'email' => $user_item['EMAIL'],
 
 144               'status' => $user_item['STATUS']), false);
 
 145             $this->userMap[$key] = $user_id;
 
 151     if ($name == 'TASK' && $this->canImport) {
 
 152       $this->taskMap[$this->currentElement['ID']] =
 
 153         ttTaskHelper::insert(array(
 
 154           'team_id' => $this->team_id,
 
 155           'name' => $this->currentElement['NAME'],
 
 156           'description' => $this->currentElement['DESCRIPTION'],
 
 157           'status' => $this->currentElement['STATUS']));
 
 159     if ($name == 'PROJECT' && $this->canImport) {
 
 160       // Prepare a list of task ids.
 
 161       $tasks = explode(',', $this->currentElement['TASKS']);
 
 162       foreach ($tasks as $id)
 
 163         $mapped_tasks[] = $this->taskMap[$id];
 
 165       // Add a new project.
 
 166       $this->projectMap[$this->currentElement['ID']] =
 
 167         ttProjectHelper::insert(array(
 
 168           'team_id' => $this->team_id,
 
 169           'name' => $this->currentElement['NAME'],
 
 170           'description' => $this->currentElement['DESCRIPTION'],
 
 171           'tasks' => $mapped_tasks,
 
 172           'status' => $this->currentElement['STATUS']));
 
 174     if ($name == 'USER_PROJECT_BIND' && $this->canImport) {
 
 175       ttUserHelper::insertBind(
 
 176         $this->userMap[$this->currentElement['USER_ID']],
 
 177         $this->projectMap[$this->currentElement['PROJECT_ID']],
 
 178         $this->currentElement['RATE'],
 
 179         $this->currentElement['STATUS']);
 
 182     if ($name == 'CLIENT' && $this->canImport) {
 
 183       // Prepare a list of project ids.
 
 184       if ($this->currentElement['PROJECTS']) {
 
 185         $projects = explode(',', $this->currentElement['PROJECTS']);
 
 186         foreach ($projects as $id)
 
 187           $mapped_projects[] = $this->projectMap[$id];
 
 190       $this->clientMap[$this->currentElement['ID']] =
 
 191         ttClientHelper::insert(array(
 
 192           'team_id' => $this->team_id,
 
 193           'name' => $this->currentElement['NAME'],
 
 194           'address' => $this->currentElement['ADDRESS'],
 
 195           'tax' => $this->currentElement['TAX'],
 
 196           'projects' => $mapped_projects,
 
 197           'status' => $this->currentElement['STATUS']));
 
 199         // Update client_id for tt_users to a mapped value.
 
 200         // We did not do it during user insertion because clientMap was not ready then.
 
 201         if ($this->currentElement['ID'] != $this->clientMap[$this->currentElement['ID']])
 
 202           ttClientHelper::setMappedClient($this->team_id, $this->currentElement['ID'], $this->clientMap[$this->currentElement['ID']]);
 
 205     if ($name == 'INVOICE' && $this->canImport) {
 
 206       $this->invoiceMap[$this->currentElement['ID']] =
 
 207         ttInvoiceHelper::insert(array(
 
 208           'team_id' => $this->team_id,
 
 209           'name' => $this->currentElement['NAME'],
 
 210           'date' => $this->currentElement['DATE'],
 
 211           'client_id' => $this->clientMap[$this->currentElement['CLIENT_ID']],
 
 212           'discount' => $this->currentElement['DISCOUNT'],
 
 213           'status' => $this->currentElement['STATUS']));
 
 216     if ($name == 'MONTHLY_QUOTA' && $this->canImport) {
 
 217       $this->insertMonthlyQuota($this->team_id, $this->currentElement['YEAR'], $this->currentElement['MONTH'], $this->currentElement['QUOTA']);
 
 220     if ($name == 'LOG_ITEM' && $this->canImport) {
 
 221       $this->logMap[$this->currentElement['ID']] =
 
 222         ttTimeHelper::insert(array(
 
 223           'timestamp' => $this->currentElement['TIMESTAMP'],
 
 224           'user_id' => $this->userMap[$this->currentElement['USER_ID']],
 
 225           'date' => $this->currentElement['DATE'],
 
 226           'start' => $this->currentElement['START'],
 
 227           'finish' => $this->currentElement['FINISH'],
 
 228           'duration' => $this->currentElement['DURATION'],
 
 229           'client' => $this->clientMap[$this->currentElement['CLIENT_ID']],
 
 230           'project' => $this->projectMap[$this->currentElement['PROJECT_ID']],
 
 231           'task' => $this->taskMap[$this->currentElement['TASK_ID']],
 
 232           'invoice' => $this->invoiceMap[$this->currentElement['INVOICE_ID']],
 
 233           'note' => (isset($this->currentElement['COMMENT']) ? $this->currentElement['COMMENT'] : ''),
 
 234           'billable' => $this->currentElement['BILLABLE'],
 
 235           'status' => $this->currentElement['STATUS']));
 
 238     if ($name == 'CUSTOM_FIELD' && $this->canImport) {
 
 239       $this->customFieldMap[$this->currentElement['ID']] =
 
 240         ttCustomFieldHelper::insertField(array(
 
 241           'team_id' => $this->team_id,
 
 242           'type' => $this->currentElement['TYPE'],
 
 243           'label' => $this->currentElement['LABEL'],
 
 244           'required' => $this->currentElement['REQUIRED'],
 
 245           'status' => $this->currentElement['STATUS']));
 
 248     if ($name == 'CUSTOM_FIELD_OPTION' && $this->canImport) {
 
 249       $this->customFieldOptionMap[$this->currentElement['ID']] =
 
 250         ttCustomFieldHelper::insertOption(array(
 
 251           'field_id' => $this->customFieldMap[$this->currentElement['FIELD_ID']],
 
 252           'value' => $this->currentElement['VALUE']));
 
 255     if ($name == 'CUSTOM_FIELD_LOG_ENTRY' && $this->canImport) {
 
 256       ttCustomFieldHelper::insertLogEntry(array(
 
 257         'log_id' => $this->logMap[$this->currentElement['LOG_ID']],
 
 258         'field_id' => $this->customFieldMap[$this->currentElement['FIELD_ID']],
 
 259         'option_id' => $this->customFieldOptionMap[$this->currentElement['OPTION_ID']],
 
 260         'value' => $this->currentElement['VALUE'],
 
 261         'status' => $this->currentElement['STATUS']));
 
 264     if ($name == 'EXPENSE_ITEM' && $this->canImport) {
 
 265       ttExpenseHelper::insert(array(
 
 266         'date' => $this->currentElement['DATE'],
 
 267         'user_id' => $this->userMap[$this->currentElement['USER_ID']],
 
 268         'client_id' => $this->clientMap[$this->currentElement['CLIENT_ID']],
 
 269         'project_id' => $this->projectMap[$this->currentElement['PROJECT_ID']],
 
 270         'name' => $this->currentElement['NAME'],
 
 271         'cost' => $this->currentElement['COST'],
 
 272         'invoice_id' => $this->invoiceMap[$this->currentElement['INVOICE_ID']],
 
 273         'status' => $this->currentElement['STATUS']));
 
 276     if ($name == 'FAV_REPORT' && $this->canImport) {
 
 278       if (strlen($this->currentElement['USERS']) > 0) {
 
 279         $arr = explode(',', $this->currentElement['USERS']);
 
 281           $user_list .= (strlen($user_list) == 0 ? '' : ',').$this->userMap[$v];
 
 283       ttFavReportHelper::insertReport(array(
 
 284         'name' => $this->currentElement['NAME'],
 
 285         'user_id' => $this->userMap[$this->currentElement['USER_ID']],
 
 286         'client' => $this->clientMap[$this->currentElement['CLIENT_ID']],
 
 287         'option' => $this->customFieldOptionMap[$this->currentElement['CF_1_OPTION_ID']],
 
 288         'project' => $this->projectMap[$this->currentElement['PROJECT_ID']],
 
 289         'task' => $this->taskMap[$this->currentElement['TASK_ID']],
 
 290         'billable' => $this->currentElement['BILLABLE'],
 
 291         'users' => $user_list,
 
 292         'period' => $this->currentElement['PERIOD'],
 
 293         'from' => $this->currentElement['PERIOD_START'],
 
 294         'to' => $this->currentElement['PERIOD_END'],
 
 295         'chclient' => $this->currentElement['SHOW_CLIENT'],
 
 296         'chinvoice' => $this->currentElement['SHOW_INVOICE'],
 
 297         'chproject' => $this->currentElement['SHOW_PROJECT'],
 
 298         'chstart' => $this->currentElement['SHOW_START'],
 
 299         'chduration' => $this->currentElement['SHOW_DURATION'],
 
 300         'chcost' => $this->currentElement['SHOW_COST'],
 
 301         'chtask' => $this->currentElement['SHOW_TASK'],
 
 302         'chfinish' => $this->currentElement['SHOW_END'],
 
 303         'chnote' => $this->currentElement['SHOW_NOTE'],
 
 304         'chcf_1' => $this->currentElement['SHOW_CUSTOM_FIELD_1'],
 
 305         'group_by' => $this->currentElement['GROUP_BY'],
 
 306         'chtotalsonly' => $this->currentElement['SHOW_TOTALS_ONLY']));
 
 308     $this->currentTag = '';
 
 311   // dataElement - callback handler for text data fragments. It builds up currentElement array with text pieces from XML.
 
 312   function dataElement($parser, $data) {
 
 313     if ($this->currentTag == 'NAME'
 
 314       || $this->currentTag == 'DESCRIPTION'
 
 315       || $this->currentTag == 'LABEL'
 
 316       || $this->currentTag == 'VALUE'
 
 317       || $this->currentTag == 'COMMENT'
 
 318       || $this->currentTag == 'ADDRESS'
 
 319       || $this->currentTag == 'CLIENT_NAME'
 
 320       || $this->currentTag == 'CLIENT_ADDRESS') {
 
 321       if (isset($this->currentElement[$this->currentTag]))
 
 322         $this->currentElement[$this->currentTag] .= trim($data);
 
 324         $this->currentElement[$this->currentTag] = trim($data);
 
 328   // importXml - uncompresses the file, reads and parses its content. During parsing,
 
 329   // startElement, endElement, and dataElement functions are called as many times as necessary.
 
 330   // Actual import occurs in the endElement handler.
 
 331   function importXml() {
 
 334     // Do we have a compressed file?
 
 336     $file_ext = substr($_FILES['xmlfile']['name'], strrpos($_FILES['xmlfile']['name'], '.') + 1);
 
 337     if (in_array($file_ext, array('bz','tbz','bz2','tbz2'))) {
 
 341     // Create a temporary file.
 
 342     $dirName = dirname(TEMPLATE_DIR . '_c/.');
 
 343     $filename = tempnam($dirName, 'import_');
 
 345     // If the file is compressed - uncompress it.
 
 347       if (!$this->uncompress($_FILES['xmlfile']['tmp_name'], $filename)) {
 
 348         $this->errors->add($i18n->getKey('error.sys'));
 
 351       unlink($_FILES['xmlfile']['tmp_name']);
 
 353       if (!move_uploaded_file($_FILES['xmlfile']['tmp_name'], $filename)) {
 
 354         $this->errors->add($i18n->getKey('error.upload'));
 
 359     // Initialize XML parser.
 
 360     $parser = xml_parser_create();
 
 361     xml_set_object($parser, $this);
 
 362     xml_set_element_handler($parser, 'startElement', 'endElement');
 
 363     xml_set_character_data_handler($parser, 'dataElement');
 
 365     // Read and parse the content of the file. During parsing, startElement, endElement, and dataElement functions are called.
 
 366     $file = fopen($filename, 'r');
 
 367     while ($data = fread($file, 4096)) {
 
 368       if (!xml_parse($parser, $data, feof($file))) {
 
 369         $this->errors->add(sprintf("XML error: %s at line %d",
 
 370           xml_error_string(xml_get_error_code($parser)),
 
 371           xml_get_current_line_number($parser)));
 
 373       if (!$this->canImport) {
 
 374         $this->errors->add($i18n->getKey('error.user_exists'));
 
 378     xml_parser_free($parser);
 
 379     if ($file) fclose($file);
 
 383   // uncompress - uncompresses the content of the $in file into the $out file.
 
 384   function uncompress($in, $out) {
 
 385     // Do we have the uncompress function?
 
 386     if (!function_exists('bzopen'))
 
 389     // Initial checks of file names and permissions.
 
 390     if (!file_exists($in) || !is_readable ($in))
 
 392     if ((!file_exists($out) && !is_writable(dirname($out))) || (file_exists($out) && !is_writable($out)))
 
 395     if (!$out_file = fopen($out, 'wb'))
 
 397     if (!$in_file = bzopen ($in, 'r'))
 
 400     while (!feof($in_file)) {
 
 401       $buffer = bzread($in_file, 4096);
 
 402       fwrite($out_file, $buffer, 4096);
 
 409   // insertMonthlyQuota - a helper function to insert a monthly quota.
 
 410   private function insertMonthlyQuota($team_id, $year, $month, $quota) {
 
 411     $mdb2 = getConnection();
 
 412     $sql = "INSERT INTO tt_monthly_quotas (team_id, year, month, quota) values ($team_id, $year, $month, $quota)";
 
 413     $affected = $mdb2->exec($sql);
 
 414     return (!is_a($affected, 'PEAR_Error'));