}
     $_REQUEST['save_results'] = $args->save_results;
     list($execSet, $gui->addIssueOp) = write_execution($db, $args, $_REQUEST, $its);
     if ($args->assignTask) {
         $fid = $tplan_mgr->getFeatureID($args->tplan_id, $args->platform_id, $args->version_id);
         $taskMgr = new assignment_mgr($db);
         $taskDomain = $taskMgr->get_available_types();
         $taskStatusDomain = $taskMgr->get_available_status();
         $fmap[$fid]['user_id'] = $fmap[$fid]['assigner_id'] = $args->user_id;
         $fmap[$fid]['build_id'] = $args->build_id;
         $fmap[$fid]['type'] = $taskDomain['testcase_execution']['id'];
         $fmap[$fid]['status'] = $taskStatusDomain['open']['id'];
         $taskMgr->assign($fmap);
     }
     if ($lexid > 0 && $args->copyIssues && $args->level == 'testcase') {
         copyIssues($db, $lexid, $execSet[$args->version_id]);
     }
 }
 // Need to re-read to update test case status
 if ($args->save_and_next || $args->doMoveNext || $args->doMovePrevious) {
     $nextInChain = -1;
     if ($cfg->exec_cfg->exec_mode->save_and_move == 'unlimited') {
         if ($args->caller == 'tcAssignedToMe') {
             $optz = array('order_by' => 'ORDER BY TPTCV.node_order');
             $filters['build_id'] = $args->build_id;
             $xx = $tcase_mgr->get_assigned_to_user($args->user_id, $args->tproject_id, array($args->tplan_id), $optz, $filters);
             $xx = current($xx);
             // key test case id
             // inside an idx array
             $args->testcases_to_show = array_keys($xx);
         }
function saveImportedResultData(&$db, $resultData, $context, $options)
{
    if (!$resultData) {
        return;
    }
    $debugMsg = ' FUNCTION: ' . __FUNCTION__;
    $tables = tlObjectWithDB::getDBTables(array('executions', 'execution_bugs'));
    $tcaseCfg = config_get('testcase_cfg');
    // ---------------------------------------------------------------------------------------
    $l10n = array('import_results_tc_not_found' => '', 'import_results_invalid_result' => '', 'tproject_id_not_found' => '', 'import_results_ok' => '', 'invalid_cf' => '', 'import_results_skipped' => '');
    foreach ($l10n as $key => $value) {
        $l10n[$key] = lang_get($key);
    }
    $resultsCfg = config_get('results');
    foreach ($resultsCfg['status_label'] as $ks => $lbl) {
        $key = $resultsCfg['status_code'][$ks];
        $l10n[$key] = lang_get($lbl);
    }
    // ---------------------------------------------------------------------------------------
    // Get Column definitions to get size dinamically instead of create constants
    $columnDef = array();
    $adodbObj = $db->get_dbmgr_object();
    $columnDef['execution_bugs'] = $adodbObj->MetaColumns($tables['execution_bugs']);
    $keySet = array_keys($columnDef['execution_bugs']);
    foreach ($keySet as $keyName) {
        if (($keylow = strtolower($keyName)) != $keyName) {
            $columnDef['execution_bugs'][$keylow] = $columnDef['execution_bugs'][$keyName];
            unset($columnDef['execution_bugs'][$keyName]);
        }
    }
    $user = new tlUser($context->userID);
    $user->readFromDB($db);
    $tcase_mgr = new testcase($db);
    $resultMap = array();
    $tplan_mgr = null;
    $tc_qty = sizeof($resultData);
    if ($tc_qty) {
        $tplan_mgr = new testplan($db);
        $tproject_mgr = new testproject($db);
        $build_mgr = new build_mgr($db);
    }
    // Need to do checks on common settings
    //
    // test project exists
    //
    // test plan id:
    //              belongs to target test project
    //              is active
    // build id:
    //          belongs to target test plan
    //          is open
    //
    // platform id:
    //          is linked  to target test plan
    //
    // execution type if not present -> set to MANUAL
    //          if presente is valid i.e. inside the TL domain
    //
    $checks = array();
    $checks['status_ok'] = true;
    $checks['msg'] = null;
    $dummy = null;
    if (!is_null($context->tprojectID) && intval($context->tprojectID) > 0) {
        $dummy = array($tproject_mgr->get_by_id($context->tprojectID, array('output' => 'existsByID')));
    } else {
        if (!is_null($context->tprojectName)) {
            $dummy = $tproject_mgr->get_by_name($context->tprojectName, null, array('output' => 'existsByName'));
        }
    }
    $checks['status_ok'] = !is_null($dummy);
    if (!$checks['status_ok']) {
        $checks['msg'][] = sprintf($l10n['tproject_id_not_found'], $context->tprojectID);
    }
    if (!$checks['status_ok']) {
        foreach ($checks['msg'] as $warning) {
            $resultMap[] = array($warning);
        }
    }
    if ($doIt = $checks['status_ok']) {
        $context->tprojectID = $dummy[0]['id'];
    }
    // --------------------------------------------------------------------
    $dummy = null;
    if (!is_null($context->tplanID) && intval($context->tplanID) > 0) {
        $dummy = $tplan_mgr->get_by_id($context->tplanID, array('output' => 'minimun'));
        if (!is_null($dummy)) {
            $dummy['id'] = $context->tplanID;
        }
    } else {
        if (!is_null($context->tplanName)) {
            $dummy = $tplan_mgr->get_by_name($context->tplanName, $context->tprojectID, array('output' => 'minimun'));
            if (!is_null($dummy)) {
                $dummy = $dummy[0];
            }
        }
    }
    if (!is_null($dummy)) {
        $context->tplanID = $dummy['id'];
    }
    if (intval($context->tprojectID) <= 0 && intval($context->tplanID) > 0) {
        $dummy = $tplan_mgr->tree_manager->get_node_hierarchy_info($context->tplanID);
        $context->tprojectID = $dummy['parent_id'];
    }
    // --------------------------------------------------------------------
    // --------------------------------------------------------------------
    $dummy = null;
    $tplan_mgr->platform_mgr->setTestProjectID($context->tprojectID);
    if (!is_null($context->platformID) && intval($context->platformID) > 0) {
        $dummy = array($tplan_mgr->platform_mgr->getByID($context->platformID));
    } else {
        if (property_exists($context, 'platformName') && !is_null($context->platformName)) {
            if (!is_null($xx = $tplan_mgr->platform_mgr->getID($context->platformName))) {
                $dummy = array(0 => array('id' => $xx));
            }
        }
    }
    if (!is_null($dummy)) {
        $context->platformID = $dummy[0]['id'];
    }
    // --------------------------------------------------------------------
    // --------------------------------------------------------------------
    $optGB = array('tplan_id' => $context->tplanID, 'output' => 'minimun');
    $dummy = null;
    if (!is_null($context->buildID) && intval($context->buildID) > 0) {
        $dummy = array($build_mgr->get_by_id($context->buildID, $optGB));
    } else {
        if (!is_null($context->buildName)) {
            $dummy = $build_mgr->get_by_name($context->buildName, $optGB);
        }
    }
    if (!is_null($dummy)) {
        $context->buildID = $dummy[0]['id'];
    }
    // --------------------------------------------------------------------
    // --------------------------------------------------------------------
    for ($idx = 0; $doIt && $idx < $tc_qty; $idx++) {
        $tester_id = 0;
        $tester_name = '';
        $using_external_id = false;
        $message = null;
        $status_ok = true;
        $tcase_exec = $resultData[$idx];
        // New attribute "execution type" makes old XML import files incompatible
        // Important NOTICE:
        // tcase_exec is passed BY REFERENCE to allow check_exec_values()change execution type if needed
        //
        $checks = check_exec_values($db, $tcase_mgr, $user_mgr, $tcaseCfg, $tcase_exec, $columnDef['execution_bugs']);
        $status_ok = $checks['status_ok'];
        if ($status_ok) {
            $tcase_id = $checks['tcase_id'];
            $tcase_external_id = trim($tcase_exec['tcase_external_id']);
            $tester_id = $checks['tester_id'];
            // external_id has precedence over internal id
            $using_external_id = $tcase_external_id != "";
        } else {
            foreach ($checks['msg'] as $warning) {
                $resultMap[] = array($warning);
            }
        }
        if ($status_ok) {
            $tcase_identity = $using_external_id ? $tcase_external_id : $tcase_id;
            $result_code = strtolower($tcase_exec['result']);
            $result_is_acceptable = isset($resultsCfg['code_status'][$result_code]) ? true : false;
            $notes = $tcase_exec['notes'];
            $message = null;
            $info_on_case = $tplan_mgr->getLinkInfo($context->tplanID, $tcase_id, $context->platformID);
            if (is_null($info_on_case)) {
                $message = sprintf($l10n['import_results_tc_not_found'], $tcase_identity);
            } else {
                if (!$result_is_acceptable) {
                    $message = sprintf($l10n['import_results_invalid_result'], $tcase_identity, $tcase_exec['result']);
                } else {
                    $info_on_case = current($info_on_case);
                    $tcversion_id = $info_on_case['tcversion_id'];
                    $version = $info_on_case['version'];
                    $notes = $db->prepare_string(trim($notes));
                    // N.B.: db_now() returns an string ready to be used in an SQL insert
                    //       example '2008-09-04', while $tcase_exec["timestamp"] => 2008-09-04
                    //
                    $execution_ts = $tcase_exec['timestamp'] != '' ? "'" . $tcase_exec["timestamp"] . "'" : $db->db_now();
                    if ($tester_id != 0) {
                        $tester_name = $tcase_exec['tester'];
                    } else {
                        $tester_name = $user->login;
                        $tester_id = $context->userID;
                    }
                    $addExecDuration = strlen($tcase_exec['execution_duration']) > 0 && is_numeric($tcase_exec['execution_duration']);
                    $lexid = 0;
                    if ($options->copyIssues) {
                        $lexid = $tcase_mgr->getSystemWideLastestExecutionID($tcversion_id);
                    }
                    $idCard = array('id' => $tcase_id, 'version_id' => $tcversion_id);
                    $exco = array('tplan_id' => $context->tplanID, 'platform_id' => $context->platformID, 'build_id' => $context->buildID);
                    $lexInfo = $tcase_mgr->getLatestExecSingleContext($idCard, $exco, array('output' => 'timestamp'));
                    $doInsert = true;
                    if (!is_null($lexInfo)) {
                        $tts = $lexInfo[$tcase_id][0]['execution_ts'];
                        $doInsert = $lexInfo[$tcase_id][0]['execution_ts'] != trim($execution_ts, "'");
                        $msgTxt = $l10n['import_results_skipped'];
                    }
                    if ($doInsert) {
                        $sql = " /* {$debugMsg} */ " . " INSERT INTO {$tables['executions']} (build_id,tester_id,status,testplan_id," . " tcversion_id,execution_ts,notes,tcversion_number,platform_id,execution_type" . ($addExecDuration ? ',execution_duration' : '') . ")" . " VALUES ({$context->buildID}, {$tester_id},'{$result_code}',{$context->tplanID}, " . " {$tcversion_id},{$execution_ts},'{$notes}', {$version}, " . " {$context->platformID}, {$tcase_exec['execution_type']}" . ($addExecDuration ? ",{$tcase_exec['execution_duration']}" : '') . ")";
                        $db->exec_query($sql);
                        $execution_id = $db->insert_id($tables['executions']);
                        // 20150127
                        /*
                        if(isset($tcase_exec['steps']) && !is_null($tcase_exec['steps']))
                        {
                          $stepSet = $tcase_mgr->getStepsSimple($tcversion_id,0,
                                                                array('fields2get' => 'TCSTEPS.step_number,TCSTEPS.id',
                                                                      'accessKey' => 'step_number'));
                          $sc = count($tcase_exec['steps']);
                          for($sx=0; $sx < $sc; $sx++)
                          {
                            $snum = $$tcase_exec['steps'][$sx];
                            // assumption: all data is valid
                            if(isset($stepSet[$snum]))
                            {
                              
                            }  
                          }  
                        }  
                        new dBug($tcase_exec);
                        die();
                        */
                        if ($lexid > 0 && $options->copyIssues) {
                            copyIssues($db, $lexid, $execution_id);
                        }
                        if (isset($tcase_exec['bug_id']) && !is_null($tcase_exec['bug_id']) && is_array($tcase_exec['bug_id'])) {
                            foreach ($tcase_exec['bug_id'] as $bug_id) {
                                $bug_id = trim($bug_id);
                                $sql = " /* {$debugMsg} */ " . " SELECT execution_id AS check_qty FROM  {$tables['execution_bugs']} " . " WHERE bug_id = '{$bug_id}' AND execution_id={$execution_id} ";
                                $rs = $db->get_recordset($sql);
                                if (is_null($rs)) {
                                    $sql = " /* {$debugMsg} */ " . " INSERT INTO {$tables['execution_bugs']} (bug_id,execution_id)" . " VALUES ('" . $db->prepare_string($bug_id) . "', {$execution_id} )";
                                    $db->exec_query($sql);
                                }
                            }
                        }
                        if (isset($tcase_exec['custom_fields']) && !is_null($tcase_exec['custom_fields']) && is_array($tcase_exec['custom_fields'])) {
                            // Get linked custom fields to this test project, for test case on execution
                            // $context->tprojectID
                            $cfieldMgr = new cfield_mgr($db);
                            $cfSetByName = $cfieldMgr->get_linked_cfields_at_execution($context->tprojectID, 1, 'testcase', null, null, null, 'name');
                            foreach ($tcase_exec['custom_fields'] as $cf) {
                                $ak = null;
                                if (isset($cfSetByName[$cf['name']])) {
                                    // write to db blind
                                    $ak[$cfSetByName[$cf['name']]['id']]['cf_value'] = $cf['value'];
                                } else {
                                    $message = sprintf($l10n['invalid_cf'], $tcase_identity, $cf['name']);
                                }
                                if (!is_null($ak)) {
                                    $cfieldMgr->execution_values_to_db($ak, $tcversion_id, $execution_id, $context->tplanID, null, 'plain');
                                }
                            }
                        }
                        if (!is_null($message)) {
                            $resultMap[] = array($message);
                        }
                        $msgTxt = $l10n['import_results_ok'];
                    }
                    $message = sprintf($msgTxt, $tcase_identity, $version, $tester_name, $l10n[$result_code], $execution_ts);
                }
            }
        }
        if (!is_null($message)) {
            $resultMap[] = array($message);
        }
    }
    return $resultMap;
}