function getTableList()
{
    global $TABLE_PREFIX, $APP;
    // get table names
    $mysqlTables = getMysqlTablesWithPrefix();
    $schemaTables = getSchemaTables();
    // create multi query
    $tables = array();
    $tableRowCounts = array();
    foreach ($schemaTables as $tableName) {
        $tableNameWithPrefix = getTableNameWithPrefix($tableName);
        if (in_array($tableNameWithPrefix, $mysqlTables)) {
            $rowCount = mysql_count($tableNameWithPrefix);
        }
        $localTableSchema = loadSchema($tableName);
        array_push($tables, array('tableName' => $tableName, 'menuName' => @$localTableSchema['menuName'], 'menuType' => @$localTableSchema['menuType'], 'menuOrder' => @$localTableSchema['menuOrder'], 'menuHidden' => @$localTableSchema['menuHidden'], 'tableHidden' => @$localTableSchema['tableHidden'], '_indent' => @$localTableSchema['_indent'], 'recordCount' => $rowCount));
    }
    // sort table list
    uasort($tables, '_sortMenusByOrder');
    //
    return $tables;
}
function userSectionAccess($tableNameWithoutPrefix)
{
    // added in v2.16
    global $CURRENT_USER;
    $tableName = getTableNameWithoutPrefix($tableNameWithoutPrefix);
    // get access level
    if (@$CURRENT_USER['accessList']['all']['accessLevel'] > 1) {
        $accessLevel = $CURRENT_USER['accessList']['all']['accessLevel'];
    } elseif (@$CURRENT_USER['accessList'][$tableName]['accessLevel']) {
        $accessLevel = @$CURRENT_USER['accessList'][$tableName]['accessLevel'];
    } else {
        $accessLevel = 0;
    }
    // accounts menu (special rules)
    if ($tableName == 'accounts') {
        if (@$CURRENT_USER['isAdmin']) {
            $accessLevel = 9;
        } elseif ($accessLevel < 9) {
            $accessLevel = 0;
        }
        // accounts menu requires admin or editor access
    }
    // don't allow viewer-only access unless section allows it
    if ($accessLevel == 3 || $accessLevel == 7) {
        $schema = loadSchema($tableName);
        if (@$schema['_disableView']) {
            if ($accessLevel == 7) {
                $accessLevel = 6;
            } else {
                $accessLevel = 0;
            }
            // drop viewer only access to no access
        }
    }
    //
    $accessLevel = applyFilters('userSectionAccess', $accessLevel, $tableName);
    return $accessLevel;
}
function getPrevAndNextRecords($options)
{
    global $TABLE_PREFIX;
    // error checking
    $errors = '';
    if (!@$options['tableName']) {
        $errors .= "No 'tableName' value specified in options!<br/>\n";
    }
    if ($errors) {
        die(__FUNCTION__ . ": {$errors}");
    }
    $tableSchema = loadSchema($options['tableName']);
    $mysqlTableName = mysql_escape($TABLE_PREFIX . $options['tableName']);
    $targetNum = @$options['recordNum'] ? mysql_escape($options['recordNum']) : 0;
    $orderBy = @$options['orderBy'] ? $options['orderBy'] : $tableSchema['listPageOrder'];
    // set inital mysql variables
    $query = "SELECT @lastSeenNum:=0, @prevNum:=0, @nextNum:=0, @firstNum:=0, @lastNum:=0, @prevNumSet:=0, @foundTarget:=0";
    if (@$options['debugSql']) {
        print "<xmp>{$query}</xmp>";
    }
    mysql_query($query) or die("MySQL Error: " . htmlencode(mysql_error()) . "\n");
    // get mysql to figure out which nums are prev, next, first, and last
    // NOTE: "The order of evaluation for expressions involving user variables is undefined..." See: http://dev.mysql.com/doc/refman/5.0/en/user-variables.html
    $query = "SELECT \n";
    $query .= "  IF(@firstNum, NULL, @firstNum:=num),\n";
    // get firstRecordNum
    $query .= "  @lastNum := num,\n";
    // get lastRecordNum
    $query .= "  IF(num='{$targetNum}', (@foundTarget:=1) & (@prevNum:=@lastSeenNum), @lastSeenNum:=num),\n";
    // get prevRecordNum (Note that using AND here instead of & caused an issue with unexpected evalutation of the assignment operators on a Windows/MySQL 5.5.33 server)
    $query .= "  IF(@foundTarget=1 AND num !='{$targetNum}' AND @nextNum = 0, @nextNum := num, null)\n";
    // get nextRecordNum
    $query .= "FROM `{$mysqlTableName}` \n";
    if (@$options['where']) {
        $query .= "WHERE {$options['where']} \n";
    }
    $query .= "ORDER BY {$orderBy}  \n";
    if (@$options['debugSql']) {
        print "<xmp>{$query}</xmp>";
    }
    mysql_query($query) or die("MySQL Error: " . htmlencode(mysql_error()) . "\n");
    // load our calculated nums
    $query = "SELECT @prevNum as 'prevRecordNum', @nextNum as 'nextRecordNum', @firstNum as 'firstRecordNum', @lastNum as 'lastRecordNum'";
    if (@$options['debugSql']) {
        print "<xmp>{$query}</xmp>";
    }
    $row = mysql_get_query($query);
    // load records matching returned nums
    $numsToGet = array_values(array_filter($row));
    array_push($numsToGet, 0);
    list($records, $metaData) = getRecords(array('tableName' => $options['tableName'], 'where' => "num IN (" . implode(',', $numsToGet) . ")", 'allowSearch' => false, 'debugSql' => @$options['debugSql']));
    $recordsByNum = array_combine(array_pluck($records, 'num'), $records);
    // package up output
    $firstRecord = $row['firstRecordNum'] ? @$recordsByNum[$row['firstRecordNum']] : array();
    $prevRecord = $row['prevRecordNum'] ? @$recordsByNum[$row['prevRecordNum']] : array();
    $nextRecord = $row['nextRecordNum'] ? @$recordsByNum[$row['nextRecordNum']] : array();
    $lastRecord = $row['lastRecordNum'] ? @$recordsByNum[$row['lastRecordNum']] : array();
    return array($prevRecord, $nextRecord, $firstRecord, $lastRecord);
}
Beispiel #4
0
}
print "\n\nThank you for choosing FreeMED as your electronic medical record / practice\nmanagement system. FreeMED is an opensource program and is located on the\nweb at http://www.freemedsoftware.org/\n\nThis command line tool will allow you to install FreeMED from the Linux\ncommand line. Please make sure that your FreeMED installation is writeable,\notherwise this may cause some *nasty* problems.\n\n";
if (!function_exists('mysql_connect')) {
    print "mysql support needs to be enabled before we can proceed!\n";
    die;
}
printHeader("Include aggregation table definition");
loadSchema('patient');
printHeader("Load admin table definitions");
loadSchema('session');
loadSchema('modules');
loadSchema('user');
loadSchema('config');
loadSchema('scheduler');
printHeader("Install ACL tables");
loadSchema('acl');
// Add the administrative account
printHeader("Add an administrative account");
print "\nPlease enter an username for your administrative account [root] : ";
$username = getInput('%s');
if ($username == "") {
    $username = "******";
}
print "\nPlease enter a password for your administrative account : ";
$password = getInput('%s');
if ($nimode) {
    $username = '******';
    $password = '******';
}
LoadObjectDependency("org.freemedsoftware.public.Installation");
Installation::CreateAdministrationAccount($username, $password);
    function getTableRow($record, $value, $formType)
    {
        global $isMyAccountMenu;
        $parentTable = $GLOBALS['menu'];
        // set field attributes
        $relatedTable = $this->relatedTable;
        $relatedWhere = getEvalOutput(@$this->relatedWhere);
        $seeMoreLink = @$this->relatedMoreLink ? "?menu={$relatedTable}&amp;search=1&amp;_ignoreSavedSearch=1&amp;" . getEvalOutput($this->relatedMoreLink) : '';
        // load list functions
        require_once "lib/menus/default/list_functions.php";
        require_once "lib/viewer_functions.php";
        // save and update globals
        list($originalMenu, $originalTableName, $originalSchema) = array($GLOBALS['menu'], $GLOBALS['tableName'], $GLOBALS['schema']);
        $GLOBALS['menu'] = $relatedTable;
        $GLOBALS['tableName'] = $relatedTable;
        $GLOBALS['schema'] = loadSchema($relatedTable);
        $GLOBALS['schema'] = array_merge($GLOBALS['schema'], getSchemaFields($GLOBALS['schema']));
        // v2.16+, add pseudo-fields name and _tableName to all fieldSchemas.  Doing this once here instead of every time in loadSchema() is less expensive
        // load list data
        list($listFields, $records, $metaData) = list_functions_init(array('isRelatedRecords' => true, 'tableName' => $relatedTable, 'where' => $relatedWhere, 'perPage' => @$this->relatedLimit));
        ### show header
        $html = '';
        $recordCount = count($records);
        $oneOrZero = $recordCount > 0 ? 1 : 0;
        $seeMoreHTML = $seeMoreLink ? "<br/><a href='{$seeMoreLink}'>" . htmlencode(t("see related records >>")) . "</a>" : '';
        $showingText = sprintf(t('Showing %1$s - %2$s of %3$s related records'), $oneOrZero, $recordCount, $metaData['totalRecords']);
        ob_start();
        ?>
<tr><td colspan="2">
  <div class="clear"></div>
  <div class="content-box">

    <div class="content-box-header">
      <div style="float:right; text-align: right; line-height: 110%">
        <?php 
        echo $showingText;
        ?>
        <?php 
        echo $seeMoreHTML;
        ?>
      </div>
      <h3><?php 
        echo $this->label;
        ?>
<!-- --></h3>
      <div class="clear"></div>
    </div> <!-- End .content-box-header -->

    <div class="content-box-content">
<?php 
        $html .= ob_get_clean();
        ### show body
        // show list
        ob_start();
        showListTable($listFields, $records, array('isRelatedRecords' => true, 'showView' => @$this->relatedView, 'showModify' => @$this->relatedModify, 'showErase' => @$this->relatedErase, 'showCreate' => @$this->relatedCreate));
        $html .= ob_get_clean();
        ### get footer
        $buttonsRight = '';
        if (@$this->relatedCreate) {
            // show "create" button for related records
            $buttonsRight = relatedRecordsButton(t('Create'), "?menu={$relatedTable}&action=edit&{$parentTable}Num=###");
        }
        $tableName = $relatedTable;
        $isRelatedTable = true;
        $buttonsRight = applyFilters('list_buttonsRight', $buttonsRight, $tableName, $isRelatedTable);
        $html .= <<<__FOOTER__

    <div style='float:right; padding-top: 3px'>
    {$buttonsRight}
    </div>
    <div class='clear'></div>

    </div><!-- End .content-box-content -->
  </div><!-- End .content-box -->
</td></tr>
__FOOTER__;
        // reset globals
        list($GLOBALS['menu'], $GLOBALS['tableName'], $GLOBALS['schema']) = array($originalMenu, $originalTableName, $originalSchema);
        //
        return $html;
    }
function _getMenuList()
{
    global $APP, $CURRENT_USER;
    $menus = array();
    $selectedMenu = getFirstDefinedValue(@$APP['selectedMenu'], @$_REQUEST['menu'], 'home');
    $menuOrder = 0;
    // get schema files
    foreach (getSchemaTables() as $tableName) {
        $schema = loadSchema($tableName);
        if (!@$schema['menuType']) {
            continue;
        }
        if (@$schema['menuHidden']) {
            continue;
        }
        $menuOrder = max($menuOrder, @$schema['menuOrder']);
        // add menu items
        $thisMenu = array();
        $thisMenu['schema'] = $schema;
        $thisMenu['menuType'] = $schema['menuType'];
        $thisMenu['menuName'] = $schema['menuName'];
        $thisMenu['menuOrder'] = $schema['menuOrder'];
        $thisMenu['tableName'] = $tableName;
        $thisMenu['isSelected'] = $selectedMenu == $tableName;
        $thisMenu['_indent'] = @$schema['_indent'];
        $thisMenu['_disableView'] = @$schema['_disableView'];
        $thisMenu['link'] = "?menu={$tableName}";
        $thisMenu['linkTarget'] = '';
        $thisMenu['linkMessage'] = '';
        if ($schema['menuType'] == 'link') {
            $isExternalLink = @$schema['_linkTarget'] != 'iframe';
            $setTargetBlank = $isExternalLink && (@$schema['_targetBlank'] || @$schema['_linkTarget'] == 'new');
            // _targetBlank is the old schema format
            if ($isExternalLink) {
                $thisMenu['link'] = $schema['_url'];
            }
            if ($setTargetBlank) {
                $thisMenu['linkTarget'] = 'target="_blank"';
            }
            if ($isExternalLink) {
                $thisMenu['linkMessage'] = @$schema['_linkMessage'];
            }
            // don't show js alert() for iframe links (show them at top of iframe page)
        }
        array_push($menus, $thisMenu);
    }
    // add admin menus
    $showAdminAtTop = false;
    if ($showAdminAtTop) {
        $menuOrder = -100;
    }
    $menus = array_merge($menus, _getAdminMenus($menuOrder));
    // sort menus by order value
    uasort($menus, '_sortMenusByOrder');
    $menus = array_values($menus);
    // re-index elements to match sort order (for operation below)
    // allow plugins to customize the menu while it's still an easily managable array
    $menus = applyFilters('menulinks_array', $menus);
    // set isSelected for menuGroups
    $groupChildSelected = false;
    for ($index = count($menus) - 1; $index >= 0; $index--) {
        $menu =& $menus[$index];
        if ($menu['menuType'] == 'menugroup') {
            if ($groupChildSelected) {
                $menu['isSelected'] = true;
                $groupChildSelected = false;
            }
        } else {
            if ($menu['isSelected']) {
                $groupChildSelected = true;
            }
        }
        unset($menu);
    }
    //
    return $menus;
}
function getUploads($tableName, $fieldName, $recordNum)
{
    global $TABLE_PREFIX;
    $uploads = array();
    // error checking
    if (!$tableName) {
        die(__FUNCTION__ . ": no 'tableName' value specified!");
    }
    if (!$fieldName) {
        die(__FUNCTION__ . ": no 'fieldName' value specified!");
    }
    if (!$recordNum) {
        die(__FUNCTION__ . ": no 'recordNum' value specified!");
    }
    // get record uploads
    $tableNameWithoutPrefix = getTableNameWithoutPrefix($tableName);
    $query = "   SELECT * FROM `{$TABLE_PREFIX}uploads` ";
    $query .= "    WHERE tableName = '" . mysql_escape($tableNameWithoutPrefix) . "' AND ";
    $query .= "          fieldName = '" . mysql_escape($fieldName) . "' AND";
    $query .= "          recordNum = '" . mysql_escape($recordNum) . "'";
    $query .= " ORDER BY `order`, num";
    $result = mysql_query($query) or die("MySQL Error: " . htmlencode(mysql_error()) . "\n");
    //
    $schema = loadSchema($tableName);
    while ($upload = mysql_fetch_assoc($result)) {
        _addUploadPseudoFields($upload, $schema, $fieldName);
        array_push($uploads, $upload);
    }
    return $uploads;
}
function cg2_listpage_getCode()
{
    $tableName = @$_REQUEST['tableName'];
    $schema = loadSchema($tableName);
    $menuName = coalesce(@$schema['menuName'], $tableName);
    // define variable names
    $tableRecordsVar = '$' . preg_replace("/[^\\w]/", '_', $tableName) . "Records";
    $metaDataVar = '$' . preg_replace("/[^\\w]/", '_', $tableName) . "MetaData";
    $recordVar = '$record';
    // define getRecords() options
    $options = array();
    $options[] = "'tableName'   => '{$tableName}',";
    if (@$_REQUEST['howMany'] == 'firstN') {
        $options[] = "'limit'       => '{$_REQUEST['limit']}',";
    } else {
        if (@$_REQUEST['howMany'] == 'paged') {
            $options[] = "'perPage'     => '{$_REQUEST['perPage']}',";
        } else {
            /* default to showing all */
        }
    }
    if (@$_REQUEST['orderBy'] == 'random') {
        $options[] = "'orderBy'     => 'RAND()',";
    }
    if (@$_REQUEST['showUploads'] == 'all') {
        $options[] = "'loadUploads' => true,";
    } elseif (@$_REQUEST['showUploads'] == 'limit') {
        $options[] = "'loadUploads' => true,";
    } else {
        $options[] = "'loadUploads' => false,";
    }
    if (@$_REQUEST['allowSearching']) {
        $options[] = "'allowSearch' => true,";
    } else {
        $options[] = "'allowSearch' => false,";
    }
    $padding = "    ";
    $getRecordsOptions = "\n{$padding}" . implode("\n{$padding}", $options) . "\n  ";
    ### generate code
    ob_start();
    ?>
<#php header('Content-type: text/html; charset=utf-8'); #>
<#php
  /* STEP 1: LOAD RECORDS - Copy this PHP code block near the TOP of your page */
  <?php 
    cg2_code_loadLibraries();
    ?>

  // load records from '<?php 
    echo $tableName;
    ?>
'
  list(<?php 
    echo $tableRecordsVar;
    ?>
, <?php 
    echo $metaDataVar;
    ?>
) = getRecords(array(<?php 
    echo $getRecordsOptions;
    ?>
));

#><?php 
    cg2_code_header();
    cg2_code_instructions('List');
    ?>

  <!-- STEP2: Display Records (Paste this where you want your records to be listed) -->
    <h1><?php 
    echo $menuName;
    ?>
 - <?php 
    echo t('List Page Viewer');
    ?>
</h1>
    <#php foreach (<?php 
    echo $tableRecordsVar;
    ?>
 as <?php 
    echo $recordVar;
    ?>
): #>
<?php 
    cg2_code_schemaFields($schema, $recordVar, $tableName);
    if (@$_REQUEST['showUploads']) {
        cg2_code_uploads($schema, $recordVar);
    }
    ?>
      <hr/>
    <#php endforeach #>

    <#php if (!<?php 
    echo $tableRecordsVar;
    ?>
): #>
      <?php 
    echo t('No records were found!');
    ?>
<br/><br/>
    <#php endif #>
  <!-- /STEP2: Display Records -->

<?php 
    if (@$_REQUEST['howMany'] == 'paged') {
        ?>
  <!-- STEP3: Display Page Links (Paste anywhere below "Load Record List") -->
    <#php if (<?php 
        echo $metaDataVar;
        ?>
['prevPage']): #>
      <a href="<#php echo <?php 
        echo $metaDataVar;
        ?>
['prevPageLink'] #>"><?php 
        echo t('&lt;&lt;  prev');
        ?>
</a>
    <#php else: #>
      &lt;&lt; prev
    <#php endif #>

    - page <#php echo <?php 
        echo $metaDataVar;
        ?>
['page'] #> of <#php echo <?php 
        echo $metaDataVar;
        ?>
['totalPages'] #> -

    <#php if (<?php 
        echo $metaDataVar;
        ?>
['nextPage']): #>
      <a href="<#php echo <?php 
        echo $metaDataVar;
        ?>
['nextPageLink'] #>"><?php 
        echo t('next');
        ?>
 &gt;&gt;</a>
    <#php else: #>
      next &gt;&gt;
    <#php endif #>
  <!-- /STEP3: Display Page Links -->
<?php 
    }
    cg2_code_footer();
    ?>

<?php 
    // return code
    $code = ob_get_clean();
    return $code;
}
function getSchemaPresets()
{
    global $APP;
    $schemaPresets = array();
    // get schema tablenames
    $schemaTables = array();
    $schemaPresetDir = DATA_DIR . '/schemaPresets/';
    foreach (getSchemaTables($schemaPresetDir) as $tableName) {
        $tableSchema = loadSchema($tableName, $schemaPresetDir);
        $menuName = @$tableSchema['menuName'] ? $tableSchema['menuName'] : $tableName;
        $schemaPresets[$tableName] = @$tableSchema['menuName'];
    }
    return $schemaPresets;
}
    function getTableRow($record, $value, $formType)
    {
        global $TABLE_PREFIX;
        // load access list
        $accessList = array();
        if (@$_REQUEST['num']) {
            $query = "SELECT * FROM `{$TABLE_PREFIX}_accesslist` WHERE userNum = '" . mysql_escape($_REQUEST['num']) . "'";
            $result = mysql_query($query) or die("MySQL Error: " . htmlencode(mysql_error()) . "\n");
            while ($record = mysql_fetch_assoc($result)) {
                $accessList[$record['tableName']] = $record;
            }
        }
        // get section list
        $sectionList = array();
        foreach (getSchemaTables() as $tableName) {
            $schema = loadSchema($tableName);
            $allowedMenuTypes = array('single', 'multi', 'category', 'menugroup', 'link', 'custom');
            if (!in_array(@$schema['menuType'], $allowedMenuTypes)) {
                continue;
            }
            $thisMenu = array();
            $thisMenu['menuName'] = htmlencode($schema['menuName']);
            if (@$schema['menuType'] != 'menugroup') {
                $thisMenu['menuName'] = '&nbsp; &nbsp; &nbsp;' . $thisMenu['menuName'];
            }
            if (@$schema['_indent']) {
                $thisMenu['menuName'] = '&nbsp; &nbsp; &nbsp;' . $thisMenu['menuName'];
            }
            $thisMenu['menuOrder'] = $schema['menuOrder'];
            $thisMenu['tableName'] = $tableName;
            $thisMenu['menuType'] = $schema['menuType'];
            array_push($sectionList, $thisMenu);
        }
        uasort($sectionList, '_sortMenusByOrder');
        // sort menus by order value
        // display field
        $allAccessLevel = @$accessList['all']['accessLevel'];
        $sectionsDivStyle = $allAccessLevel != 1 ? "display: none;" : '';
        //
        ob_start();
        ?>
 <tr>
  <td valign="top" style="padding-top: 2px"><?php 
        echo $this->label;
        ?>
</td>
  <td>

<table border="0" cellspacing="1" cellpadding="0">
<thead>
<tr>
<th width="305"><?php 
        et('Section Name');
        ?>
</th>
<th width="115" style="text-align: center"><?php 
        et('Access');
        ?>
</th>
<th width="100" style="text-align: center"><?php 
        et('Max Records');
        ?>
</th>
</tr>
</thead>
<tr>
<td class="listRow listRowOdd"><?php 
        et('All Sections');
        ?>
</td>
<td class="listRow listRowOdd" style="text-align: center">
  <select name="accessList[all][accessLevel]" style="width: 140px" onchange="(this.value=='1') ? $('.sectionAccessList').slideDown() : $('.sectionAccessList').slideUp();">
  <option value="0" <?php 
        selectedIf($allAccessLevel, '0');
        ?>
><?php 
        et('None');
        ?>
</option>
  <option value="3" <?php 
        selectedIf($allAccessLevel, '3');
        ?>
><?php 
        et('Viewer');
        ?>
</option>
  <option value="6" <?php 
        selectedIf($allAccessLevel, '6');
        ?>
><?php 
        et('Author');
        ?>
</option>
  <option value="7" <?php 
        selectedIf($allAccessLevel, '7');
        ?>
><?php 
        eht('Author & Viewer');
        ?>
</option>
  <option value="9" <?php 
        selectedIf($allAccessLevel, '9');
        ?>
><?php 
        et('Editor');
        ?>
</option>
  <option value="1" <?php 
        selectedIf($allAccessLevel, '1');
        ?>
><?php 
        et('By Section');
        ?>
</option>
  </select>
</td>
<td class="listRow listRowOdd" style="text-align: center"><?php 
        et('No Limit');
        ?>
</td>
</tr>
</table>

<script type="text/javascript">
function toggleDisabledForAccessListMaxRecords(tablename) {
var accessLevel = $("#accesslevel_"+tablename).val();
var disableMaxRecords = (accessLevel == 9 || accessLevel == 3);
if (disableMaxRecords) { $("#maxRecords_"+tablename).attr("disabled", true).css("background-color","#DDD");  }
else                   { $("#maxRecords_"+tablename).removeAttr("disabled").css("background-color","#FFF");  }
}
</script>

<div class="sectionAccessList" style="<?php 
        echo $sectionsDivStyle;
        ?>
">
<div style="width: 0px; height: 0px;"></div><?php 
        /* fixes IE7 issue which caused table to get no layout space, causing overlap and missing table content. the issue seems to be caused by a div with only a table inside. adding anything else inside the div seems to fix it, including &nbsp, but that adds extra whitespace, hence the div with no area */
        ?>
<table border="0" cellspacing="1" cellpadding="0">

<?php 
        // list sections
        foreach ($sectionList as $section) {
            $bgColorClass = @$bgColorClass == "listRowEven" ? 'listRowOdd' : 'listRowEven';
            # rotate bgclass
            $fieldnamePrefix = "accessList[{$section['tableName']}]";
            $accessLevel = @$accessList[$section['tableName']]['accessLevel'];
            $maxRecords = @$accessList[$section['tableName']]['maxRecords'];
            $disableMaxRecords = $accessLevel == 9 || $accessLevel == 3;
            $maxRecordsAttr = $disableMaxRecords ? 'style="text-align: center; background-color: #DDD;" disabled="disabled"' : 'style="text-align: center;"';
            ?>
<tr>
<td class="listRow <?php 
            echo $bgColorClass;
            ?>
" width="305">&nbsp;&nbsp;&nbsp;&nbsp;<?php 
            echo $section['menuName'];
            ?>
</td>
<td class="listRow <?php 
            echo $bgColorClass;
            ?>
" width="115" style="text-align: center">
<?php 
            if ($section['menuType'] == 'single' || $section['tableName'] == 'accounts' || $section['menuType'] == 'menugroup' || $section['menuType'] == 'link') {
                ?>
<input type="hidden"   name="<?php 
                echo $fieldnamePrefix;
                ?>
[accessLevel]" value="0" />
<input type="checkbox" name="<?php 
                echo $fieldnamePrefix;
                ?>
[accessLevel]" value="9" <?php 
                checkedIf($accessLevel, '9');
                ?>
 />
<?php 
            } elseif ($section['menuType'] == 'multi') {
                ?>
  <select name="<?php 
                echo $fieldnamePrefix;
                ?>
[accessLevel]" id="accesslevel_<?php 
                echo $section['tableName'];
                ?>
" style="width: 140px" onchange="toggleDisabledForAccessListMaxRecords('<?php 
                echo $section['tableName'];
                ?>
')">
  <option value="0" <?php 
                selectedIf($accessLevel, '0');
                ?>
><?php 
                et('None');
                ?>
</option>
  <option value="3" <?php 
                selectedIf($accessLevel, '3');
                ?>
><?php 
                et('Viewer');
                ?>
</option>
  <option value="6" <?php 
                selectedIf($accessLevel, '6');
                ?>
><?php 
                et('Author');
                ?>
</option>
  <option value="7" <?php 
                selectedIf($accessLevel, '7');
                ?>
><?php 
                eht('Author & Viewer');
                ?>
</option>
  <option value="9" <?php 
                selectedIf($accessLevel, '9');
                ?>
><?php 
                et('Editor');
                ?>
</option>
  </select>
<?php 
            } elseif ($section['menuType'] == 'category') {
                ?>
  <select name="<?php 
                echo $fieldnamePrefix;
                ?>
[accessLevel]" id="accesslevel_<?php 
                echo $section['tableName'];
                ?>
" style="width: 140px" onchange="toggleDisabledForAccessListMaxRecords('<?php 
                echo $section['tableName'];
                ?>
')">
  <option value="0" <?php 
                selectedIf($accessLevel, '0');
                ?>
><?php 
                et('None');
                ?>
</option>
  <option value="9" <?php 
                selectedIf($accessLevel, '9');
                ?>
><?php 
                et('Editor');
                ?>
</option>
  </select>
<?php 
            }
            ?>

</td>
<td class="<?php 
            echo $bgColorClass;
            ?>
" width="100" style="text-align: center">


<?php 
            if ($section['menuType'] == 'single') {
                printf(t("Single Page"));
            } elseif ($section['tableName'] == 'accounts') {
                ?>

<?php 
            } elseif ($section['menuType'] == 'multi') {
                ?>
  <input class="text-input medium-input" type="text" name="<?php 
                echo $fieldnamePrefix;
                ?>
[maxRecords]" id="maxRecords_<?php 
                echo $section['tableName'];
                ?>
"
         value="<?php 
                echo $maxRecords;
                ?>
" size="6" maxlength="6"
         <?php 
                echo $maxRecordsAttr;
                ?>
 />
<?php 
            }
            ?>
</td>

</tr>
<?php 
        }
        ?>

</table></div>


<br/><div style="font-size: 11px">
  <b><?php 
        et('Access Levels:');
        ?>
</b><br/>
  <div style="padding-left: 20px;">
    <?php 
        et('None - Don\'t allow user to access this section');
        ?>
<br/>
    <?php 
        et('Viewer - User can view any record in this section (must also be enabled in section editor)');
        ?>
<br/>
    <?php 
        et('Author - User can only access records they have created');
        ?>
<br/>
    <?php 
        eht("Author & Viewer - User can view any record and modify records they've created");
        ?>
<br/>
    <?php 
        et('Editor - User can access any records in this section');
        ?>
<br/>
  </div>
  <?php 
        et('Max Records: Max records user is allowed to create (for regular users only - leave blank for unlimited)');
        ?>
</div>

  </td>
 </tr>

<?php 
        $html = ob_get_clean();
        return $html;
    }
function cg2_inputSchemaField_getOptions($tableName, $fieldname = '')
{
    if (!$tableName) {
        return "<option value=''>" . htmlencode(t("<select section first>")) . "</option>\n";
    }
    $fieldnames = array();
    $validTypes = array('textfield', 'textbox', 'wysiwyg');
    $schema = loadSchema($tableName);
    $fieldSchemas = array_filter($schema, 'is_array');
    foreach ($fieldSchemas as $name => $fieldSchema) {
        if (!in_array(@$fieldSchema['type'], $validTypes)) {
            continue;
        }
        $fieldnames[] = $name;
    }
    // get options HTML
    $htmlOptions = "<option value=''>&lt;select field&gt;</option>\n";
    $htmlOptions .= getSelectOptions(@$_REQUEST[$fieldname], $fieldnames);
    return $htmlOptions;
}
function cg2_categorypage_getCode()
{
    $tableName = @$_REQUEST['tableName'];
    $schema = loadSchema($tableName);
    $menuName = coalesce(@$schema['menuName'], $tableName);
    // define variable names
    $categoryRecordsVar = '$' . preg_replace("/[^\\w]/", '_', $tableName) . "Records";
    $selectedCategoryVar = '$selected' . ucfirst(preg_replace("/[^\\w]/", '_', $tableName));
    $categoryRecordVar = '$categoryRecord';
    ### generate code
    ob_start();
    ?>
<#php header('Content-type: text/html; charset=utf-8'); #>
<#php
  /* STEP 1: LOAD RECORDS - Copy this PHP code block near the TOP of your page */
<?php 
    cg2_code_loadLibraries();
    ?>

  // load records from '<?php 
    echo $tableName;
    ?>
'
  list(<?php 
    echo $categoryRecordsVar;
    ?>
, <?php 
    echo $selectedCategoryVar;
    ?>
) = getCategories(array(
    'tableName'            => '<?php 
    echo $tableName;
    ?>
', //
    'categoryFormat'       => '<?php 
    echo $_REQUEST['categoryFormat'];
    ?>
',  // showall, onelevel, twolevel, breadcrumb
    'defaultCategory'      => '<?php 
    echo $_REQUEST['defaultCategory'] == 'num' ? $_REQUEST['defaultCategoryNum'] : $_REQUEST['defaultCategory'];
    ?>
',    // Enter 'first', a category number, or leave blank '' for none
    
    // advanced options (you can safely ignore these)
    'rootCategoryNum'      => '<?php 
    echo $_REQUEST['rootCategoryNum'];
    ?>
',      // Only categories _below_ this one will be shown (defaults to blank or 0 for all)
    'ulAttributes'         => '',      // add html attributes to <ul> tags, eg: 'class="menuUL"' would output <ul class="menuUL">
    'selectedCategoryNum'  => '',      // this record number is returned as the "selected category", defaults to getLastNumberInUrl()
    'ulAttributesCallback' => '',      // ADVANCED: custom function to return ul attributes, eg: 'myUlAttr' and function myUlAttr($category) { return "id='ul_uniqueId_{$category['num']}'"; }
    'liAttributesCallback' => '',      // ADVANCED: custom function to return li attributes, eg: 'myLiAttr' and function myLiAttr($category) { return "id='li_uniqueId_{$category['num']}'"; }
    'loadCreatedBy'        => false,   // loads createdBy.* fields for user who created category record (false is faster)
    'loadUploads'          => true,    // loads upload fields, eg: $category['photos'] gets defined with array of uploads (false is faster)
    'ignoreHidden'         => false,   // false = hide records with 'hidden' flag set, true = ignore status of hidden flag when loading records
    'debugSql'             => false,   // display the MySQL query being used to load records (for debugging)
  ));

#><?php 
    cg2_code_header();
    cg2_code_instructions('Category');
    ?>

<table border="1" cellspacing="0" cellpadding="2" width="100%">
  <tr>
    <td valign="top" width="200">

    <?php 
    if (@$_REQUEST['outputHtmlStyle'] == 'list') {
        ?>
    
      <h3>Category Menu</h3>
      <ul>
        <#php foreach (<?php 
        echo $categoryRecordsVar;
        ?>
 as <?php 
        echo $categoryRecordVar;
        ?>
): #>
          <#php echo <?php 
        echo $categoryRecordVar;
        ?>
['_listItemStart'] #>
      
          <#php if (<?php 
        echo $categoryRecordVar;
        ?>
['_isSelected']): #>
            <b><a href="<#php echo <?php 
        echo $categoryRecordVar;
        ?>
['_link'] #>"><#php echo <?php 
        echo $categoryRecordVar;
        ?>
['name'] #></a></b>
          <#php else: #>
            <a href="<#php echo <?php 
        echo $categoryRecordVar;
        ?>
['_link'] #>"><#php echo <?php 
        echo $categoryRecordVar;
        ?>
['name'] #></a>
          <#php endif; #>
      
          <#php echo <?php 
        echo $categoryRecordVar;
        ?>
['_listItemEnd'] #>
        <#php endforeach; #>
      </ul>
    <?php 
    } else {
        ?>
    
      <h3>Category Menu</h3>
      <#php foreach (<?php 
        echo $categoryRecordsVar;
        ?>
 as <?php 
        echo $categoryRecordVar;
        ?>
): #>
        <#php echo str_repeat("&nbsp; &nbsp; &nbsp;", <?php 
        echo $categoryRecordVar;
        ?>
['depth']); #>
      
        <#php if (<?php 
        echo $categoryRecordVar;
        ?>
['_isSelected']): #><b><#php endif; #>
        <a href="<#php echo <?php 
        echo $categoryRecordVar;
        ?>
['_link'] #>"><#php echo <?php 
        echo $categoryRecordVar;
        ?>
['name'] #></a>
        <#php if (<?php 
        echo $categoryRecordVar;
        ?>
['_isSelected']): #></b><#php endif; #>
      
        <br/>
      <#php endforeach; #>
    
    <?php 
    }
    ?>

    </td>
    <td valign="top">
      
      <h3>Selected Category</h3>
      
    <#php if (!<?php 
    echo $selectedCategoryVar;
    ?>
): #>
      <?php 
    echo t('No category is selected!');
    ?>
<br/>
    <#php endif #>

    <#php if (<?php 
    echo $selectedCategoryVar;
    ?>
): #>
<?php 
    cg2_code_schemaFields($schema, $selectedCategoryVar, $tableName);
    cg2_code_uploads($schema, $selectedCategoryVar);
    ?>
    <#php endif #>

    <#php if (<?php 
    echo $selectedCategoryVar;
    ?>
): #>
    <div class="instructions">
      <b>Advanced Code Snippets and Field List</b> (you can safely remove this section)</b><br/>
      <#php
        $selectedNum     = intval($selectedCategory['num']);
        $recordsOnBranch = mysql_select('category', "lineage LIKE '%:$selectedNum:%'");
        $branchNums      = array_pluck($recordsOnBranch, 'num');
        $branchNumsAsCSV = mysql_getValuesAsCSV($branchNums);
      #>
      Selected category num: <#php echo $selectedCategory['num']; #><br/>
      All nums in branch: <#php echo $branchNumsAsCSV; #><br/>
      All fields available for the selected record:<br/>
      <div style="margin-left: 25px; font-family: monospace">
        <#php echo nl2br(str_replace('  ', ' &nbsp;', htmlencode(print_r($selectedCategory, true)))); #>
      </div>
    </div>
    <#php endif #>

      
      <br/><br/>
    </td>
  </tr>
</table>


<?php 
    cg2_code_footer();
    ?>

<?php 
    // return code
    $code = ob_get_clean();
    return $code;
}
<?php

// load libraries
require_once "lib/menus/default/common.php";
require_once file_exists('lib/wysiwyg_custom.php') ? 'lib/wysiwyg_custom.php' : 'lib/wysiwyg.php';
// set globals
global $TABLE_PREFIX, $tableName, $escapedTableName, $action, $schema, $CURRENT_USER, $hasEditorAccess, $hasAuthorAccess, $hasViewerAccess, $hasViewerAccessOnly, $hasAuthorViewerAccess, $isMyAccountMenu, $isSingleMenu;
$isMyAccountMenu = $menu == '_myaccount';
$tableName = $isMyAccountMenu ? 'accounts' : $menu;
$schema = loadSchema($tableName);
$schema = array_merge($schema, getSchemaFields($schema));
// v2.16+, add pseudo-fields name and _tableName to all fieldSchemas.  Doing this once here instead of every time in loadSchema() is less expensive
$escapedTableName = mysql_escape($TABLE_PREFIX . $tableName);
$hasEditorAccess = userSectionAccess($tableName) >= 9;
$hasAuthorAccess = userSectionAccess($tableName) >= 6;
$hasViewerAccess = userSectionAccess($tableName) >= 3;
$hasViewerAccessOnly = userSectionAccess($tableName) == 3;
$hasAuthorViewerAccess = userSectionAccess($tableName) >= 7;
$isSingleMenu = @$schema['menuType'] == 'single';
// get action
if ($isSingleMenu && $hasAuthorAccess) {
    $_defaultAction = 'edit';
} elseif ($isSingleMenu && $hasViewerAccess) {
    $_defaultAction = 'view';
} else {
    $_defaultAction = 'list';
}
$action = getRequestedAction($_defaultAction);
//
doAction('section_init', $tableName, $action);
//
function recreateThumbnails()
{
    global $TABLE_PREFIX;
    $tableNameWithoutPrefix = getTablenameWithoutPrefix($_REQUEST['tablename']);
    // error checking
    $stopPrefix = "STOPJS:";
    // this tells javascript to stop creating thumbnails
    $requiredFields = array('tablename', 'fieldname', 'maxHeight', 'maxWidth');
    foreach ($requiredFields as $fieldname) {
        if (!@$_REQUEST[$fieldname]) {
            die($stopPrefix . "Required fieldname '{$fieldname}' not specified!");
        }
    }
    if (preg_match('/[^0-9\\_]/i', $_REQUEST['maxHeight'])) {
        die($stopPrefix . "Invalid value for max height!\n");
    }
    if (preg_match('/[^0-9\\_]/i', $_REQUEST['maxWidth'])) {
        die($stopPrefix . "Invalid value for max width!\n");
    }
    // get upload count
    static $count;
    if ($count == '') {
        $where = mysql_escapef("tableName = ? AND fieldName = ?", $tableNameWithoutPrefix, $_REQUEST['fieldname']);
        $totalUploads = mysql_count('uploads', $where);
    }
    // load upload
    $whereEtc = mysql_escapef("tableName = ? AND fieldname = ?", $tableNameWithoutPrefix, $_REQUEST['fieldname']);
    $whereEtc .= " LIMIT 1 OFFSET " . intval($_REQUEST['offset']);
    @(list($upload) = mysql_select('uploads', $whereEtc));
    //
    if ($upload) {
        // get uploadDir and uploadUrl
        $schema = loadSchema($upload['tableName']);
        list($uploadDir, $uploadUrl) = getUploadDirAndUrl($schema[$upload['fieldName']]);
        // get upload's absolute filepath
        $absoluteFilepath = addUploadPathPrefix($upload['filePath'], $uploadDir);
        // make path absolute
        // error checking
        if (!file_exists($absoluteFilepath)) {
            $error = "Upload doesn't exist '{$absoluteFilepath}'!<br/>\n";
            $error .= "Found in: {$upload['tableName']}, {$upload['fieldName']}, record {$upload['recordNum']}.";
            die($error);
        }
        ### resize image
        $isImage = preg_match("/\\.(gif|jpg|jpeg|png)\$/i", $absoluteFilepath);
        if ($isImage) {
            $thumbNum = $_REQUEST['thumbNum'];
            $thumbSavePath = preg_replace("|([^/]+)\$|", "thumb{$thumbNum}/\$1", $absoluteFilepath);
            $thumbUrlPath = preg_replace("|([^/]+)\$|", "thumb{$thumbNum}/\$1", $upload['urlPath']);
            // erase old thumbnail
            if (file_exists($thumbSavePath)) {
                @unlink($thumbSavePath) || die("Can't erase old thumbnail '{$thumbSavePath}': {$php_errormsg}");
            }
            // create new thumbnail
            list($thumbWidth, $thumbHeight) = saveResampledImageAs($thumbSavePath, $absoluteFilepath, $_REQUEST['maxWidth'], $_REQUEST['maxHeight']);
            doAction('upload_thumbnail_save', array($tableNameWithoutPrefix, $_REQUEST['fieldname'], $thumbNum, $thumbSavePath));
            // update upload database
            $query = "UPDATE `{$TABLE_PREFIX}uploads`\n";
            $query .= "   SET `thumbFilepath{$thumbNum}` = '" . mysql_escape(removeUploadPathPrefix($thumbSavePath, $uploadDir)) . "',\n";
            $query .= "       `thumbUrlPath{$thumbNum}`  = '" . mysql_escape(removeUploadPathPrefix($thumbUrlPath, $uploadUrl)) . "',\n";
            $query .= "       `thumbWidth{$thumbNum}`    = '" . mysql_escape($thumbWidth) . "',\n";
            $query .= "       `thumbHeight{$thumbNum}`   = '" . mysql_escape($thumbHeight) . "'\n";
            $query .= " WHERE num = '" . mysql_escape($upload['num']) . "'";
            mysql_query($query) or die("MySQL Error: " . htmlencode(mysql_error()) . "\n");
        }
    }
    // print status message
    $offset = $_REQUEST['offset'] + 1;
    if ($offset <= $totalUploads) {
        print "{$offset}/{$totalUploads}";
    } else {
        print "done";
    }
    exit;
}
function cg2_combopage_getCode()
{
    $tableName = @$_REQUEST['tableName'];
    $schema = loadSchema($tableName);
    $menuName = coalesce(@$schema['menuName'], $tableName);
    // define variable names
    $tableRecordsVar = '$' . preg_replace("/[^\\w]/", '_', $tableName) . "Records";
    $metaDataVar = '$' . preg_replace("/[^\\w]/", '_', $tableName) . "MetaData";
    $listRecordVar = '$listRecord';
    $detailRecordVar = '$detailRecord';
    // list records - define getRecords() options
    $options = array();
    $options[] = "'tableName'   => '{$tableName}',";
    if (@$_REQUEST['howMany'] == 'firstN') {
        $options[] = "'limit'       => '{$_REQUEST['limit']}',";
    }
    $options[] = "'loadUploads' => false,";
    $options[] = "'allowSearch' => false,";
    $padding = "    ";
    $listRecordsOptions = "\n{$padding}" . implode("\n{$padding}", $options) . "\n  ";
    // detail record - define getRecords() options
    $options = array();
    $options[] = "'tableName'   => '{$tableName}',";
    $options[] = "'where'       => whereRecordNumberInUrl(1), // If no record # is specified then latest record is shown";
    if (@$_REQUEST['showUploads'] == 'all') {
        $options[] = "'loadUploads' => true,";
    } elseif (@$_REQUEST['showUploads'] == 'limit') {
        $options[] = "'loadUploads' => true,";
    } else {
        $options[] = "'loadUploads' => false,";
    }
    $options[] = "'allowSearch' => false,";
    $options[] = "'limit'       => '1',";
    $detailRecordOptions = "\n{$padding}" . implode("\n{$padding}", $options) . "\n  ";
    ### generate code
    ob_start();
    ?>
<#php header('Content-type: text/html; charset=utf-8'); #>
<#php
  /* STEP 1: LOAD RECORDS - Copy this PHP code block near the TOP of your page */
  <?php 
    cg2_code_loadLibraries();
    ?>

  // load detail record from '<?php 
    echo $tableName;
    ?>
'
  list(<?php 
    echo $tableRecordsVar;
    ?>
, <?php 
    echo $metaDataVar;
    ?>
) = getRecords(array(<?php 
    echo $detailRecordOptions;
    ?>
));
  <?php 
    echo $detailRecordVar;
    ?>
 = @<?php 
    echo $tableRecordsVar;
    ?>
[0]; // get first record
  if (!<?php 
    echo $detailRecordVar;
    ?>
) { dieWith404("Record not found!"); } // show error message if no record found

  // load list records from '<?php 
    echo $tableName;
    ?>
'
  list(<?php 
    echo $tableRecordsVar;
    ?>
, <?php 
    echo $metaDataVar;
    ?>
) = getRecords(array(<?php 
    echo $listRecordsOptions;
    ?>
));

#><?php 
    cg2_code_header();
    cg2_code_instructions('Combo');
    ?>

<h1><?php 
    echo $menuName;
    ?>
 - <?php 
    echo t('Combo Page Viewer');
    ?>
</h1>

<table border="1" cellspacing="2" cellpadding="4">
 <tr>
  <td valign="top">

  <!-- STEP2: Display Record List (Paste this where you want your record list) -->
    <b>Record List</b><br/>

    <#php foreach (<?php 
    echo $tableRecordsVar;
    ?>
 as <?php 
    echo $listRecordVar;
    ?>
): #>
      <#php $isSelected = (<?php 
    echo $listRecordVar;
    ?>
['num'] == <?php 
    echo $detailRecordVar;
    ?>
['num']); #>
      <#php if ($isSelected) { print "<b>"; } #>
      <a href="<#php echo htmlencode(<?php 
    echo $listRecordVar;
    ?>
['_link']) #>"><#php echo htmlencode(<?php 
    echo $listRecordVar;
    ?>
['<?php 
    echo @$_REQUEST['titleField'];
    ?>
']) #></a><br/>
      <#php if ($isSelected) { print "</b>"; } #>
    <#php endforeach #>

    <#php if (!<?php 
    echo $tableRecordsVar;
    ?>
): #>
      No records were found!<br/><br/>
    <#php endif #>
  <!-- /STEP2: Display Record List -->

  </td>
  <td valign="top">

  <!-- STEP2: Display Record Detail (Paste this where you want your record details) -->
    <b>Record Detail</b><br/>
<?php 
    cg2_code_schemaFields($schema, $detailRecordVar, $tableName);
    if (@$_REQUEST['showUploads']) {
        cg2_code_uploads($schema, $detailRecordVar);
    }
    ?>

  <a href="mailto:?subject=<#php echo urlencode(thisPageUrl()) #>">Email this Page</a>
  <!-- /STEP2: Display Record Detail -->

  </td>
 </tr>
</table>

<?php 
    cg2_code_footer();
    // return code
    $code = ob_get_clean();
    return $code;
}
function getSelectOptionsFromTable($tableName, $valueField, $labelField, $selectedValue, $showEmptyOptionFirst)
{
    if (!is_array($selectedValue)) {
        $selectedValue = (array) $selectedValue;
    }
    // v2.60 force to array interally for simpler code to test single or multiple selected values
    // load options
    $escapedLabelField = mysql_escape($labelField);
    $escapedValueField = mysql_escape($valueField);
    $escapedTableName = $GLOBALS['TABLE_PREFIX'] . mysql_escape($tableName);
    // get records
    $schema = loadSchema($tableName);
    $query = "SELECT `{$escapedLabelField}`, `{$escapedValueField}` FROM `{$escapedTableName}`";
    if (@$schema['listPageOrder']) {
        $query .= " ORDER BY {$schema['listPageOrder']}";
    }
    // v2.14 - sort by schema sort order if available
    $records = mysql_select_query($query);
    // create html
    $html = '';
    if ($showEmptyOptionFirst) {
        $html .= "<option value=''>" . t('&lt;select&gt;') . "</option>\n";
    }
    foreach ($records as $record) {
        $label = $record[$labelField];
        $value = $record[$valueField];
        $selectedAttr = in_array($value, $selectedValue) ? " selected='selected'" : '';
        $html .= "<option value='" . htmlencode($value) . "'{$selectedAttr}>" . htmlencode($label) . "</option>\n";
    }
    //
    return $html;
}
function getTablesAndFieldnames()
{
    global $APP;
    $tablesAndFields = array();
    //
    foreach (getSchemaTables() as $tableName) {
        $schema = loadSchema($tableName);
        foreach ($schema as $fieldname => $fieldSchema) {
            if (!is_array($fieldSchema)) {
                continue;
            }
            // skip table metadata - fields are arrays
            if (@$fieldSchema['type'] == 'separator') {
                continue;
            }
            // skip separators
            if (@$fieldSchema['type'] == 'relatedRecords') {
                continue;
            }
            // skip
            $tablesAndFields[$tableName][] = $fieldname;
        }
    }
    // sort tablenames (fieldnames are already sorted by saveSchema)
    ksort($tablesAndFields);
    //
    return $tablesAndFields;
}
function cg2_rssfeed_getCode()
{
    $tableName = @$_REQUEST['tableName'];
    $schema = loadSchema($tableName);
    $menuName = coalesce(@$schema['menuName'], $tableName);
    // define variable names
    $tableRecordsVar = '$' . preg_replace("/[^\\w]/", '_', $tableName) . "Records";
    $metaDataVar = '$' . preg_replace("/[^\\w]/", '_', $tableName) . "MetaData";
    $recordVar = '$record';
    // define getRecords() options
    $options = array();
    $options[] = "'tableName'   => '{$tableName}',";
    if (@$_REQUEST['howMany'] == 'firstN') {
        $options[] = "'limit'       => '{$_REQUEST['limit']}',";
    } else {
        /* default to showing all */
    }
    $options[] = "'orderBy'     => '',   // use default database order";
    $options[] = "'loadUploads' => false,";
    $options[] = "'allowSearch' => false,";
    $padding = "    ";
    $getRecordsOptions = "\n{$padding}" . implode("\n{$padding}", $options) . "\n  ";
    ### generate code
    ob_start();
    ?>
<#php
  /* STEP 1: LOAD RECORDS - Copy this PHP code block near the TOP of your page */
  <?php 
    cg2_code_loadLibraries();
    ?>

  // load records from '<?php 
    echo $tableName;
    ?>
'
  list(<?php 
    echo $tableRecordsVar;
    ?>
, <?php 
    echo $metaDataVar;
    ?>
) = getRecords(array(<?php 
    echo $getRecordsOptions;
    ?>
));

<?php 
    /* not used
      // get updated and created times
    <?php if (@$schema['updatedDate']): ?>
      $lastUpdated = max(coalesce(array_map('strtotime', array_pluck(<?php echo $tableRecordsVar ?>, 'updatedDate')), array(time())));
    <?php else: ?>
      $lastUpdated = time();
    <?php endif ?>
    <?php if (@$schema['createdDate']): ?>
      $lastCreated = max(coalesce(array_map('strtotime', array_pluck(<?php echo $tableRecordsVar ?>, 'createdDate')), array(time())));
    <?php else: ?>
      $lastCreated = time();
    <?php endif ?>
    */
    ?>
#>
<#php header('Content-type: application/xml; charset=utf-8'); #><#php echo '<'.'?xml version="1.0" encoding="UTF-8"?>'; #>
<rss version="2.0">
  <channel>
    <title><?php 
    echo htmlencode(@$_REQUEST['feedTitle']);
    ?>
</title>
    <link><?php 
    echo htmlencode(@$_REQUEST['feedLink']);
    ?>
</link>
    <description><?php 
    echo htmlencode(@$_REQUEST['feedDescription']);
    ?>
</description>
    <pubDate><#php echo date('r') #></pubDate>
    <language><?php 
    echo htmlencode(@$_REQUEST['feedLanguage']);
    ?>
</language>

    <#php foreach (<?php 
    echo $tableRecordsVar;
    ?>
 as <?php 
    echo $recordVar;
    ?>
): #>
    <item>
      <title><#php echo htmlencode($record['<?php 
    echo @$_REQUEST['titleField'];
    ?>
']) #></title>
      <link>http://<#php echo $_SERVER['HTTP_HOST']; #>/<#php echo <?php 
    echo $recordVar;
    ?>
['_link'] #></link>
      <description><![CDATA[<#php echo <?php 
    echo $recordVar;
    ?>
['<?php 
    echo @$_REQUEST['descriptionField'];
    ?>
'] #>]]></description>
<?php 
    if (@$schema['createdDate']) {
        ?>
      <pubDate><#php echo date('r', strtotime(<?php 
        echo $recordVar;
        ?>
['createdDate'])) #></pubDate>
<?php 
    }
    ?>
      <guid isPermaLink="true"><#php echo <?php 
    echo $recordVar;
    ?>
['_link'] #></guid>
    </item>
    <#php endforeach #>
  </channel>
</rss>
<?php 
    // return code
    $code = ob_get_clean();
    return $code;
}
function _upgradeAccounts()
{
    // add new upload fields
    $schema = loadSchema('accounts');
    // make schema and menu visible
    if (@$schema['tableHidden']) {
        $schema['tableHidden'] = 0;
    }
    if (@$schema['menuHidden']) {
        $schema['menuHidden'] = 0;
    }
    // add new fields
    if (!@$schema['createdDate']) {
        $schema['createdDate'] = array('type' => 'none', 'label' => "Created", 'isSystemField' => '1');
    }
    if (!@$schema['createdByUserNum']) {
        $schema['createdByUserNum'] = array('type' => 'none', 'label' => "Created By", 'isSystemField' => '1');
    }
    if (!@$schema['updatedDate']) {
        $schema['updatedDate'] = array('type' => 'none', 'label' => "Last Updated", 'isSystemField' => '1');
    }
    if (!@$schema['updatedByUserNum']) {
        $schema['updatedByUserNum'] = array('type' => 'none', 'label' => "Last Updated By", 'isSystemField' => '1');
    }
    if (!@$schema['accessList']) {
        $schema['accessList'] = array('type' => 'accessList', 'label' => "Section Access", 'isSystemField' => '1', 'order' => time());
    }
    if (!@$schema['lastLoginDate']) {
        // added in v2.08
        $schema['lastLoginDate'] = array('type' => 'date', 'label' => "Last Login", 'defaultDate' => 'none', 'order' => time(), 'showTime' => '1', 'use24HourFormat' => '0', 'showSeconds' => '1', 'yearRangeStart' => '2010', 'yearRangeEnd' => '2020');
    }
    // remove fields
    foreach (array_keys($schema) as $fieldname) {
        $fieldSchema =& $schema[$fieldname];
        if (!is_array($fieldSchema)) {
            continue;
        }
        // fields are stored as arrays, other entries are table metadata, skip metadata
        // remove old "show tablenames" field for old access settings
        if (@$fieldSchema['type'] == 'separator' && preg_match("/listTableNames\\(\\)'>MySQL Tablenames/", @$fieldSchema['separatorHTML'])) {
            unset($schema[$fieldname]);
        }
    }
    ### update order
    // increase field order for all fields
    foreach (array_keys($schema) as $fieldname) {
        $fieldSchema =& $schema[$fieldname];
        if (!is_array($fieldSchema)) {
            continue;
        }
        // fields are stored as arrays, other entries are table metadata, skip metadata
        $fieldSchema['order'] += 10;
    }
    // hard code field order
    if (@$schema['num']) {
        $schema['num']['order'] = '1';
    }
    if (@$schema['createdDate']) {
        $schema['createdDate']['order'] = '2';
    }
    if (@$schema['createdByUserNum']) {
        $schema['createdByUserNum']['order'] = '3';
    }
    if (@$schema['updatedDate']) {
        $schema['updatedDate']['order'] = '4';
    }
    if (@$schema['updatedByUserNum']) {
        $schema['updatedByUserNum']['order'] = '5';
    }
    ### change fields
    // Set checked/unchecked values for 'isAdmin' field
    if (@$schema['isAdmin']) {
        if (@$schema['isAdmin']['checkedValue'] == '') {
            $schema['isAdmin']['checkedValue'] = 'Yes';
        }
        if (@$schema['isAdmin']['uncheckedValue'] == '') {
            $schema['isAdmin']['uncheckedValue'] = '-';
        }
        $schema['isAdmin']['adminOnly'] = "2";
    }
    // Set accessList to be a system field
    if (@$schema['accessList']) {
        $schema['accessList']['isSystemField'] = 1;
    }
    // v1.32 - add "My Account" fields
    $myAccountFields = array('fullname', 'username', 'email', 'password');
    foreach ($myAccountFields as $field) {
        if (!is_array(@$schema[$field])) {
            continue;
        }
        if (array_key_exists('myAccountField', $schema[$field])) {
            continue;
        }
        // ignore if already set
        $schema[$field]['myAccountField'] = 1;
    }
    // save changes
    saveSchema('accounts', $schema);
    // add to schema
    createMissingSchemaTablesAndFields();
    // add to database
    clearAlertsAndNotices();
    // don't show "created table/field" alerts
}
function cg2_detailpage_getCode()
{
    $tableName = @$_REQUEST['tableName'];
    $schema = loadSchema($tableName);
    $menuName = coalesce(@$schema['menuName'], $tableName);
    // define variable names
    $tableRecordsVar = '$' . preg_replace("/[^\\w]/", '_', $tableName) . "Records";
    $metaDataVar = '$' . preg_replace("/[^\\w]/", '_', $tableName) . "MetaData";
    $recordVar = '$' . preg_replace("/[^\\w]/", '_', $tableName) . "Record";
    // define getRecords() options
    $options = array();
    $options[] = "'tableName'   => '{$tableName}',";
    if (@$_REQUEST['whichRecord'] == 'first') {
        $options[] = "'where'       => '', // load first record";
    } elseif (@$_REQUEST['whichRecord'] == 'url') {
        $options[] = "'where'       => whereRecordNumberInUrl(0),";
    } elseif (@$_REQUEST['whichRecord'] == 'custom') {
        $options[] = "'where'       => \"`num` = '" . intval(@$_REQUEST['recordNumCustom']) . "'\",";
    }
    if (@$_REQUEST['showUploads'] == 'all') {
        $options[] = "'loadUploads' => true,";
    } elseif (@$_REQUEST['showUploads'] == 'limit') {
        $options[] = "'loadUploads' => true,";
    } else {
        $options[] = "'loadUploads' => false,";
    }
    $options[] = "'allowSearch' => false,";
    $options[] = "'limit'       => '1',";
    $padding = "    ";
    $getRecordsOptions = "\n{$padding}" . implode("\n{$padding}", $options) . "\n  ";
    ### generate code
    ob_start();
    ?>
<#php header('Content-type: text/html; charset=utf-8'); #>
<#php
  /* STEP 1: LOAD RECORDS - Copy this PHP code block near the TOP of your page */
  <?php 
    cg2_code_loadLibraries();
    ?>

  // load record from '<?php 
    echo $tableName;
    ?>
'
  list(<?php 
    echo $tableRecordsVar;
    ?>
, <?php 
    echo $metaDataVar;
    ?>
) = getRecords(array(<?php 
    echo $getRecordsOptions;
    ?>
));
  <?php 
    echo $recordVar;
    ?>
 = @<?php 
    echo $tableRecordsVar;
    ?>
[0]; // get first record
  if (!<?php 
    echo $recordVar;
    ?>
) { dieWith404("Record not found!"); } // show error message if no record found

#><?php 
    cg2_code_header();
    cg2_code_instructions('Detail');
    ?>

  <!-- STEP2: Display Record (Paste this where you want your record to appear) -->
    <h1><?php 
    echo $menuName;
    ?>
 - Detail Page Viewer</h1>
<?php 
    cg2_code_schemaFields($schema, $recordVar, $tableName);
    if (@$_REQUEST['showUploads']) {
        cg2_code_uploads($schema, $recordVar);
    }
    ?>
  <!-- /STEP2: Display Record -->
    <hr/>

  <a href="<#php echo <?php 
    echo $metaDataVar;
    ?>
['_listPage'] ?>">&lt;&lt; <?php 
    echo t('Back to list page');
    ?>
</a>
  <a href="mailto:?subject=<#php echo urlencode(thisPageUrl()) #>"><?php 
    echo t('Email this Page');
    ?>
</a>

<?php 
    cg2_code_footer();
    ?>

<?php 
    // return code
    $code = ob_get_clean();
    return $code;
}
function _getFieldLabel($fullFieldname)
{
    @(list($fieldname, $tableName) = array_reverse(explode('.', $fullFieldname)));
    // get schema
    $schema = array();
    if (!$tableName && $GLOBALS['schema']) {
        $schema =& $GLOBALS['schema'];
    } else {
        if ($tableName == 'createdBy') {
            $tableName = 'accounts';
        }
        // workaround for legacy 'createdBy.fieldname' fieldnames
        $schema = loadSchema($tableName);
    }
    // get label
    $label = @$schema[$fieldname]['label'];
    return $label;
}
function getListOptionsFromSchema($fieldSchema, $record = null, $useCache = false, $listValues = null)
{
    global $TABLE_PREFIX;
    $listOptions = array();
    $optionsType = @$fieldSchema['optionsType'];
    // get list values to lookup
    $listValuesAsCSV = '';
    if ($listValues) {
        foreach ($listValues as $value) {
            $listValuesAsCSV .= "'" . mysql_escape($value) . "',";
        }
        $listValuesAsCSV = chop($listValuesAsCSV, ',');
        // remove trailing comma
    }
    ### parse text options
    if ($optionsType == 'text') {
        // parse
        $optionText = explode("\n", @$fieldSchema['optionsText']);
        foreach ($optionText as $optionString) {
            if (preg_match("/(^|[^\\|])(\\|\\|)*(\\|)(?!\\|)/", $optionString, $match, PREG_OFFSET_CAPTURE)) {
                $delimiterOffset = $match[3][1];
                $value = substr($optionString, 0, $delimiterOffset);
                $label = substr($optionString, $delimiterOffset + 1);
            } else {
                $value = $optionString;
                $label = $optionString;
            }
            $value = str_replace("||", "|", $value);
            $label = str_replace("||", "|", $label);
            // remove trailing whitespace
            $value = rtrim($value);
            $label = rtrim($label);
            $listOptions[] = array($value, $label);
        }
    } else {
        $cacheTable = '';
        // create query
        if ($optionsType == 'table') {
            $valueField = @$fieldSchema['optionsValueField'];
            $labelField = @$fieldSchema['optionsLabelField'];
            $selectTable = $TABLE_PREFIX . $fieldSchema['optionsTablename'];
            $tableSchema = loadSchema($fieldSchema['optionsTablename']);
            $where = $listValuesAsCSV ? "WHERE `{$valueField}` IN ({$listValuesAsCSV})" : '';
            $orderBy = @$tableSchema['listPageOrder'] ? "ORDER BY {$tableSchema['listPageOrder']}" : '';
            $query = "SELECT `{$valueField}`, `{$labelField}` FROM `{$selectTable}` {$where} {$orderBy} LIMIT 0, 999";
            $cacheTable = $fieldSchema['optionsTablename'];
        } else {
            if ($optionsType == 'query') {
                $filterFieldValue = @$record[@$fieldSchema['filterField']];
                $GLOBALS['ESCAPED_FILTER_VALUE'] = mysql_escape($filterFieldValue);
                $query = getEvalOutput($fieldSchema['optionsQuery']);
                if (preg_match("/\\bFROM\\s+(\\S+)/", $query, $matches)) {
                    $cacheTable = $matches[1];
                    $cacheTable = preg_replace("/\\W/", '', $cacheTable);
                    // remove ` quotes, etc
                }
            } else {
                die("Unknown optionsType '{$optionsType}'!");
            }
        }
        // load cache module
        if ($useCache && $cacheTable) {
            $libDir = dirname(__FILE__);
            if (file_exists("{$libDir}/viewer_turboCache.php")) {
                require_once "{$libDir}/viewer_turboCache.php";
            }
            // load cached result
            if (!function_exists('turboCache_load')) {
                die("Error: 'useCaching' enabled but no caching plugin found!<br/>Either disable 'useCaching' or install caching plugin.");
            }
            $listOptions = turboCache_load($cacheTable, $query);
            if ($listOptions) {
                return $listOptions;
            }
        }
        // execute query
        $result = @mysql_query($query);
        if (!$result) {
            $error = "There was an error creating the list field '" . @$fieldSchema['name'] . "'.\n\n";
            $error .= "MySQL Error: " . mysql_error() . "\n\n";
            header("Content-type: text/plain");
            die($error);
        }
        while ($row = mysql_fetch_row($result)) {
            $value = $row[0];
            $label = array_key_exists(1, $row) ? $row[1] : $value;
            // use value if no label specified
            $listOptions[] = array($value, $label);
        }
        if (is_resource($result)) {
            mysql_free_result($result);
        }
        // save to cache
        if ($useCache && $cacheTable) {
            turboCache_save($cacheTable, $query, $listOptions);
        }
    }
    //
    return $listOptions;
}