/**
 * returns an array of RecType Structures for all RecTypes
 * rectypes = {{"groups":{"groupIDToIndex":{recTypeGroupID:index},
 *                         recTypeGroupID:{propName:val,...},...}},
 *             "names":{rtyID:name,...},
 *             "pluralNames":{rtyID:pluralName,...},
 *             "usageCount":{rtyID:nonzero-count,...},
 *             "dtDisplayOrder":{rtyID:[ordered dtyIDs], ...},
 *             "typedefs":{"commonFieldNames":[defRecType Column names],
 *                         "commonNamesToIndex":{"defRecTypes columnName":index,...},
 *                         "dtFieldNamesToIndex":{"defRecStructure columnName":index,...},
 *                         "dtFieldNames":[defRecStructure Column names],
 *                         rtyID:{"dtFields":{dtyID:[val,...]},
 *                                 "commonFields":[val,....]},
 *                         ...},
 *             "constraints":[]}};
 *
 * @global    int $dbID databse ID
 * @param     boolean $useCachedData if true does a lookup for the rectypes structure in cache
 * @return    object iformation describing all the rectypes defined in the database
 * @uses      getRectypeColNames()
 * @uses      getColumnNameToIndex()
 * @uses      getRectypeStructureFieldColNames()
 * @uses      DATABASE
 * @uses      getCachedData()
 * @uses      setCachedData()
 * @uses      getRectypeGroups()
 * @uses      getRecTypeUsageCount()
 */
function getAllRectypeStructures($useCachedData = false)
{
    global $dbID;
    $cacheKey = DATABASE . ":AllRecTypeInfo";
    if ($useCachedData) {
        $rtStructs = getCachedData($cacheKey);
        if ($rtStructs) {
            return $rtStructs;
        }
    }
    // NOTE: these are ordered to match the order of getRectypeStructureFieldColNames from DisplayName on
    $colNames = array("rst_RecTypeID", "rst_DetailTypeID", "if(rst_DisplayName is not null and CHAR_LENGTH(rst_DisplayName)>0,rst_DisplayName,dty_Name) as rst_DisplayName", "if(rst_DisplayHelpText is not null and CHAR_LENGTH(rst_DisplayHelpText)>0,rst_DisplayHelpText,dty_HelpText) as rst_DisplayHelpText", "if(rst_DisplayExtendedDescription is not null and CHAR_LENGTH(rst_DisplayExtendedDescription)>0,rst_DisplayExtendedDescription,dty_ExtendedDescription) as rst_DisplayExtendedDescription", "rst_DisplayOrder", "rst_DisplayWidth", "rst_DefaultValue", "rst_RecordMatchOrder", "rst_CalcFunctionID", "rst_RequirementType", "rst_NonOwnerVisibility", "rst_Status", "rst_OriginatingDBID", "rst_MaxValues", "rst_MinValues", "if(rst_DisplayDetailTypeGroupID is not null,rst_DisplayDetailTypeGroupID,dty_DetailTypeGroupID) as rst_DisplayDetailTypeGroupID", "if(rst_FilteredJsonTermIDTree is not null and CHAR_LENGTH(rst_FilteredJsonTermIDTree)>0,rst_FilteredJsonTermIDTree,dty_JsonTermIDTree) as rst_FilteredJsonTermIDTree", "if(rst_PtrFilteredIDs is not null and CHAR_LENGTH(rst_PtrFilteredIDs)>0,rst_PtrFilteredIDs,dty_PtrTargetRectypeIDs) as rst_PtrFilteredIDs", "rst_OrderForThumbnailGeneration", "rst_TermIDTreeNonSelectableIDs", "rst_Modified", "rst_LocallyModified", "dty_TermIDTreeNonSelectableIDs", "dty_FieldSetRectypeID");
    $query = "select " . join(",", $colNames) . " from defRecStructure" . " left join defDetailTypes on rst_DetailTypeID = dty_ID" . " left join defDetailTypeGroups on dtg_ID = if(rst_DisplayDetailTypeGroupID is not null,rst_DisplayDetailTypeGroupID,dty_DetailTypeGroupID)" . " order by rst_RecTypeID, rst_DisplayOrder, rst_ID";
    $res = mysql_query($query);
    $rtStructs = array('groups' => getRectypeGroups(), 'names' => array(), 'pluralNames' => array(), 'usageCount' => getRecTypeUsageCount(), 'dtDisplayOrder' => array());
    $rtStructs['typedefs'] = array('commonFieldNames' => getRectypeColNames(), 'commonNamesToIndex' => getColumnNameToIndex(getRectypeColNames()), 'dtFieldNamesToIndex' => getColumnNameToIndex(getRectypeStructureFieldColNames()), 'dtFieldNames' => getRectypeStructureFieldColNames());
    while ($row = mysql_fetch_row($res)) {
        if (!array_key_exists($row[0], $rtStructs['typedefs'])) {
            $rtStructs['typedefs'][$row[0]] = array('dtFields' => array($row[1] => array_slice($row, 2)));
            $rtStructs['dtDisplayOrder'][$row[0]] = array();
        } else {
            $rtStructs['typedefs'][$row[0]]['dtFields'][$row[1]] = array_slice($row, 2);
        }
        array_push($rtStructs['dtDisplayOrder'][$row[0]], $row[1]);
    }
    // get rectypes ordered by the RecType Group order, then by Group Name, then by rectype order in group and then by rectype name
    $query = "select rty_ID, rtg_ID, rtg_Name, " . join(",", getRectypeColNames());
    $query = preg_replace("/rty_ConceptID/", "", $query);
    if ($dbID) {
        //if(trm_OriginatingDBID,concat(cast(trm_OriginatingDBID as char(5)),'-',cast(trm_IDInOriginatingDB as char(5))),'null') as trm_ConceptID
        $query .= " if(rty_OriginatingDBID, concat(cast(rty_OriginatingDBID as char(5)),'-',cast(rty_IDInOriginatingDB as char(5))), concat('{$dbID}-',cast(rty_ID as char(5)))) as rty_ConceptID";
    } else {
        $query .= " if(rty_OriginatingDBID, concat(cast(rty_OriginatingDBID as char(5)),'-',cast(rty_IDInOriginatingDB as char(5))), '') as rty_ConceptID";
    }
    $query .= " from defRecTypes left join defRecTypeGroups  on rtg_ID = rty_RecTypeGroupID" . " order by rtg_Order, rtg_Name, rty_OrderInGroup, rty_Name";
    $res = mysql_query($query);
    while ($row = mysql_fetch_row($res)) {
        array_push($rtStructs['groups'][$rtStructs['groups']['groupIDToIndex'][$row[1]]]['allTypes'], $row[0]);
        if ($row[14]) {
            //rty_ShowInList
            array_push($rtStructs['groups'][$rtStructs['groups']['groupIDToIndex'][$row[1]]]['showTypes'], $row[0]);
        }
        $commonFields = array_slice($row, 3);
        $rtStructs['typedefs'][$row[0]]['commonFields'] = $commonFields;
        $rtStructs['names'][$row[0]] = $row[3];
        $rtStructs['pluralNames'][$row[0]] = $row[8];
    }
    $rtStructs['constraints'] = getAllRectypeConstraint();
    setCachedData($cacheKey, $rtStructs);
    return $rtStructs;
}
//10-rst_DisplayDetailTypeGroupID
//11-rst_FilteredJsonTermIDTree
//12-rst_PtrFilteredIDs
//13-rst_TermIDTreeNonSelectableIDs
//14-rst_CalcFunctionID
//15-rst_Status
//16-rst_OrderForThumbnailGeneration
//17-dty_TermIDTreeNonSelectableIDs
//18-dty_FieldSetRectypeID
//19-rst_NonOwnerVisibility]....]
//rst_DisplayName, rst_DisplayHelpText, rst_DisplayExtendedDescription,
// rst_DefaultValue, rst_RequirementType, rst_MaxValues, rst_MinValues, rst_DisplayWidth, rst_RecordMatchOrder,
// rst_DisplayOrder, rst_DisplayDetailTypeGroupID, rst_FilteredJsonTermIDTree, rst_PtrFilteredIDs,
// rst_TermIDTreeNonSelectableIDs, rst_CalcFunctionID, rst_Status, rst_OrderForThumbnailGeneration,
// dty_TermIDTreeNonSelectableIDs, dty_FieldSetRectypeID, rst_NonOwnerVisibility] ...]
$rstC2I = getColumnNameToIndex(getRectypeStructureFieldColNames());
foreach ($rec_types as $rec_type) {
    foreach (getRectypeFields($rec_type) as $dtyID => $rdr) {
        // saw TODO need to represent the trm ids  and rectype pointer ids that are valid for this rectype.detailtype.
        array_push($detailRequirements, array($rec_type, $dtyID, $rstC2I['rst_RequirementType'] ? $rdr[$rstC2I['rst_RequirementType']] : null, $rstC2I['rst_MaxValues'] && $rdr[$rstC2I['rst_MaxValues']] ? intval($rdr[$rstC2I['rst_MaxValues']]) : null, array_key_exists('rst_DisplayName', $rstC2I) ? $rdr[$rstC2I['rst_DisplayName']] : null, $rstC2I['rst_DisplayHelpText'] ? $rdr[$rstC2I['rst_DisplayHelpText']] : null, $rstC2I['rst_RecordMatchOrder'] ? intval($rdr[$rstC2I['rst_RecordMatchOrder']]) : 0, $rstC2I['rst_DisplayWidth'] ? intval($rdr[$rstC2I['rst_DisplayWidth']]) : 0, $rstC2I['rst_DisplayOrder'] ? intval($rdr[$rstC2I['rst_DisplayOrder']]) : 0, $rstC2I['rst_DisplayExtendedDescription'] ? $rdr[$rstC2I['rst_DisplayExtendedDescription']] : null, $rstC2I['rst_DefaultValue'] ? $rdr[$rstC2I['rst_DefaultValue']] : null, $rstC2I['rst_MinValues'] ? intval($rdr[$rstC2I['rst_MinValues']]) : 0, $rstC2I['rst_DisplayDetailTypeGroupID'] ? $rdr[$rstC2I['rst_DisplayDetailTypeGroupID']] : null, $rstC2I['rst_FilteredJsonTermIDTree'] ? $rdr[$rstC2I['rst_FilteredJsonTermIDTree']] : null, $rstC2I['rst_TermIDTreeNonSelectableIDs'] ? $rdr[$rstC2I['rst_TermIDTreeNonSelectableIDs']] : null, $rstC2I['dty_TermIDTreeNonSelectableIDs'] ? $rdr[$rstC2I['dty_TermIDTreeNonSelectableIDs']] : null, $rstC2I['rst_PtrFilteredIDs'] ? $rdr[$rstC2I['rst_PtrFilteredIDs']] : null, $rstC2I['rst_CalcFunctionID'] ? $rdr[$rstC2I['rst_CalcFunctionID']] : null, $rstC2I['rst_OrderForThumbnailGeneration'] ? $rdr[$rstC2I['rst_OrderForThumbnailGeneration']] : null, $rstC2I['rst_Status'] ? $rdr[$rstC2I['rst_Status']] : null, $rstC2I['rst_NonOwnerVisibility'] ? $rdr[$rstC2I['rst_NonOwnerVisibility']] : null));
        //20-Non-Owner Visibility
    }
}
$commonData = array("users" => $users, "workgroups" => $workgroups, "ratings" => array("0" => "not rated", "1" => "*", "2" => "**", "3" => "***", "4" => "****", "5" => "*****"), "recordTypes" => $recordTypes, "detailTypes" => $detailTypes, "detailRequirements" => $detailRequirements, 'max_post_size' => _get_config_bytes(ini_get('post_max_size')), 'max_file_size' => _get_config_bytes(ini_get('upload_max_filesize')));
if (!@$_REQUEST["json"]) {
    print "var HAPI_commonData = ";
}
print json_encode($commonData);
if (!@$_REQUEST["json"]) {
    print ";\n";
}