Exemple #1
0
function importTestCaseDataFromXML(&$db, $fileName, $parentID, $tproject_id, $userID, $options = null)
{
    tLog('importTestCaseDataFromXML called for file: ' . $fileName);
    $xmlTCs = null;
    $resultMap = null;
    $my = array();
    $my['options'] = array('useRecursion' => false, 'importIntoProject' => 0, 'duplicateLogic' => array('hitCriteria' => 'name', 'actionOnHit' => null));
    $my['options'] = array_merge($my['options'], (array) $options);
    foreach ($my['options'] as $varname => $value) {
        ${$varname} = $value;
    }
    if (file_exists($fileName)) {
        $xml = @simplexml_load_file($fileName);
        if ($xml !== FALSE) {
            $xmlKeywords = $xml->xpath('//keywords');
            $kwMap = null;
            if ($xmlKeywords) {
                $tproject = new testproject($db);
                $loop2do = sizeof($xmlKeywords);
                for ($idx = 0; $idx < $loop2do; $idx++) {
                    $tproject->importKeywordsFromSimpleXML($tproject_id, $xmlKeywords[$idx]);
                }
                $kwMap = $tproject->get_keywords_map($tproject_id);
                $kwMap = is_null($kwMap) ? null : array_flip($kwMap);
            }
            if (!$my['options']['useRecursion'] && $xml->getName() == 'testcases') {
                $resultMap = importTestCasesFromSimpleXML($db, $xml, $parentID, $tproject_id, $userID, $kwMap, $my['options']['duplicateLogic']);
            }
            if ($useRecursion && $xml->getName() == 'testsuite') {
                $resultMap = importTestSuitesFromSimpleXML($db, $xml, $parentID, $tproject_id, $userID, $kwMap, $my['options']);
            }
        }
    }
    return $resultMap;
}
/** Process CVS file contents with requirements into TL
 *  and creates an array with reports
 *  @return array_of_strings list of particular REQ data with resolution comment
 *
 *
 **/
function executeImportedReqs(&$db, $arrImportSource, $map_cur_reqdoc_id, $conflictSolution, $emptyScope, $idSRS, $tprojectID, $userID)
{
    define('SKIP_CONTROLS', 1);
    $req_mgr = new requirement_mgr($db);
    $import_status = null;
    $field_size = config_get('field_size');
    foreach ($arrImportSource as $data) {
        $docID = trim_and_limit($data['docid'], $field_size->req_docid);
        $title = trim_and_limit($data['title'], $field_size->req_title);
        $scope = $data['description'];
        $type = $data['type'];
        $status = $data['status'];
        $expected_coverage = $data['expected_coverage'];
        $node_order = $data['node_order'];
        if ($emptyScope == 'on' && empty($scope)) {
            // skip rows with empty scope
            $import_status = lang_get('req_import_result_skipped');
        } else {
            $crash = $map_cur_reqdoc_id && array_search($docID, $map_cur_reqdoc_id);
            if ($crash) {
                // process conflict according to choosen solution
                tLog('Conflict found. solution: ' . $conflictSolution);
                $import_status['msg'] = 'Error';
                if ($conflictSolution == 'overwrite') {
                    $item = current($req_mgr->getByDocID($docID, $tprojectID));
                    $last_version = $req_mgr->get_last_version_info($item['id']);
                    // BUGID 0003745: CSV Requirements Import Updates Frozen Requirement
                    if ($last_version['is_open'] == 1) {
                        $op = $req_mgr->update($item['id'], $last_version['id'], $docID, $title, $scope, $userID, $status, $type, $expected_coverage, $node_order, SKIP_CONTROLS);
                        if ($op['status_ok']) {
                            $import_status['msg'] = lang_get('req_import_result_overwritten');
                        }
                    } else {
                        $import_status['msg'] = lang_get('req_import_result_skipped_is_frozen');
                    }
                } elseif ($conflictSolution == 'skip') {
                    // no work
                    $import_status['msg'] = lang_get('req_import_result_skipped');
                }
            } else {
                // no conflict - just add requirement
                $import_status = $req_mgr->create($idSRS, $docID, $title, $scope, $userID, $status, $type, $expected_coverage, $node_order);
            }
            $arrImport[] = array('doc_id' => $docID, 'title' => $title, 'import_status' => $import_status['msg']);
        }
    }
    return $arrImport;
}
Exemple #3
0
/**
 * set session data after modification or authorization
 *
 * @param resource &$db reference to DB identifier
 * @param string $user
 * @param integer $id
 * @param integer $roleID 
 * @param string $email 
 * @param string $locale [default = null]
 * @param boolean $active [default = null] documentation
 * 
 * @return integer status code
 * 
 * @TODO havlatm: move to tlSession class
 * @TODO fix return functionality
 **/
function setUserSession(&$db, $user, $id, $roleID, $email, $locale = null, $active = null)
{
    tLog('setUserSession: $user='******' $id=' . $id . ' $roleID=' . $roleID . ' $email=' . $email . ' $locale=' . $locale);
    $_SESSION['userID'] = $id;
    $_SESSION['testprojectID'] = null;
    $_SESSION['s_lastAttachmentList'] = null;
    if (!is_null($locale)) {
        $_SESSION['locale'] = $locale;
        setDateTimeFormats($locale);
    }
    $tproject_mgr = new testproject($db);
    $gui_cfg = config_get('gui');
    $opt = array('output' => 'map_name_with_inactive_mark', 'order_by' => $gui_cfg->tprojects_combo_order_by);
    $arrProducts = $tproject_mgr->get_accessible_for_user($id, $opt);
    $tproject_cookie = 'TL_lastTestProjectForUserID_' . $id;
    if (isset($_COOKIE[$tproject_cookie])) {
        if (isset($arrProducts[$_COOKIE[$tproject_cookie]]) && $arrProducts[$_COOKIE[$tproject_cookie]]) {
            $_SESSION['testprojectID'] = $_COOKIE[$tproject_cookie];
            tLog('Cookie: {$tproject_cookie}=' . $_SESSION['testprojectID']);
        }
    }
    if (!$_SESSION['testprojectID']) {
        $tpID = null;
        if (sizeof($arrProducts)) {
            $tpID = key($arrProducts);
        }
        $_SESSION['testprojectID'] = $tpID;
    }
    // Validation is done in navBar.php
    $tplan_cookie = 'TL_lastTestPlanForUserID_' . $id;
    if (isset($_COOKIE[$tplan_cookie])) {
        $_SESSION['testplanID'] = $_COOKIE[$tplan_cookie];
        tLog("Cookie: {$tplan_cookie}=" . $_SESSION['testplanID']);
    }
    return 1;
}
 *
 * @internal Revisions:
 * 20101010 - franciscom - added testsuite_id as parameter, needed to do checks when creating test case
 * 20100225 - eloff - initial commit
 *
 **/
require_once '../../config.inc.php';
require_once 'common.php';
testlinkInitPage($db);
$data = array('success' => true, 'message' => '');
$iParams = array("name" => array(tlInputParameter::STRING_N, 0, 100), "testcase_id" => array(tlInputParameter::INT), "testsuite_id" => array(tlInputParameter::INT));
$args = G_PARAMS($iParams);
if (has_rights($db, 'mgt_view_tc')) {
    $tree_manager = new tree($db);
    $node_types_descr_id = $tree_manager->get_available_node_types();
    // To allow name check when creating a NEW test case => we do not have test case id
    $args['testcase_id'] = $args['testcase_id'] > 0 ? $args['testcase_id'] : null;
    $args['testsuite_id'] = $args['testsuite_id'] > 0 ? $args['testsuite_id'] : null;
    // for debug -
    // $xx = "\$args['testcase_id']:{$args['testcase_id']} - \$args['name']:{$args['name']}" .
    //       " - \$args['testsuite_id']:{$args['testsuite_id']}";
    // file_put_contents('c:\checkTCaseDuplicateName.php.ajax', $xx);
    $check = $tree_manager->nodeNameExists($args['name'], $node_types_descr_id['testcase'], $args['testcase_id'], $args['testsuite_id']);
    $data['success'] = !$check['status'];
    $data['message'] = $check['msg'];
} else {
    tLog('User has not right needed to do requested action - checkTCaseDuplicateName.php', 'ERROR');
    $data['success'] = false;
    $data['message'] = lang_get('user_has_no_right_for_action');
}
echo json_encode($data);
require '../../config.inc.php';
require_once 'common.php';
require_once 'displayMgr.php';
$timerOn = microtime(true);
$templateCfg = templateConfiguration();
$args = init_args($db);
$tplan_mgr = new testplan($db);
$gui = initializeGui($db, $args, $tplan_mgr);
$mailCfg = buildMailCfg($gui);
$metricsMgr = new tlTestPlanMetrics($db);
$dummy = $metricsMgr->getStatusTotalsByTopLevelTestSuiteForRender($args->tplan_id);
if (is_null($dummy)) {
    // no test cases -> no report
    $gui->do_report['status_ok'] = 0;
    $gui->do_report['msg'] = lang_get('report_tspec_has_no_tsuites');
    tLog('Overall Metrics page: no test cases defined');
} else {
    // do report
    $gui->statistics->testsuites = $dummy->info;
    $gui->do_report['status_ok'] = 1;
    $gui->do_report['msg'] = '';
    $items2loop = array('testsuites', 'keywords');
    $keywordsMetrics = $metricsMgr->getStatusTotalsByKeywordForRender($args->tplan_id);
    $gui->statistics->keywords = !is_null($keywordsMetrics) ? $keywordsMetrics->info : null;
    if ($gui->showPlatforms) {
        $items2loop[] = 'platform';
        $platformMetrics = $metricsMgr->getStatusTotalsByPlatformForRender($args->tplan_id);
        $gui->statistics->platform = !is_null($platformMetrics) ? $platformMetrics->info : null;
    }
    if ($gui->testprojectOptions->testPriorityEnabled) {
        $items2loop[] = 'priorities';
 /**
  *
  *
  **/
 function checkCfg()
 {
     $status_ok = true;
     if (property_exists($this->cfg, 'projectkey')) {
         $pk = trim((string) $this->cfg->projectkey);
         if ($pk == '') {
             $status_ok = false;
             $msg = __CLASS__ . ' - Empty configuration: <projectKey>';
         }
     } else {
         // this is oK if user only wants to LINK issues
         $this->cfg->projectkey = self::NOPROJECTKEY;
     }
     if (!$status_ok) {
         tLog(__METHOD__ . ' / ' . $msg, 'ERROR');
     }
     return $status_ok;
 }
 /**
  * establishes the database connection to the bugtracking system
  *
  * @return bool returns true if the db connection was established and the
  * db could be selected, false else
  *
  **/
 function connect()
 {
     if (is_null($this->cfg->dbhost) || is_null($this->cfg->dbuser)) {
         return false;
     }
     // cast everything to string in order to avoid issues
     // @20140604 someone has been issues trying to connect to JIRA on MSSQL
     $this->cfg->dbtype = strtolower((string) $this->cfg->dbtype);
     $this->cfg->dbhost = (string) $this->cfg->dbhost;
     $this->cfg->dbuser = (string) $this->cfg->dbuser;
     $this->cfg->dbpassword = (string) $this->cfg->dbpassword;
     $this->cfg->dbname = (string) $this->cfg->dbname;
     $this->dbConnection = new database($this->cfg->dbtype);
     $result = $this->dbConnection->connect(false, $this->cfg->dbhost, $this->cfg->dbuser, $this->cfg->dbpassword, $this->cfg->dbname);
     if (!$result['status']) {
         $this->dbConnection = null;
         $connection_args = "(interface: - Host:{$this->cfg}->dbhost - " . "DBName: {$this->cfg}->dbname - User: {$this->cfg}->dbuser) ";
         $msg = sprintf(lang_get('BTS_connect_to_database_fails'), $connection_args);
         tLog($msg . $result['dbms_msg'], 'ERROR');
     } elseif ($this->cfg->dbtype == 'mysql') {
         if ($this->cfg->dbcharset == 'UTF-8') {
             $r = $this->dbConnection->exec_query("SET CHARACTER SET utf8");
             $r = $this->dbConnection->exec_query("SET NAMES utf8");
             $r = $this->dbConnection->exec_query("SET collation_connection = 'utf8_general_ci'");
         } else {
             $r = $this->dbConnection->exec_query("SET CHARACTER SET " . $this->cfg->dbcharset);
             $r = $this->dbConnection->exec_query("SET NAMES " . $this->cfg->dbcharset);
         }
     }
     $this->connected = $result['status'] ? true : false;
     return $this->connected;
 }
/**
 *
 * $event->message
 * $event->logLevel
 * $event->source
 * $event->objectID
 * $event->objectType
 * $event->code
 *
 */
function logEvent($event)
{
    return tLog($event->message, $event->logLevel, $event->source, $event->objectID, $event->objectType, $event->code);
}
/**
 * Generate HTML header and send it to browser
 * @param string $format identifier of document format; value must be in $tlCfg->reports_formats
 * @param integer $doc_kind Magic number of document kind; see consts.inc.php for list 
 *    (for example: DOC_TEST_PLAN_DESIGN)
 * @author havlatm
 */
function flushHttpHeader($format, $doc_kind = 0)
{
    $file_extensions = config_get('reports_file_extension');
    $reports_applications = config_get('reports_applications');
    switch ($doc_kind) {
        case DOC_TEST_SPEC:
            $kind_acronym = '_test_spec';
            break;
        case DOC_TEST_PLAN_DESIGN:
            $kind_acronym = '_test_plan';
            break;
        case DOC_TEST_PLAN_EXECUTION:
            $kind_acronym = '_test_report';
            break;
        case DOC_REQ_SPEC:
            $kind_acronym = '_req_spec';
            break;
        default:
            $kind_acronym = '';
            break;
    }
    if ($format == FORMAT_MAIL_HTML) {
        tLog('flushHttpHeader> Invalid format: ' . $format, 'ERROR');
    }
    $filename = isset($_SESSION['testprojectPrefix']) ? $_SESSION['testprojectPrefix'] : '';
    $filename .= $kind_acronym . '-' . date('Y-m-d') . '.' . $file_extensions[$format];
    tLog('Flush HTTP header for ' . $format);
    $contentType = isset($reports_applications[$format]) ? $reports_applications[$format] : 'text/html';
    $contentType .= is_null($format) || $format == '' ? '' : "; name='Testlink_" . $format . "'";
    header("Content-type: {$contentType}");
    header("Content-Description: TestLink - Generated Document (see " . __FUNCTION__ . ")");
    if (!is_null($format) && $format != '' && $format != FORMAT_HTML) {
        header("Content-Disposition: attachment; filename={$filename}");
    }
    flush();
}
 /**
  * 
  * @param $feature_map
  * $feature_map['feature_id']['user_id']
  * $feature_map['feature_id']['type']
  * $feature_map['feature_id']['status']
  * $feature_map['feature_id']['assigner_id']
  * $feature_map['feature_id']['build_id']
  * 
  *
  * Need to manage situation where user_id = 0 is passed
  * I will IGNORE IT
  *
  * @internal revisions
  */
 function assign($feature_map)
 {
     $debugMsg = 'Class:' . __CLASS__ . ' - Method: ' . __FUNCTION__;
     $ret = array();
     $types = $this->get_available_types();
     $safe = null;
     foreach ($feature_map as $feature_id => $elem) {
         $safe['feature_id'] = intval($feature_id);
         $safe['build_id'] = intval($elem['build_id']);
         $safe['type'] = intval($elem['type']);
         $uSet = (array) $elem['user_id'];
         foreach ($uSet as $user_id) {
             $safe['user_id'] = intval($user_id);
             // Check if exists before adding
             $check = "/* {$debugMsg} */ ";
             $check .= " SELECT id FROM {$this->tables['user_assignments']} " . " WHERE feature_id = " . $safe['feature_id'] . " AND build_id = " . $safe['build_id'] . " AND type = " . $safe['type'] . " AND user_id = " . $safe['user_id'];
             $rs = $this->db->get_recordset($check);
             if (is_null($rs) || count($rs) == 0) {
                 if ($safe['user_id'] > 0) {
                     $sql = "INSERT INTO {$this->tables['user_assignments']} " . "(feature_id,user_id,assigner_id,type,status,creation_ts";
                     $values = "VALUES({$safe['feature_id']},{$safe['user_id']}," . "{$elem['assigner_id']}," . "{$safe['type']},{$elem['status']},";
                     $values .= isset($elem['creation_ts']) ? $elem['creation_ts'] : $this->db->db_now();
                     if (isset($elem['deadline_ts'])) {
                         $sql .= ",deadline_ts";
                         $values .= "," . $elem['deadline_ts'];
                     }
                     if (isset($elem['build_id'])) {
                         $sql .= ",build_id";
                         $values .= "," . $safe['build_id'];
                     } else {
                         if ($safe['type'] == $types['testcase_execution']['id']) {
                             throw new Exception("Error Processing Request - BUILD ID is Mandatory");
                         }
                     }
                     $sql .= ") " . $values . ")";
                     tLog(__METHOD__ . '::' . $sql, "DEBUG");
                     $this->db->exec_query($sql);
                     $ret[] = $sql;
                 }
             }
         }
         // loop over users
     }
     return $ret;
 }
Exemple #11
0
 /** 
  * execute SQL query, 
  * requires connection to be opened
  * 
  * @param string $p_query SQL request
  * @param integer $p_limit (optional) number of rows
  * @param integer $p_offset (optional) begining row number
  * 
  * @return boolean result of request 
  **/
 function exec_query($p_query, $p_limit = -1, $p_offset = -1)
 {
     $ec = 0;
     $emsg = null;
     $logLevel = 'DEBUG';
     $message = '';
     if ($this->logQueries) {
         $this->nQuery++;
         $t_start = $this->microtime_float();
     }
     if ($p_limit != -1 || $p_offset != -1) {
         $t_result = $this->db->SelectLimit($p_query, $p_limit, $p_offset);
     } else {
         $t_result = $this->db->Execute($p_query);
     }
     if ($this->logQueries) {
         $t_elapsed = number_format($this->microtime_float() - $t_start, 4);
         $this->overallDuration += $t_elapsed;
         $message = "SQL [" . $this->nQuery . "] executed [took {$t_elapsed} secs]" . "[all took {$this->overallDuration} secs]:\n\t\t";
     }
     $message .= $p_query;
     if (!$t_result) {
         $ec = $this->error_num();
         $emsg = $this->error_msg();
         $message .= "\nQuery failed: errorcode[" . $ec . "]" . "\n\terrormsg:" . $emsg;
         $logLevel = 'ERROR';
         tLog("ERROR ON exec_query() - database.class.php <br />" . $this->error(htmlspecialchars($p_query)) . "<br />THE MESSAGE : {$message} ", 'ERROR', "DATABASE");
         echo "<pre> ============================================================================== </pre>";
         echo "<pre> DB Access Error - debug_print_backtrace() OUTPUT START </pre>";
         echo "<pre> ATTENTION: Enabling more debug info will produce path disclosure weakness (CWE-200) </pre>";
         echo "<pre>            Having this additional Information could be useful for reporting </pre>";
         echo "<pre>            issue to development TEAM. </pre>";
         echo "<pre> ============================================================================== </pre>";
         if (defined('DBUG_ON') && DBUG_ON == 1) {
             echo "<pre>";
             debug_print_backtrace();
             echo "</pre>";
         }
         //else
         //{
         //  echo "<pre>"; debug_print_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); echo "</pre>";
         //}
         echo "<pre> ============================================================================== </pre>";
         $t_result = false;
     }
     if ($this->logEnabled) {
         tLog($message, $logLevel, "DATABASE");
     }
     if ($this->logQueries) {
         array_push($this->queries_array, array($p_query, $t_elapsed, $ec, $emsg));
     }
     return $t_result;
 }
function logWarningEvent($message, $activityCode = null, $objectID = null, $objectType = null)
{
    return tLog($message, "WARNING", "GUI", $objectID, $objectType, $activityCode);
}
 /**
  * @param integer $value the value which should be validated
  * @return bool return true if the value was successfully validated, else throws an Exception
  */
 public function validate($value)
 {
     $msg = 'Input parameter validation failed';
     if (!is_numeric($value)) {
         $msg = "{$msg} [numeric: " . htmlspecialchars($value) . "]";
         tLog($msg, 'ERROR');
         throw new Exception($msg);
     }
     $value = intval($value);
     $minVal = $this->minVal;
     if ($value < $minVal) {
         $msg = "{$msg} [minVal: " . htmlspecialchars($value) . " = {$minVal}]";
         tLog($msg, 'ERROR');
         throw new Exception($msg);
     }
     $maxVal = $this->maxVal;
     if ($value > $maxVal) {
         $msg = "{$msg} [maxVal: " . htmlspecialchars($value) . " = {$maxVal}]";
         tLog($msg, 'ERROR');
         throw new Exception($msg);
     }
     $pfnValidation = $this->pfnValidation;
     if ($pfnValidation && !$pfnValidation($value)) {
         $msg = "{$msg} [external function]";
         tLog($msg, 'ERROR');
         throw new Exception($msg);
     }
     return true;
 }
 /**
  * Unserialize project options
  * 
  * @param array $recorset produced by getTestProject() 
  */
 protected function parseTestProjectRecordset(&$recordset)
 {
     if (count($recordset) > 0) {
         foreach ($recordset as $number => $row) {
             $recordset[$number]['opt'] = unserialize($row['options']);
         }
     } else {
         $recordset = null;
         tLog('parseTestProjectRecordset: No project on query', 'DEBUG');
     }
 }
Exemple #15
0
/**
 * get user name from pool (save used names in session to improve performance)
 * 
 * @param integer $db DB connection identifier 
 * @param integer $userId
 * 
 * @return string readable user name
 * @author havlatm
 */
function gendocGetUserName(&$db, $userId)
{
    $authorName = null;
    if (isset($_SESSION['userNamePool'][$userId])) {
        $authorName = $_SESSION['userNamePool'][$userId];
    } else {
        $user = tlUser::getByID($db, $userId);
        if ($user) {
            $authorName = $user->getDisplayName();
            $authorName = htmlspecialchars($authorName);
            $_SESSION['userNamePool'][$userId] = $authorName;
        } else {
            $authorName = lang_get('undefined');
            tLog('tlUser::getByID($db,$userId) failed', 'ERROR');
        }
    }
    return $authorName;
}
 function create_tc_from_requirement($mixIdReq, $srs_id, $user_id, $tproject_id = null, $tc_count = null)
 {
     $debugMsg = 'Class:' . __CLASS__ . ' - Method: ' . __FUNCTION__;
     $tcase_mgr = new testcase($this->db);
     $tsuite_mgr = new testsuite($this->db);
     $req_cfg = config_get('req_cfg');
     $field_size = config_get('field_size');
     $auto_testsuite_name = $req_cfg->default_testsuite_name;
     $node_descr_type = $this->tree_mgr->get_available_node_types();
     $empty_steps = null;
     $empty_preconditions = '';
     // fix for BUGID 2995
     $labels['tc_created'] = lang_get('tc_created');
     $output = null;
     $reqSet = is_array($mixIdReq) ? $mixIdReq : array($mixIdReq);
     /* contribution BUGID 2996, testcase creation */
     if (is_null($tproject_id) || $tproject_id == 0) {
         $tproject_id = $this->tree_mgr->getTreeRoot($srs_id);
     }
     if ($req_cfg->use_req_spec_as_testsuite_name) {
         $full_path = $this->tree_mgr->get_path($srs_id);
         $addition = " (" . lang_get("testsuite_title_addition") . ")";
         $truncate_limit = $field_size->testsuite_name - strlen($addition);
         // REQ_SPEC_A
         //           |-- REQ_SPEC_A1
         //                          |-- REQ_SPEC_A2
         //                                         |- REQ100
         //                                         |- REQ101
         //
         // We will try to check if a test suite has already been created for
         // top REQ_SPEC_A  (we do search using automatic generated name as search criteria).
         // If not => we need to create all path till leaves (REQ100 and REQ200)
         //
         //
         // First search: we use test project
         $parent_id = $tproject_id;
         $deep_create = false;
         foreach ($full_path as $key => $node) {
             // follow hierarchy of test suites to create
             $tsuiteInfo = null;
             $testsuite_name = substr($node['name'], 0, $truncate_limit) . $addition;
             if (!$deep_create) {
                 // child test suite with this name, already exists on current parent ?
                 // At first a failure we will not check anymore an proceed with deep create
                 $sql = "/* {$debugMsg} */ SELECT id,name FROM {$this->tables['nodes_hierarchy']} NH " . " WHERE name='" . $this->db->prepare_string($testsuite_name) . "' " . " AND node_type_id=" . $node_descr_type['testsuite'] . " AND parent_id = {$parent_id} ";
                 // If returns more that one record use ALWAYS first
                 $tsuiteInfo = $this->db->fetchRowsIntoMap($sql, 'id');
             }
             if (is_null($tsuiteInfo)) {
                 $tsuiteInfo = $tsuite_mgr->create($parent_id, $testsuite_name, $req_cfg->testsuite_details);
                 $output[] = sprintf(lang_get('testsuite_name_created'), $testsuite_name);
                 $deep_create = true;
             } else {
                 $tsuiteInfo = current($tsuiteInfo);
                 $tsuite_id = $tsuiteInfo['id'];
             }
             $tsuite_id = $tsuiteInfo['id'];
             // last value here will be used as parent for test cases
             $parent_id = $tsuite_id;
         }
         $output[] = sprintf(lang_get('created_on_testsuite'), $testsuite_name);
     } else {
         // don't use req_spec as testsuite name
         // Warning:
         // We are not maintaining hierarchy !!!
         $sql = " SELECT id FROM {$this->tables['nodes_hierarchy']} NH " . " WHERE name='" . $this->db->prepare_string($auto_testsuite_name) . "' " . " AND parent_id=" . $testproject_id . " " . " AND node_type_id=" . $node_descr_type['testsuite'];
         $result = $this->db->exec_query($sql);
         if ($this->db->num_rows($result) == 1) {
             $row = $this->db->fetch_array($result);
             $tsuite_id = $row['id'];
             $label = lang_get('created_on_testsuite');
         } else {
             // not found -> create
             tLog('test suite:' . $auto_testsuite_name . ' was not found.');
             $new_tsuite = $tsuite_mgr->create($testproject_id, $auto_testsuite_name, $req_cfg->testsuite_details);
             $tsuite_id = $new_tsuite['id'];
             $label = lang_get('testsuite_name_created');
         }
         $output[] = sprintf($label, $auto_testsuite_name);
     }
     /* end contribution */
     // create TC
     $createOptions = array();
     $createOptions['check_names_for_duplicates'] = config_get('check_names_for_duplicates');
     $createOptions['action_on_duplicate_name'] = config_get('action_on_duplicate_name');
     $testcase_importance_default = config_get('testcase_importance_default');
     // compute test case order
     $testcase_order = config_get('treemenu_default_testcase_order');
     $nt2exclude = array('testplan' => 'exclude_me', 'requirement_spec' => 'exclude_me', 'requirement' => 'exclude_me');
     $siblings = $this->tree_mgr->get_children($tsuite_id, $nt2exclude);
     if (!is_null($siblings)) {
         $dummy = end($siblings);
         $testcase_order = $dummy['node_order'];
     }
     foreach ($reqSet as $reqID) {
         $reqData = $this->get_by_id($reqID, requirement_mgr::LATEST_VERSION);
         $count = !is_null($tc_count) ? $tc_count[$reqID] : 1;
         $reqData = $reqData[0];
         // Generate name with progessive
         $instance = 1;
         $getOptions = array('check_criteria' => 'like', 'access_key' => 'name');
         $itemSet = $tcase_mgr->getDuplicatesByName($reqData['title'], $tsuite_id, $getOptions);
         $nameSet = null;
         if (!is_null($itemSet)) {
             $nameSet = array_flip(array_keys($itemSet));
         }
         for ($idx = 0; $idx < $count; $idx++) {
             $testcase_order++;
             // We have a little problem to work on:
             // suppose you have created:
             // TC [1]
             // TC [2]
             // TC [3]
             // If we delete TC [2]
             // When I got siblings  il will got 2, if I create new progressive using next,
             // it will be 3 => I will get duplicated name.
             //
             // Seems better option can be:
             // Get all siblings names, put on array, create name an check if exists, if true
             // generate a new name.
             // This may be at performance level is better than create name then check on db,
             // because this approach will need more queries to DB
             //
             $tcase_name = $reqData['title'] . " [{$instance}]";
             if (!is_null($nameSet)) {
                 while (isset($nameSet[$tcase_name])) {
                     $instance++;
                     $tcase_name = $reqData['title'] . " [{$instance}]";
                 }
             }
             $nameSet[$tcase_name] = $tcase_name;
             // 20100106 - franciscom - multiple test case steps feature - removed expected_results
             // Julian - BUGID 2995
             $tcase = $tcase_mgr->create($tsuite_id, $tcase_name, $req_cfg->testcase_summary_prefix . $reqData['scope'], $empty_preconditions, $empty_steps, $user_id, null, $testcase_order, testcase::AUTOMATIC_ID, TESTCASE_EXECUTION_TYPE_MANUAL, $testcase_importance_default, $createOptions);
             $tcase_name = $tcase['new_name'] == '' ? $tcase_name : $tcase['new_name'];
             $output[] = sprintf($labels['tc_created'], $tcase_name);
             // create coverage dependency
             if (!$this->assign_to_tcase($reqData['id'], $tcase['id'])) {
                 $output[] = 'Test case: ' . $tcase_name . " was not created";
             }
         }
     }
     return $output;
 }
Exemple #17
0
/**
 * Load global configuration to function
 * 
 * @param string $config_id key for identification of configuration parameter
 * @return mixed the configuration parameter(s)
 * 
 * @internal Revisions
 */
function config_get($config_id)
{
    $t_value = '';
    $t_found = false;
    $logInfo = array('msg' => "config option not available: {$config_id}", 'level' => 'WARNING');
    if (!$t_found) {
        $my = "g_" . $config_id;
        if ($t_found = isset($GLOBALS[$my])) {
            $t_value = $GLOBALS[$my];
        } else {
            $cfg = $GLOBALS['tlCfg'];
            if ($t_found = property_exists($cfg, $config_id)) {
                $t_value = $cfg->{$config_id};
            }
        }
        if ($t_found) {
            $logInfo = array('msg' => "config option: {$config_id} is {$t_value}", 'level' => 'INFO');
        }
    }
    tLog($logInfo['msg'], $logInfo['level']);
    return $t_value;
}
$reports_mgr = new tlReports($db, $gui->tplan_id);
// -----------------------------------------------------------------------------
// Do some checks to understand if reports make sense
// Check if there are linked test cases to the choosen test plan.
$tc4tp_count = 1;
//$reports_mgr->get_count_testcase4testplan();
tLog('TC in TP count = ' . $tc4tp_count);
if ($tc4tp_count == 0) {
    // Test plan without test cases
    $gui->do_report['status_ok'] = 0;
    $gui->do_report['msg'] = lang_get('report_tplan_has_no_tcases');
}
// Build qty
$build_count = 1;
//$reports_mgr->get_count_builds();
tLog('Active Builds count = ' . $build_count);
if ($build_count == 0) {
    // Test plan without builds can have execution data
    $gui->do_report['status_ok'] = 0;
    $gui->do_report['msg'] = lang_get('report_tplan_has_no_build');
}
// -----------------------------------------------------------------------------
// get navigation data
$gui->menuItems = array();
if ($gui->do_report['status_ok']) {
    // create a list or reports
    $context = new stdClass();
    $context->tproject_id = $args->tproject_id;
    $context->tplan_id = $args->tplan_id;
    $tplan_mgr = new testplan($db);
    $dmy = $tplan_mgr->get_by_id($context->tplan_id);
Exemple #19
0
 function TLSmarty()
 {
     global $tlCfg;
     global $g_locales_html_select_date_field_order;
     global $g_locales_date_format;
     global $g_locales_timestamp_format;
     // $this->Smarty();
     parent::__construct();
     $this->template_dir = TL_ABS_PATH . 'gui/templates/';
     $this->compile_dir = TL_TEMP_PATH;
     $this->config_dir = TL_ABS_PATH . 'gui/templates/';
     $testproject_coloring = $tlCfg->gui->testproject_coloring;
     $testprojectColor = $tlCfg->gui->background_color;
     //TL_BACKGROUND_DEFAULT;
     if (isset($_SESSION['testprojectColor'])) {
         $testprojectColor = $_SESSION['testprojectColor'];
         if ($testprojectColor == "") {
             $testprojectColor = $tlCfg->gui->background_color;
         }
     }
     $this->assign('testprojectColor', $testprojectColor);
     $my_locale = isset($_SESSION['locale']) ? $_SESSION['locale'] : TL_DEFAULT_LOCALE;
     $basehref = isset($_SESSION['basehref']) ? $_SESSION['basehref'] : TL_BASE_HREF;
     if ($tlCfg->smarty_debug) {
         $this->debugging = true;
         tLog("Smarty debug window = ON");
     }
     // -------------------------------------------------------------------------------------
     // Must be initialized to avoid log on TestLink Event Viewer due to undefined variable.
     // This means that optional/missing parameters on include can not be used.
     //
     // Good refactoring must be done in future, to create group of this variable
     // with clear names that must be a hint for developers, to understand where this
     // variables are used.
     // inc_head.tpl
     $this->assign('SP_html_help_file', null);
     $this->assign('menuUrl', null);
     $this->assign('args', null);
     $this->assign('additionalArgs', null);
     $this->assign('pageTitle', null);
     $this->assign('css_only', null);
     $this->assign('body_onload', null);
     // inc_attachments.tpl
     $this->assign('attach_tableStyles', "font-size:12px");
     $this->assign('attach_tableClassName', "simple");
     $this->assign('attach_inheritStyle', 0);
     $this->assign('attach_show_upload_btn', 1);
     $this->assign('attach_show_title', 1);
     $this->assign('attach_downloadOnly', false);
     // inc_help.tpl
     $this->assign('inc_help_alt', null);
     $this->assign('inc_help_title', null);
     $this->assign('inc_help_style', null);
     $this->assign('show_help_icon', true);
     $this->assign('tplan_name', null);
     $this->assign('name', null);
     // -----------------------------------------------------------------------------
     $this->assign('basehref', $basehref);
     $this->assign('css', $basehref . TL_TESTLINK_CSS);
     $this->assign('locale', $my_locale);
     // -----------------------------------------------------------------------------
     // load configuration
     $this->assign('session', isset($_SESSION) ? $_SESSION : null);
     // load configuration
     $this->assign('tlCfg', $tlCfg);
     $this->assign('gsmarty_gui', $tlCfg->gui);
     $this->assign('gsmarty_spec_cfg', config_get('spec_cfg'));
     $this->assign('gsmarty_attachments', config_get('attachments'));
     $this->assign('pageCharset', $tlCfg->charset);
     $this->assign('tlVersion', TL_VERSION);
     $this->assign('gsmarty_bugInterfaceOn', config_get('bugInterfaceOn'));
     $this->assign('testproject_coloring', null);
     // -----------------------------------------------------------------------------
     // define a select structure for {html_options ...}
     $this->assign('gsmarty_option_yes_no', array(0 => lang_get('No'), 1 => lang_get('Yes')));
     $this->assign('gsmarty_option_priority', array(HIGH => lang_get('high_priority'), MEDIUM => lang_get('medium_priority'), LOW => lang_get('low_priority')));
     $this->assign('gsmarty_option_importance', array(HIGH => lang_get('high_importance'), MEDIUM => lang_get('medium_importance'), LOW => lang_get('low_importance')));
     // this allows unclosed <head> tag to add more information and link; see inc_head.tpl
     $this->assign('openHead', 'no');
     // there are some variables which should not be assigned for template
     // but must be initialized
     // inc_head.tpl
     $this->assign('jsValidate', null);
     $this->assign('jsTree', null);
     $this->assign('editorType', null);
     // user feedback variables (used in inc_update.tpl)
     $this->assign('user_feedback', null);
     $this->assign('feedback_type', '');
     // Possibile values: soft
     $this->assign('action', 'updated');
     //todo: simplify (remove) - use user_feedback
     $this->assign('sqlResult', null);
     //todo: simplify (remove) - use user_feedback
     $this->assign('refresh', 'no');
     $this->assign('result', null);
     $this->assign('optLocale', config_get('locales'));
     $this->assign('gsmarty_href_keywordsView', ' "lib/keywords/keywordsView.php" ' . ' target="mainframe" class="bold" ' . ' title="' . lang_get('menu_manage_keywords') . '"');
     $this->assign('gsmarty_html_select_date_field_order', $g_locales_html_select_date_field_order[$my_locale]);
     $this->assign('gsmarty_date_format', $g_locales_date_format[$my_locale]);
     $this->assign('gsmarty_timestamp_format', $g_locales_timestamp_format[$my_locale]);
     // -----------------------------------------------------------------------------
     // Images
     $tlImages = array('info' => TL_THEME_IMG_DIR . "/question.gif", 'reorder' => TL_THEME_IMG_DIR . "/arrow_switch.png", 'sort' => TL_THEME_IMG_DIR . "/sort_hint.png", 'api_info' => TL_THEME_IMG_DIR . "/brick.png", 'direct_link' => TL_THEME_IMG_DIR . "/world_link.png", 'checked' => TL_THEME_IMG_DIR . "/apply_f2_16.png", 'export_import' => TL_THEME_IMG_DIR . "/export_import.png", 'export' => TL_THEME_IMG_DIR . "/export.png", 'import' => TL_THEME_IMG_DIR . "/import.png", 'delete' => TL_THEME_IMG_DIR . "/trash.png");
     $this->assign("tlImages", $tlImages);
     $sort_img = TL_THEME_IMG_DIR . "/sort_hint.png";
     $api_info_img = TL_THEME_IMG_DIR . "/brick.png";
     $direct_link_img = TL_THEME_IMG_DIR . "/world_link.png";
     $this->assign("sort_img", $sort_img);
     $this->assign("checked_img", TL_THEME_IMG_DIR . "/apply_f2_16.png");
     $this->assign("delete_img", TL_THEME_IMG_DIR . "/trash.png");
     $this->assign("insert_step_img", TL_THEME_IMG_DIR . "/insert_step.png");
     $msg = lang_get('show_hide_api_info');
     $toggle_api_info_img = "<img class=\"clickable\" title=\"{$msg}\" alt=\"{$msg}\" " . " onclick=\"showHideByClass('span','api_info');event.stopPropagation();\" " . " src=\"{$api_info_img}\" align=\"left\" />";
     $this->assign("toggle_api_info_img", $toggle_api_info_img);
     $msg = lang_get('show_hide_direct_link');
     $toggle_direct_link_img = "<img class=\"clickable\" title=\"{$msg}\" alt=\"{$msg}\" " . " onclick=\"showHideByClass('div','direct_link');event.stopPropagation();\" " . " src=\"{$direct_link_img}\" align=\"left\" />";
     $this->assign("toggle_direct_link_img", $toggle_direct_link_img);
     // Some useful values for Sort Table Engine
     switch (TL_SORT_TABLE_ENGINE) {
         case 'kryogenix.org':
             $sort_table_by_column = lang_get('sort_table_by_column');
             $sortHintIcon = "<img title=\"{$sort_table_by_column}\" " . " alt=\"{$sort_table_by_column}\" " . " src=\"{$sort_img}\" align=\"left\" />";
             $this->assign("sortHintIcon", $sortHintIcon);
             $this->assign("noSortableColumnClass", "sorttable_nosort");
             break;
         default:
             $this->assign("sortHintIcon", '');
             $this->assign("noSortableColumnClass", '');
             break;
     }
     // Register functions
     $this->register_function("lang_get", "lang_get_smarty");
     $this->register_function("localize_date", "localize_date_smarty");
     $this->register_function("localize_timestamp", "localize_timestamp_smarty");
     $this->register_function("localize_tc_status", "translate_tc_status_smarty");
     $this->register_modifier("basename", "basename");
     $this->register_modifier("dirname", "dirname");
 }
 /**
  * 
  *
  **/
 function getIssue($issueID)
 {
     if (!$this->isConnected()) {
         return false;
     }
     try {
         $issue = $this->APIClient->get_issue($issueID);
         if (!is_null($issue) && is_object($issue)) {
             $issue->IDHTMLString = "<b>{$issueID} : </b>";
             $issue->statusCode = $issue->State;
             $issue->statusVerbose = $issue->statusCode;
             $issue->statusHTMLString = "[{$issue->statusCode}] ";
             $issue->summaryHTMLString = $issue->summary;
         }
     } catch (\YouTrack\YouTrackException $yte) {
         tLog($yte->getMessage(), 'ERROR');
         $issue = null;
     }
     return $issue;
 }
Exemple #21
0
/**
 * used by filter options:
 *              result on specific build
 *              result on current build
 *
 *  
 * @param object &$tplan_mgr reference to test plan manager object
 * @param array &$tcase_set reference to test case set to filter
 * @param integer $tplan_id ID of test plan
 * @param array $filters filters to apply to test case set
 *
 * @return array new tcase_set
 */
function filter_by_status_for_build(&$tplan_mgr, &$tcase_set, $tplan_id, $filters)
{
    $safe_platform = intval($filters->setting_platform);
    $safe_build = intval($filters->filter_result_build);
    if ($safe_platform > 0) {
        tLog(__FUNCTION__ . ':: $tplan_mgr->getHitsStatusSetOnBuildPlatform', 'DEBUG');
        $hits = $tplan_mgr->getHitsStatusSetOnBuildPlatform($tplan_id, $safe_platform, $safe_build, (array) $filters->filter_result_result);
    } else {
        tLog(__FUNCTION__ . ':: $tplan_mgr->getHitsStatusSetOnBuildALOP', 'DEBUG');
        $hits = $tplan_mgr->getHitsStatusSetOnBuildALOP($tplan_id, $safe_build, (array) $filters->filter_result_result);
    }
    if (is_null($hits)) {
        $tcase_set = array();
    } else {
        helper_filter_cleanup($tcase_set, $hits);
    }
    return $tcase_set;
}
 /**
  *
  */
 public function addIssue($summary, $description)
 {
     // From Redmine API documentation (@20130406)
     // Parameters:
     //
     // issue - A hash of the issue attributes:
     // project_id
     // tracker_id
     // status_id
     // subject
     // description
     // category_id
     // assigned_to_id - ID of the user to assign the issue to (currently no mechanism to assign by name)
     // parent_issue_id - ID of the parent issue
     // custom_fields - See Custom fields
     // watcher_user_ids - Array of user ids to add as watchers (since 2.3.0)
     // Check mandatory info
     if (!property_exists($this->cfg, 'projectidentifier')) {
         throw new exception(__METHOD__ . " project identifier is MANDATORY");
     }
     try {
         // needs json or xml
         $issueXmlObj = new SimpleXMLElement('<?xml version="1.0"?><issue></issue>');
         // according with user report is better to use htmlspecialchars
         // 5703: Create issue with Portuguese characters produces mangled text
         //
         // $issueXmlObj->addChild('subject', htmlentities($summary));
         // $issueXmlObj->addChild('description', htmlentities($description));
         // limit size to redmine max => 255 ?
         $issueXmlObj->addChild('subject', substr(htmlspecialchars($summary), 0, 255));
         $issueXmlObj->addChild('description', htmlspecialchars($description));
         $issueXmlObj->addChild('project_id', (string) $this->cfg->projectidentifier);
         $issueXmlObj->addChild('tracker_id', (string) $this->cfg->trackerid);
         // http://www.redmine.org/issues/6843
         // "Target version" is the new display name for this property,
         // but it's still named fixed_version internally and thus in the API.
         // $issueXmlObj->addChild('fixed_version_id', (string)2);
         if (!is_null($this->issueAttr)) {
             foreach ($this->issueAttr as $ka => $kv) {
                 // will treat everything as simple strings
                 $issueXmlObj->addChild($ka, (string) $kv);
             }
         }
         $op = $this->APIClient->addIssueFromSimpleXML($issueXmlObj);
         $ret = array('status_ok' => true, 'id' => (string) $op->id, 'msg' => sprintf(lang_get('redmine_bug_created'), $summary, $issueXmlObj->project_id));
     } catch (Exception $e) {
         $msg = "Create REDMINE Ticket FAILURE => " . $e->getMessage();
         tLog($msg, 'WARNING');
         $ret = array('status_ok' => false, 'id' => -1, 'msg' => $msg . ' - serialized issue:' . serialize($issue));
     }
     return $ret;
 }
 **/
require_once '../../config.inc.php';
require_once 'common.php';
testlinkInitPage($db);
$data['userfeedback'] = lang_get('inventory_msg_no_action');
$data['success'] = FALSE;
$args = init_args();
checkRights($db, $_SESSION['currentUser'], $args);
if ($_SESSION['currentUser']->hasRight($db, "project_inventory_management", $args->tproject_id)) {
    $tlIs = new tlInventory($args->tproject_id, $db);
    $data['success'] = $tlIs->setInventory($args);
    $data['success'] = $data['success'] == 1 ? true : false;
    $data['userfeedback'] = $tlIs->getUserFeedback();
    $data['record'] = $tlIs->getCurrentData();
} else {
    tLog('User has not rights to set a device!', 'ERROR');
    $data['userfeedback'] = lang_get('inventory_msg_no_rights');
}
echo json_encode($data);
/**
 * 
 *
 */
function init_args()
{
    $_REQUEST = strings_stripSlashes($_REQUEST);
    $iParams = array("machineID" => array(tlInputParameter::INT_N), "machineOwner" => array(tlInputParameter::INT_N), "machineName" => array(tlInputParameter::STRING_N, 0, 255), "machineIp" => array(tlInputParameter::STRING_N, 0, 50), "machineNotes" => array(tlInputParameter::STRING_N, 0, 2000), "machinePurpose" => array(tlInputParameter::STRING_N, 0, 2000), "machineHw" => array(tlInputParameter::STRING_N, 0, 2000), "tproject_id" => array(tlInputParameter::INT_N));
    $args = new stdClass();
    R_PARAMS($iParams, $args);
    return $args;
}
 public function addIssue($summary, $description)
 {
     try {
         $issue = array('project' => (string) $this->cfg->projectkey, 'type' => (int) $this->cfg->issuetype, 'summary' => $summary, 'description' => $description);
         $op = $this->APIClient->createIssue($this->authToken, $issue);
         $ret = array('status_ok' => true, 'id' => $op->key, 'msg' => sprintf(lang_get('jira_bug_created'), $summary, $issue['project']));
     } catch (Exception $e) {
         $msg = "Create JIRA Ticket FAILURE => " . $e->getMessage();
         tLog($msg, 'WARNING');
         $ret = array('status_ok' => false, 'id' => -1, 'msg' => $msg . ' - serialized issue:' . serialize($issue));
     }
     return $ret;
 }
Exemple #25
0
 **/
require_once 'lib/functions/configCheck.php';
checkConfiguration();
require_once 'config.inc.php';
require_once 'common.php';
require_once 'doAuthorize.php';
$templateCfg = templateConfiguration();
$doRender = false;
// BUGID 0003129
$op = doDBConnect($db);
if (!$op['status']) {
    $smarty = new TLSmarty();
    $smarty->assign('title', lang_get('fatal_page_title'));
    $smarty->assign('content', $op['dbms_msg']);
    $smarty->display('workAreaSimple.tpl');
    tLog('Connection fail page shown.', 'ERROR');
    exit;
}
$args = init_args();
$gui = init_gui($db, $args);
switch ($args->action) {
    case 'doLogin':
    case 'ajaxlogin':
        doSessionStart();
        unset($_SESSION['basehref']);
        setPaths();
        $op = doAuthorize($db, $args->login, $args->pwd);
        if ($op['status'] < tl::OK) {
            $gui->note = is_null($op['msg']) ? lang_get('bad_user_passwd') : $op['msg'];
            if ($args->action == 'ajaxlogin') {
                echo json_encode(array('success' => false, 'reason' => $gui->note));
Exemple #26
0
        $filters->hide_testcases = HIDE_TESTCASES;
        $filters->filter_assigned_user_include_unassigned = true;
        $filters->show_testsuite_contents = true;
        // ----- BUGID 3451 and related ---------------------------------------
        $additionalInfo->useCounters = CREATE_TC_STATUS_COUNTERS_OFF;
        $additionalInfo->useColours = COLOR_BY_TC_STATUS_OFF;
        list($treeContents, $additionalArgs) = generateExecTree($db, $workPath, $args->tproject_id, $args->tproject_name, $args->tplan_id, $testplan_name, $filters, $additionalInfo);
        $tree = $treeContents->menustring;
        $gui->ajaxTree = new stdClass();
        $gui->ajaxTree->root_node = $treeContents->rootnode;
        $gui->ajaxTree->children = $treeContents->menustring;
        $gui->ajaxTree->loadFromChildren = true;
        $gui->ajaxTree->cookiePrefix .= $gui->ajaxTree->root_node->id . "_";
        break;
    default:
        tLog("Argument _REQUEST['type'] has invalid value", 'ERROR');
        exit;
        break;
}
$smarty = new TLSmarty();
$smarty->assign('gui', $gui);
$smarty->assign('arrCheckboxes', $arrCheckboxes);
$smarty->assign('selFormat', $args->format);
$smarty->assign('docType', $args->doc_type);
$smarty->assign('docTestPlanId', $args->tplan_id);
$smarty->assign('tree', $tree);
$smarty->assign('menuUrl', $workPath);
$smarty->assign('args', $getArguments);
$smarty->assign('additionalArgs', $additionalArgs);
$smarty->display($templateCfg->template_dir . $templateCfg->default_template);
/**
/**
 * TestLink Open Source Project - http://testlink.sourceforge.net/ 
 * This script is distributed under the GNU General Public License 2 or later. 
 *
 * Get list of users with a project right
 * 
 * @package 	TestLink
 * @author 		Martin Havlat
 * @copyright 	2009, TestLink community 
 * @version    	CVS: $Id: getUsersWithRight.php,v 1.1 2010/02/12 00:20:12 havlat Exp $
 *
 * @internal Revisions:
 * None
 *
 **/
require_once '../../config.inc.php';
require_once 'common.php';
testlinkInitPage($db);
$data = array();
$iParams = array("right" => array(tlInputParameter::STRING_N, 0, 100, '/^[a-z0-9_]+$/'));
$args = G_PARAMS($iParams);
// user must have the same right as requested (security)
if (has_rights($db, $args['right'])) {
    $tlUser = new tlUser($_SESSION['userID']);
    $data['rows'] = $tlUser->getNamesForProjectRight($db, $args['right'], $_SESSION['testprojectID']);
    $data['rows'][] = array('id' => '0', 'login' => ' ', 'first' => ' ', 'last' => ' ');
    // option for no owner
} else {
    tLog('Invalid right for the user: '******'right'], 'ERROR');
}
echo json_encode($data);
Exemple #28
0
 /**
  * this function establishes the database connection to the
  * bugtracking system
  *
  * @return bool returns true if the db connection was established and the
  * db could be selected, false else
  *
  * @version 1.0
  * @author Francisco Mancardi
  * @since 14.09.2006
  *
  * @version 1.0
  * @author Andreas Morsing
  * @since 22.04.2005, 21:05:25
  **/
 function connect()
 {
     if (is_null($this->dbHost) || is_null($this->dbUser)) {
         return false;
     }
     $this->dbConnection = new database($this->dbType);
     $result = $this->dbConnection->connect(false, $this->dbHost, $this->dbUser, $this->dbPass, $this->dbName);
     if (!$result['status']) {
         $this->dbConnection = null;
         $bts_type = config_get('interface_bugs');
         $connection_args = "(interface: {$bts_type} - Host:{$this->dbHost} - DBName: {$this->dbName} - User: {$this->dbUser}) ";
         $msg = sprintf(lang_get('BTS_connect_to_database_fails'), $connection_args);
         tLog($msg . $result['dbms_msg'], 'ERROR');
     } elseif (BUG_TRACK_DB_TYPE == 'mysql') {
         if ($this->dbCharSet == 'UTF-8') {
             $r = $this->dbConnection->exec_query("SET CHARACTER SET utf8");
             $r = $this->dbConnection->exec_query("SET NAMES utf8");
             $r = $this->dbConnection->exec_query("SET collation_connection = 'utf8_general_ci'");
         } else {
             $r = $this->dbConnection->exec_query("SET CHARACTER SET " . $this->dbCharSet);
             $r = $this->dbConnection->exec_query("SET NAMES " . $this->dbCharSet);
         }
     }
     $this->Connected = $result['status'] ? 1 : 0;
     return $this->Connected;
 }
Exemple #29
0
 /**
  * update test case specification
  * 
  * @param integer $id Test case unique identifier (node_hierarchy table)
  * @param integer $tcversion_id Test Case Version unique ID (node_hierarchy table)
  * @param string $name name/title
  * @param string $summary
  * @param string $preconditions
  * @param array $steps steps + expected results
  * @param integer $user_id who is doing the update
  * @param string $keywords_id optional list of keyword id to be linked to test case
  *         this list will override previous keyword links (delete + insert).
  *
  * @param integer $tc_order optional order inside parent test suite
  * @param integer $execution_type optional
  * @param integer $importance optional
  * 
  *
  *
  */
 function update($id, $tcversion_id, $name, $summary, $preconditions, $steps, $user_id, $keywords_id = '', $tc_order = self::DEFAULT_ORDER, $execution_type = TESTCASE_EXECUTION_TYPE_MANUAL, $importance = 2, $attr = null)
 {
     $ret['status_ok'] = 1;
     $ret['msg'] = '';
     $ret['reason'] = '';
     $attrib = array('status' => null, 'estimatedExecDuration' => null);
     $attrib = array_merge($attrib, (array) $attr);
     tLog("TC UPDATE ID=({$id}): exec_type={$execution_type} importance={$importance}");
     // Check if new name will be create a duplicate testcase under same parent
     if ($checkDuplicates = config_get('check_names_for_duplicates')) {
         // $check = $this->tree_manager->nodeNameExists($name,$this->my_node_type,$id);
         // new dBug($check);
         // get my parent
         $mi = $this->tree_manager->get_node_hierarchy_info($id);
         $itemSet = $this->getDuplicatesByName($name, $mi['parent_id'], array('id2exclude' => $id));
         // new dBug($itemSet);
         /*
         $ret['status_ok'] = !$check['status']; 
         $ret['msg'] = $check['msg']; 
         $ret['reason'] = $ret['status_ok'] ? '' : 'already_exists';
         */
         if (!is_null($itemSet)) {
             $ret['status_ok'] = false;
             $ret['msg'] = sprintf(lang_get('name_already_exists'), $name);
             $ret['reason'] = 'already_exists';
             $ret['hit_on'] = current($itemSet);
         }
         if ($ret['status_ok'] == false) {
             // get more info for feedback
         }
         // new dBug($ret);
     }
     if ($ret['status_ok']) {
         $sql = array();
         $sql[] = " UPDATE {$this->tables['nodes_hierarchy']} SET name='" . $this->db->prepare_string($name) . "' WHERE id= {$id}";
         $dummy = " UPDATE {$this->tables['tcversions']} " . " SET summary='" . $this->db->prepare_string($summary) . "'," . " updater_id=" . $this->db->prepare_int($user_id) . ", " . " modification_ts = " . $this->db->db_now() . "," . " execution_type=" . $this->db->prepare_int($execution_type) . ", " . " importance=" . $this->db->prepare_int($importance) . "," . " preconditions='" . $this->db->prepare_string($preconditions) . "' ";
         if (!is_null($attrib['status'])) {
             $dummy .= ", status=" . intval($attrib['status']);
         }
         if (!is_null($attrib['estimatedExecDuration'])) {
             $dummy .= ", estimated_exec_duration=";
             $v = trim($attrib['estimatedExecDuration']);
             $dummy .= $v == '' ? "NULL" : floatval($v);
         }
         $dummy .= " WHERE id = " . $this->db->prepare_int($tcversion_id);
         $sql[] = $dummy;
         foreach ($sql as $stm) {
             $result = $this->db->exec_query($stm);
             if (!$result) {
                 $ret['status_ok'] = 0;
                 $ret['msg'] = $this->db->error_msg;
                 break;
             }
         }
         if ($ret['status_ok'] && !is_null($steps)) {
             $this->update_tcversion_steps($tcversion_id, $steps);
         }
         if ($ret['status_ok']) {
             $this->updateKeywordAssignment($id, $keywords_id);
         }
     }
     return $ret;
 }
 /**
  * getHitsSameStatusPartialALOP($id,$statusSet) 
  *
  * returns recordset with:
  *
  * test cases that has at least ONE of requested status 
  * ON LAST EXECUTION ON AT LEAST ONE OF builds on build set, for a platform
  *
  * If build set is empty
  * test cases that has at least ONE of requested status 
  * ON LAST EXECUTION ON AT LEAST ONE OF ALL ACTIVE builds, for a platform
  *
  */
 function getHitsSameStatusPartialALOP($id, $statusSet, $buildSet = null)
 {
     $debugMsg = 'Class:' . __CLASS__ . ' - Method: ' . __FUNCTION__;
     $getHitsNotRunMethod = 'getHitsNotRunPartialALOP';
     $getHitsStatusSetMethod = 'getHitsStatusSetPartialALOP';
     // Needed because, may be we will need to remove an element
     $statusSetLocal = (array) $statusSet;
     $items = null;
     $hits = array('notRun' => array(), 'otherStatus' => array());
     $dummy = array_flip($statusSetLocal);
     // (code => idx)
     $get = array('notRun' => isset($dummy[$this->notRunStatusCode]), 'otherStatus' => false);
     if ($get['notRun']) {
         tLog(__METHOD__ . ":: \$tplan_mgr->{$getHitsNotRunMethod}", 'DEBUG');
         $hits['notRun'] = (array) $this->{$getHitsNotRunMethod}($id, $buildSet);
         unset($statusSetLocal[$dummy[$this->notRunStatusCode]]);
     }
     if ($get['otherStatus'] = count($statusSetLocal) > 0) {
         tLog(__METHOD__ . ":: \$tplan_mgr->{$getHitsStatusSetMethod}", 'DEBUG');
         $hits['otherStatus'] = (array) $this->{$getHitsStatusSetMethod}($id, $statusSetLocal, $buildSet);
     }
     // build results recordset
     $hitsFoundOn = array();
     $hitsFoundOn['notRun'] = count($hits['notRun']) > 0;
     $hitsFoundOn['otherStatus'] = count($hits['otherStatus']) > 0;
     if ($get['notRun'] && $get['otherStatus']) {
         if ($hitsFoundOn['notRun'] && $hitsFoundOn['otherStatus']) {
             $items = array_keys($hits['notRun']) + array_keys($hits['otherStatus']);
         }
     } else {
         if ($get['notRun'] && $hitsFoundOn['notRun']) {
             $items = array_keys($hits['notRun']);
         } else {
             if ($get['otherStatus'] && $hitsFoundOn['otherStatus']) {
                 $items = array_keys($hits['otherStatus']);
             }
         }
     }
     return is_null($items) ? $items : array_flip($items);
 }