ko_center System Administrator Documentation

Application:ko_center — Centralized LED Dashboard & System Management
Version:v0.70 (2026-08-01)
Primary File:/os/ai/io/ko_center.php (16,322 lines, 205 functions)
Database:SQLite 3 — /os/ai/io/ko_center.db3 (~39.6 MB, 30+ tables)
Web Server:Apache + mod_php (primary) / Python Flask (equivalent: ko_center.py)
Language:PHP 5.3+ (procedural, single-file architecture)
Last Modified:2026-08-01 06:47 (server time)

Table of Contents

1. System Architecture & Design

1.1 Architectural Overview

ko_center is a single-file PHP web application — all 205 functions and the entire routing logic reside in one file. It follows a traditional LAMP stack pattern with no external framework dependencies.

Key Design Characteristics:

1.2 Request Lifecycle

HTTP Request → Apache/PHP → startup() → Parse ?q= → Route to handler → Generate HTML → Response

startup() does:
  1. session_start()
  2. Set error_reporting(0)
  3. Initialize $progid, $dttm, $dttm_ip
  4. Set $GLOBALS paths (dbfile, kbfile, hosts_allow, logfil, etc.)
  5. Detect host OS (win/linux)
  6. Parse $_REQUEST['q'] into $options[] array
  7. Check if database exists (auto-install if not)
  8. Route to appropriate handler based on $options[0]

1.3 Core Global Variables

VariableTypeDescription
$progidstringProgram identifier: "ko_center"
$dttmstringCurrent datetime: YYYYMMDD_HHMMSS
$dttm_ipstringIP-formatted datetime: YY.MM.DD.HH
$hostosstringOperating system: "win" or "" (linux)
$allowflagstringContents of hosts.allow file
$kb_userstringKB user extracted from hosts.allow field 2
$userstringCurrent user from hosts.allow field 2
$passstringPassword from hosts.allow field 3
$stepstringLogin step indicator
$leds_contextstringLED context: "racks randomus default"
$led_contextstringLED context details

1.4 $GLOBALS Registry

KeyValuePurpose
hosts_allow$document_root/../safer/hosts.allowAuthentication file path
kbfile$document_root/ko_center/db3/koaac_kb.db3Knowledge Base database
kb_rootpath$document_root/ko_center/kbKB file storage root
kbpath$document_root/ko_center/kbKB path (alias)
ko_center_certsfile$document_root/ko_center/db3/ko_center_certs.db3Certificates database
logfil$logfil_rootpath/ko_center_YYYYMM.logMonthly log file
progid"ko_center"Program name
screenshots_pcharts""pChart screenshot path (empty = disabled)
dbsAssociative arrayMulti-database registry keyed by role
rolesArray['admin', 'local', 'users', 'anon']
themesArrayjQuery UI theme names
tblnamestringDefault table: "leds"
js_outputbooleanJavaScript output flag (default false)

2. Installation & Initial Setup

2.1 Prerequisites

ComponentMinimum VersionNotes
Web ServerApache 2.4+ or Python 3.6+Apache with mod_php for PHP version; Flask for Python
PHP5.3+Requires PDO SQLite extension
SQLite3.xBundled with PHP PDO
ImageMagickAny versionRequired only for LED GIF generation (cr_leds.py)
PerlAny versionRequired for iperms utility functions
Disk Space~50 MBDatabase (39.6 MB) + images + logs
PHP Memory256 MBmemory_limit in php.ini

2.2 Installation Steps

Step 1: Deploy Application Files

mkdir -p /var/www/html/ko_center
mkdir -p /var/www/html/ko_center/db3
mkdir -p /var/www/html/ko_center/kb
mkdir -p /var/www/html/ko_center/images/btn
mkdir -p /var/www/html/ko_center/images/ani
mkdir -p /var/www/html/ko_center/images/fpb
cp ko_center.php /var/www/html/ko_center/
cp ko_center.db3 /var/www/html/ko_center/db3/

Step 2: Configure hosts.allow

Create or edit /var/www/html/../safer/hosts.allow:

allow all
# Format: allow <user> <role> <username>
# Example: allow admin user joachim

Step 3: Set File Permissions

chown -R www-data:www-data /var/www/html/ko_center/
chmod 666 /var/www/html/ko_center/db3/ko_center.db3
chmod 755 /var/www/html/ko_center/
chmod 666 /var/www/html/ko_center/ko_trigger.dat  # if using trigger feature

Step 4: First-Time Initialization

Access the application in a browser:

http://<server>/ko_center/ko_center.php

If the database file doesn't exist, leds_install("new") is called automatically (line 421), which creates all core tables and inserts default data.

Step 5: Verify Installation

2.3 leds_install() Function Details

The leds_install() function (line 9707) supports two modes:

ModeBehavior
"new"Creates database if it doesn't exist. If file already exists, returns error.
"old"Renames existing database to ko_center_YYYYMMDD_HHMMSS.db3 before creating a fresh one.

Tables created during install:

Function CallTable CreatedDefault Data Inserted
pdo_cr_leds() + pdo_insert_leds()ledsYes
pdo_cr_nodes() + pdo_insert_nodes()nodesYes
pdo_cr_roles() + pdo_insert_roles()rolesYes
pdo_cr_users() + pdo_insert_users()usersYes
pdo_cr_fp() + pdo_insert_fp()fpYes
pdo_cr_grid() + pdo_insert_grid()gridYes
pdo_cr_us() + pdo_insert_us()usYes
pdo_cr_hw() + pdo_insert_hw()hwYes
pdo_cr_n11() + pdo_insert_n11()n11Yes
pdo_cr_dbs() + pdo_insert_dbs()dbsYes
pdo_cr_fgmenu() + pdo_insert_fgmenu()fgmenuYes
pdo_cr_obj() + pdo_insert_obj()objYes
pdo_cr_pano() + pdo_insert_pano()panoYes
pdo_cr_kb()koaac_kbNo (created empty)

3. Configuration Reference

3.1 Path Configuration (startup() lines 130-151)

SettingDefault PathDescription
$path_btn/ko_center/images/btnButton image directory
$path_ani/ko_center/images/aniAnimated LED GIF directory
$path_fpb/ko_center/images/fpbFloor plan button images
$logfil_rootpath$document_root/../ko_saferLog file directory
$logfil_basenameko_center_YYYYMM.logMonthly log file name
$hosts_allow$document_root/../safer/hosts.allowAuthentication file
$kb_rootpath$document_root/ko_center/kbKB file storage

3.2 Theme Configuration

Available jQuery UI themes (set via $_SESSION['theme']):

ThemeCSS FileImage Path
redmondjs/themes/redmond/jquery-ui-1.7.2.custom.cssjs/themes/redmond/images/
humanityjs/themes/humanity/jquery-ui-1.7.2.custom.cssjs/themes/humanity/images/
frogjs/themes/le-frog/jquery-ui-1.7.2.custom.cssjs/themes/le-frog/images/
swankyjs/themes/swanky-purse/jquery-ui-1.7.2.custom.cssjs/themes/swanky-purse/images/
darknessjs/themes/ui-darkness/jquery-ui-1.7.2.custom.cssjs/themes/ui-darkness/images/
lightnessjs/themes/ui-lightness/jquery-ui-1.7.2.custom.cssjs/themes/ui-lightness/images/
sunnyjs/themes/sunny/jquery-ui-1.7.2.custom.cssjs/themes/sunny/images/
mintjs/themes/mint-choc/jquery-ui-1.7.2.custom.cssjs/themes/mint-choc/images/

3.3 Session Variables

VariableSet ByValuesPurpose
$_SESSION['user']leds_login_validate()Username stringAuthenticated user identity
$_SESSION['role']leds_login_validate()admin, local, users, anonAccess control level
$_SESSION['preview']User toggle"on" / "" (empty)Enable/disable image preview on LED clicks
$_SESSION['theme']User selectionTheme nameUI color theme
$_SESSION['grid_zoom']User toggletrue / "" / falseGrid zoom state
$_SESSION['hs_type']User selectionall, grid, us, hw, n11, noneHotspot type filter for zoom viewer
$_SESSION['org_type']User selectiona, e, h, o, p, tOrganization type filter
$_SESSION['gridimgpath']js_scripts()Theme image pathjQuery UI theme images

4. Database Administration

4.1 Database File

PropertyValue
Path/os/ai/io/ko_center.db3
TypeSQLite 3
Size~39.6 MB
Tables30+
Access MethodPHP PDO via newpdo() function
Connection Stringsqlite:/os/ai/io/ko_center.db3

4.2 Database Connection Function

function newpdo( $dbfile ) {
    $pdo = new PDO("sqlite:$dbfile");
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
    return $pdo;
}

4.3 Complete Table Inventory

TableRowsDescription
leds262LED indicator records (primary display table)
randomus101Random user/person data
leds_randomus101Combined LED schema + randomus data
ko_plansProject plans with steps and items
ko_hwHardware inventory details
koaac_kbKnowledge Base articles
nodesNetwork nodes and devices
rolesUser role definitions
usersUser account records
cabsCabinet/rack data
kocabCabinet details
kohwHardware records
koplansPlan records
cfgConfiguration key-value pairs
dbsDatabase registry (multi-DB support)
menusNavigation menu definitions
fpFloor plan references
gridGrid view configuration
usUser-specific data/preferences
n11N11 monitoring alert data
panoPanorama/tour data
objObject references
zoomZoom viewer configuration
zoomxmlZoom XML hotspot data
shelvesShelf/rack shelf data
halloHallo records
haloHalo records
nimbusNimbus records
aureoleAureole records
leds_defaultsDefault LED settings
leds_racksLED-to-rack mappings
periodsReporting time periods
rptsReport definitions and SQL
hrc_datacenters_equipmentDatacenter equipment inventory
hrc_dc_*Various datacenter tables (1307comm, unix, win, btu, etc.)
defrag_planDefragmentation plans
defrag_plansumDefrag plan summaries
moveplan_detailsMove plan details
es_ipIP address tracking
es_hwExtended hardware info
kohw_*Hardware table variants (win, hrc, unix, etc.)
kohw_hrc_defragHRC defrag hardware
kohw_cabs_defragCabinet defrag hardware

4.4 Database Maintenance Commands

# Integrity check
sqlite3 /os/ai/io/ko_center.db3 "PRAGMA integrity_check;"

# List all tables
sqlite3 /os/ai/io/ko_center.db3 ".tables"

# Row counts for all tables
sqlite3 /os/ai/io/ko_center.db3 "SELECT name, (SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name=m.name) FROM sqlite_master m WHERE type='table';"

# Vacuum (reclaim space, rebuild database)
sqlite3 /os/ai/io/ko_center.db3 "VACUUM;"

# Analyze (update query planner statistics)
sqlite3 /os/ai/io/ko_center.db3 "ANALYZE;"

# Backup
cp /os/ai/io/ko_center.db3 /os/ai/io/ko_center.db3.backup.$(date +%Y%m%d_%H%M%S)

# Export table to CSV
sqlite3 -header -csv /os/ai/io/ko_center.db3 "SELECT * FROM leds LIMIT 100;" > leds_export.csv

# Check database size
ls -lh /os/ai/io/ko_center.db3

# Check freelist (fragmentation indicator)
sqlite3 /os/ai/io/ko_center.db3 "PRAGMA freelist_count;"

5. User & Role Management

5.1 Authentication Flow

  1. User accesses application → leds_login_form() (line 8450) displays login form
  2. User submits credentials → leds_login_validate() (line 8568) processes
  3. Credentials validated against hosts.allow file contents
  4. On success: $_SESSION['user'] and $_SESSION['role'] are set
  5. On failure: Login form redisplayed with error
  6. Logout: leds_logout() (line 8739) clears session and redirects

5.2 Role Definitions

RoleDescriptionAccess Level
anonUnauthenticated / anonymousRead-only, minimal features
usersStandard authenticated userView LED status, basic navigation, grid views
localLocal/system userExtended access including config
opOperatorOperational features, LED management
mgrsManagerManagement features, reports, KB
adminAdministratorFull access, all features, database management

5.3 Role-Based Database Access

The dbs_init() function (line 15441) defines multi-database access by role:

$dbfiles['admin']['ko_center']['dbfile'] = "$document_root/ko_center/ko_center.db3";
$dbfiles['admin']['ko_center']['tables'] = array('fp', 'leds', 'rpts', 'roles', 'users', ...);

Each role has access to specific databases and tables, enabling data isolation between user groups.

6. Security Assessment

Critical Security Notice: ko_center.php is a legacy application with several known security vulnerabilities. Review and remediate before deploying in any production or exposed environment.

6.1 Vulnerability Summary

#VulnerabilitySeverityLocationDescription
V1 SQL Injection Critical leds_show() L6939, pdo_grid() L10686, multiple grid functions User input interpolated directly into SQL queries via string concatenation. Example: $sql = "select * from $tblname where led_dttm == 'current' and led_type == '$led_type'"
V2 Shell Command Injection Critical leds_process() L6485, iperms() L6425, localcmds() L15887 User-controlled values passed to system(), exec(), passthru(), and proc_open() without sanitization
V3 Cross-Site Scripting (XSS) High All functions that output user data No htmlspecialchars() or output encoding applied to user-supplied data displayed in HTML
V4 Plain Text Passwords High randomus table (login_pass column) Passwords stored in plain text, no hashing or salting
V5 No CSRF Protection Medium All form submissions No anti-CSRF tokens on any forms
V6 No Rate Limiting Medium Login form, all endpoints No brute-force protection or request throttling
V7 Directory Traversal High File operations in KB, upload, scrub File paths constructed from user input without path sanitization
V8 Error Information Leakage Low startup() L107 error_reporting(0) suppresses errors but may hide issues; however, custom error messages may leak path info
V9 Weak Session Management Medium startup() L105 No session regeneration after login, no session timeout, no secure cookie flags
V10 No HTTPS Enforcement Medium All endpoints No HSTS, no redirect to HTTPS

6.2 Recommended Remediations

VulnerabilityPriorityRecommended Fix
SQL Injection P0 Replace all string-interpolated SQL with prepared statements using PDO prepare() / execute()
Shell Injection P0 Use escapeshellarg() on all user input passed to shell commands; consider replacing shell calls with PHP native functions
XSS P1 Apply htmlspecialchars() to all user-supplied data before output in HTML
Plain Text Passwords P0 Hash passwords with password_hash() (bcrypt) and verify with password_verify()
CSRF P1 Add CSRF token generation and validation to all state-changing forms
Rate Limiting P2 Implement login attempt throttling; consider Apache mod_evasive or application-level rate limiting
Directory Traversal P0 Sanitize all file paths with basename() and restrict to allowed directories
Session Management P1 Add session_regenerate_id(true) after login; set session timeout; configure secure cookie flags

7. Logging, Debugging & Monitoring

7.1 Log File Configuration

Log files are created in the ko_safer directory with monthly rotation:

Log directory: /os/ai/io/../ko_safer/
Log pattern:  ko_center_YYYYMM.log
Example:      /os/ai/io/../ko_safer/ko_center_202608.log

Log file path construction (startup() lines 144-148):

$yyyymm = date('Ym');
$logfil_basename = $progid . "_" . $yyyymm . ".log";
$logfil_rootpath = $document_root . "/../ko_safer";
$logfil = $logfil_rootpath . "/" . $logfil_basename;
$GLOBALS['logfil'] = $logfil;

7.2 Logging Functions

FunctionLineDescription
logwrite($logfil, $logrec)4673Append a record to the log file
logdump($logfil)4683Read and display entire log file contents
bugfile($options)10993Write comprehensive debug info to fp_bugs.txt (database file, URL table, page, POST data, GET data, session data)

7.3 Debug Mode

Debug output is currently disabled (error_reporting(0) at line 107). To enable debugging:

  1. Change error_reporting(0) to error_reporting(E_ALL) in startup()
  2. Uncomment debug print() statements throughout the code (prefixed with //)
  3. Check log files in /os/ai/io/../ko_safer/
  4. Use ?q=about or ?q=pdo for basic diagnostics

7.4 Monitoring Checklist

8. Backup & Recovery Procedures

8.1 Backup Script

#!/bin/bash
# ko_center_backup.sh — Daily backup script

DB="/os/ai/io/ko_center.db3"
KB="/os/ai/io/ko_center/kb"
CERTS="/os/ai/io/ko_center/db3/ko_center_certs.db3"
KB_DB="/os/ai/io/ko_center/db3/koaac_kb.db3"
BACKUP_DIR="/os/ai/io/backups"
HOSTS_ALLOW="/os/ai/io/../safer/hosts.allow"
DATE=$(date +%Y%m%d_%H%M%S)

mkdir -p "$BACKUP_DIR"

# Backup database
cp "$DB" "$BACKUP_DIR/ko_center_$DATE.db3"
gzip "$BACKUP_DIR/ko_center_$DATE.db3"

# Backup certificates DB
cp "$CERTS" "$BACKUP_DIR/ko_center_certs_$DATE.db3"
gzip "$BACKUP_DIR/ko_center_certs_$DATE.db3"

# Backup KB database
cp "$KB_DB" "$BACKUP_DIR/koaac_kb_$DATE.db3"
gzip "$BACKUP_DIR/koaac_kb_$DATE.db3"

# Backup hosts.allow
cp "$HOSTS_ALLOW" "$BACKUP_DIR/hosts.allow_$DATE"

# Backup KB file attachments
tar -czf "$BACKUP_DIR/ko_kb_attachments_$DATE.tar.gz" -C "$(dirname $KB)" "$(basename $KB)"

# Keep only last 30 days of backups
find "$BACKUP_DIR" -name "ko_center_*.db3.gz" -mtime +30 -delete
find "$BACKUP_DIR" -name "hosts.allow_*" -mtime +30 -delete
find "$BACKUP_DIR" -name "ko_kb_attachments_*.tar.gz" -mtime +30 -delete

echo "Backup completed: $DATE"

8.2 Recovery Procedure

  1. Stop the web server: systemctl stop apache2 (or service apache2 stop)
  2. Copy backup to database location:
    gunzip -c /os/ai/io/backups/ko_center_YYYYMMDD_HHMMSS.db3.gz > /os/ai/io/ko_center.db3
  3. Verify integrity:
    sqlite3 /os/ai/io/ko_center.db3 "PRAGMA integrity_check;"
  4. Set correct permissions:
    chown www-data:www-data /os/ai/io/ko_center.db3
    chmod 666 /os/ai/io/ko_center.db3
  5. Start the web server: systemctl start apache2
  6. Verify: Browse to ?q=about and ?q=pdo

8.3 Files to Backup

File/DirectoryCriticalityBackup Frequency
/os/ai/io/ko_center.db3CriticalDaily
/os/ai/io/ko_center/db3/ko_center_certs.db3CriticalDaily
/os/ai/io/ko_center/db3/koaac_kb.db3CriticalDaily
/os/ai/io/safer/hosts.allowCriticalDaily
/os/ai/io/ko_center.phpCriticalOn every code change
/os/ai/io/images/HighWeekly
/os/ai/io/ko_center/kb/HighDaily
/os/ai/io/../ko_safer/MediumMonthly (archived)

9. Routine Maintenance

9.1 Scheduled Maintenance Tasks

TaskFrequencyCommand / Action
Database backupDailyRun backup script (see Section 8.1)
Log rotationMonthlyCompress old logs, delete logs older than 90 days
Database vacuumMonthlysqlite3 ko_center.db3 "VACUUM;"
Database analyzeMonthlysqlite3 ko_center.db3 "ANALYZE;"
Disk space checkWeeklydf -h /os/ai/io/
File permissions auditWeeklyVerify db3 file is writable by web server user
Image asset verificationMonthlyVerify images/btn/, images/ani/, images/fpb/ have expected files
LED record cleanupMonthlyArchive or delete old LED records (led_dttm != 'current')
KB article reviewMonthlyRemove outdated or unused KB entries
Database integrity checkWeeklysqlite3 ko_center.db3 "PRAGMA integrity_check;"
Free space checkWeeklysqlite3 ko_center.db3 "PRAGMA freelist_count;"
Trigger file checkWeeklyVerify ko_trigger.dat exists and is writable

9.2 LED Record Management

LED records use led_dttm = 'current' to mark active records. Historical records should be archived:

-- Archive old LED records to a separate table
CREATE TABLE IF NOT EXISTS leds_archive AS SELECT * FROM leds WHERE 1=0;
INSERT INTO leds_archive SELECT * FROM leds WHERE led_dttm != 'current';
DELETE FROM leds WHERE led_dttm != 'current';

9.3 Database Optimization

# Rebuild all indexes
sqlite3 /os/ai/io/ko_center.db3 "REINDEX;"

# Update query planner statistics
sqlite3 /os/ai/io/ko_center.db3 "ANALYZE;"

# Check database size
ls -lh /os/ai/io/ko_center.db3

# Check for fragmentation
sqlite3 /os/ai/io/ko_center.db3 "PRAGMA freelist_count;"

# If freelist_count > 0, vacuum is recommended
sqlite3 /os/ai/io/ko_center.db3 "VACUUM;"

10. Troubleshooting Guide

10.1 Common Issues & Solutions

SymptomProbable CauseSolution
Blank white page PHP error suppressed by error_reporting(0) Temporarily change error_reporting(0) to error_reporting(E_ALL) in startup() at line 107
"Database not found" error ko_center.db3 missing or incorrect path in $GLOBALS['dbfile'] Verify path in startup() (line 138); run leds_install("new") by accessing the URL in a browser
"Permission denied" errors Web server user cannot write to database file or directories chown www-data:www-data /os/ai/io/ko_center.db3; chmod 666 /os/ai/io/ko_center.db3
LED images not displaying Missing ani_*.gif files in images/ani/ Run python3 /os/ai/io/cr_leds.py <static.png> <dynamic.png>
Button images broken Missing btn_*.gif files in images/btn/ Verify button images exist in /os/ai/io/images/btn/
Login fails for all users hosts.allow missing, wrong path, or wrong format Check /os/ai/io/../safer/hosts.allow exists and contains allow all or properly formatted entries
Trigger not refreshing other browsers ko_trigger.dat not writable or missing touch /os/ai/io/ko_trigger.dat && chmod 666 /os/ai/io/ko_trigger.dat
Grid view shows empty or error Table doesn't exist or has no data; SQL error Verify table exists: sqlite3 ko_center.db3 ".tables"; check SQL in query
Report export fails File write permission issues in output directory Verify web server user has write permission to output directory
Slow page loads Large database (39.6 MB), complex queries, missing indexes Run VACUUM and ANALYZE; add indexes to frequently queried columns
KB file uploads fail PHP upload_max_filesize or post_max_size too small Increase in php.ini: upload_max_filesize = 50M, post_max_size = 50M
Theme not applying jQuery UI theme CSS files missing Verify theme CSS files exist in js/themes/<theme>/

10.2 Debugging Checklist

  1. Check PHP is running: php -v
  2. Check database exists: ls -la /os/ai/io/ko_center.db3
  3. Check database integrity: sqlite3 /os/ai/io/ko_center.db3 "PRAGMA integrity_check;"
  4. Check web server error log: tail -f /var/log/apache2/error.log
  5. Check application logs: ls -la /os/ai/io/../ko_safer/
  6. Verify file permissions: namei -l /os/ai/io/ko_center.db3
  7. Test basic functionality: Browse to ?q=about
  8. Test database connectivity: Browse to ?q=pdo
  9. Check PHP error log: tail -f /var/log/php_errors.log
  10. Enable error reporting: Temporarily set error_reporting(E_ALL) in startup()

10.3 Performance Tuning

AreaSettingRecommendation
PHP Memorymemory_limitSet to 256M or higher for large grid views
PHP Execution Timemax_execution_timeSet to 300 for long-running reports
PHP Upload Sizeupload_max_filesizeSet to 50M for KB file uploads
SQLite Cache SizePRAGMA cache_sizeSet to -64000 (64MB) for better query performance
SQLite Journal ModePRAGMA journal_modeSet to WAL for better concurrent read performance
Apache KeepAliveKeepAlive OnEnable for better performance with multiple AJAX requests
Apache MaxClientsMaxClientsAdjust based on expected concurrent users

11. File Structure & Asset Inventory

11.1 Complete Directory Layout

/os/ai/io/
├── ko_center.php          [16,322 lines]  Main PHP application
├── ko_center.py            [Python Flask]  Python equivalent
├── ko_center.db3           [39.6 MB]      SQLite database
├── ko_center.html          [User doc]      System user documentation
├── ko_center_admin.html    [Admin doc]     Administrator documentation (previous)
├── ko_center_sysadm.html   [This file]    System administrator documentation
├── new_leds.py             [Script]       Create leds_randomus table
├── new_leds_tbl.py         [Script]       Generalized table creation
├── cr_leds.py              [Script]       LED GIF generation with ImageMagick
├── response_trigger_plan.txt       [Doc]    Trigger mechanism design
├── prompt_*.txt            [Prompts]      Original task prompts
├── response_*.txt          [Docs]         Response documents
├── ko_trigger.dat          [Runtime]      Trigger timestamp (created at runtime)
├── led_red_flashing.jpg    [Asset]        LED image asset
├── images/
│   ├── btn/                 Button GIF images (btn_black.gif, btn_white.gif, etc.)
│   ├── ani/                 Animated LED GIFs (ani_red0.gif through ani_trans3.gif)
│   ├── fpb/                 Floor plan button images
│   └── cab/                 Cabinet images
├── ko_center/
│   ├── db3/                 Additional database files
│   │   ├── ko_center_certs.db3
│   │   └── koaac_kb.db3
│   └── kb/                  Knowledge Base file storage
├── js/
│   ├── jquery-1.7.2.min.js
│   ├── jquery-ui-1.7.2.custom.min.js
│   ├── fg-menu/             fg-menu JavaScript and CSS
│   ├── jqgrid-4.4.0/       jqGrid library (JS, CSS, images, i18n)
│   └── tooltip/             Tooltip JavaScript
├── css/                     Theme CSS files (jQuery UI themes)
├── ../safer/
│   └── hosts.allow          Authentication/authorization file
└── ../ko_safer/
    └── ko_center_YYYYMM.log  Monthly application logs

11.2 Key File Sizes

FileSizeLinesDescription
ko_center.php~635 KB16,322Main application (all functionality)
ko_center.db3~39.6 MBSQLite database
ko_center.pyPython Flask equivalent
new_leds.pyCreate leds_randomus table
new_leds_tbl.pyGeneralized table creation
cr_leds.pyLED GIF generation

12. PHP Function Reference (205 Functions)

12.1 Core Application Functions

FunctionLinePurpose
startup()101Application initialization: session, globals, paths, config, routing
html_header()8395Generate HTML <head> section with CSS/JS includes
html_footer()10987Generate HTML </body></html> closing tags
html_page()6635Generate complete HTML page (header + buttons + content + footer)
html_btn_squares()7331Generate navigation button squares
js_scripts()14337Generate JavaScript includes (jQuery, jqGrid, fg-menu)
leds_show()6895Main LED display — queries DB, renders LED grid with blinking GIFs
leds_detail()7759LED detail view with associated hardware items and images
leds_about()6323About page
leds_login_form()8450Login form HTML generation
leds_login_validate()8568Login credential validation against hosts.allow
leds_logout()8739Session cleanup and redirect to main page
leds_config()6653Configuration page with theme/org/role/preview/hotspot buttons
leds_install()9707Database initialization — creates all tables and inserts default data

12.2 Database Functions

FunctionLinePurpose
newpdo($dbfile)6595Create SQLite PDO connection
pdo_create($dbfile, $tblname, $sql)9785Create a new database table (drop + create)
pdo_insert($dbfile, $tblname, $data)9799Insert a row into a table from CSV/PSV file
pdo_cr_leds()9929Create the leds table
pdo_cr_kb()9981Create the KB (koaac_kb) table
pdo_cr_nodes()10132Create the nodes table
pdo_cr_roles()10166Create the roles table
pdo_cr_users()10178Create the users table
pdo_cr_fp()10200Create the floor plan (fp) table
pdo_cr_grid()10220Create the grid table
pdo_cr_us()10240Create the us (user-specific) table
pdo_cr_hw()10261Create the hw table
pdo_cr_n11()10282Create the n11 table
pdo_cr_dbs()15641Create the dbs (database registry) table
pdo_cr_flds()15728Create the flds (fields) table
pdo_cr_menus()9981Create the menus table
pdo_insert_leds()10305Insert default LED records
pdo_insert_nodes()10423Insert default node records
pdo_insert_roles()10474Insert default role records
pdo_insert_users()10491Insert default user records
pdo_insert_fp()10516Insert default floor plan records
pdo_insert_grid()10538Insert default grid records
pdo_insert_us()10552Insert default user-specific records
pdo_insert_hw()10570Insert default hardware records
pdo_insert_n11()10586Insert default n11 records
pdo_insert_obj()10600Insert default object records
pdo_insert_pano()10621Insert default panorama records
pdo_insert_dbs()15754Insert default database registry records
pdo_cr_fgmenu()9981Create the fgmenu table
pdo_insert_fgmenu()9994Insert default fgmenu records

12.3 Grid & Data Display Functions

FunctionLinePurpose
pdo_grid($options)10686Generate sortable/filterable database grid view
pdo_gridxml($options)11021Export grid data as XML
pdo_unload($options)11693Unload/export table data
pdo_list($options)11786List all database tables
pdo_update($options)11790Update table data (inline editing)
pdo_load($options)11794Load table data for editing
sql_view($options)9645SQL query interface
leds_view($options)9685Generic data view
leds_list($options)9689Generic data listing
leds_test($options)9694Test/diagnostic view

12.4 Report Functions

FunctionLinePurpose
leds_reports_sql($options)3681SQL query interface for custom reports
leds_reports_csv($dbfile, $sql, $csvfil)3841Export report data as CSV
leds_reports_rpt($options)3931Generate formatted report with print/export options
rptsxml($options)16043XML report generation
rpts($options)16134Report listing and management
reports_menu($code)3377Generate report navigation menu

12.5 KB (Knowledge Base) Functions

FunctionLinePurpose
leds_kb($options)12401Knowledge Base listing
leds_kb_rpts($options)12594KB reports
koaac_kb_new_form($options)4844New KB entry form
koaac_kb_add_form($options)5436Add KB entry form
koaac_kb_upload($kbid)5690KB file upload handler
kbwrite($kbfil, $kbrec)4661Write KB record to file
kb_ls($options, $path)4701List KB files in directory
kb_mkdir($kbpath, $kbid)6031Create KB directory structure

12.6 Utility Functions

FunctionLinePurpose
logwrite($logfil, $logrec)4673Write a record to the log file
logdump($logfil)4683Dump entire log file contents
bugfile($options)10993Write comprehensive debug info to fp_bugs.txt
ko_unique()14904Generate UUID
ko_unique1()14909Generate short unique ID (8 chars)
pc_encode($data)14918PC encoding (obfuscation/encoding)
pc_decode($data, $hash)14923PC decoding
datediff($interval, $date1, $date2)14939Calculate difference between two dates
datediff_leds($diffdays)14951LED-specific date difference (returns color, speed, days)
iperms($options)6425System permissions/utility functions (periods, job2db)
localcmds($options)15887Local command execution interface
telnet($options)15939Telnet connection utility
ko_imap($options)14700IMAP email functions
email_headers()16117Email header generation
leds_process($title, $cmd, $cwd)6485Execute shell process and display formatted output
leds_process_psv($title, $cmd, $cwd)6519Execute Perl script process and display output
leds_process_value($title, $cmd, $cwd)6560Execute command and return value

12.7 AJAX Functions

FunctionLinePurpose
ko_ajax($options)2508AJAX request handler (test1: login simulation with refreshPage event)
ko_ajax_controller($options)2532Generate AJAX controller JavaScript (LoginController)
ko_ajax_listener($options)2555Generate AJAX listener JavaScript (event handling)
ko_ajax_app($options)2580Generate AJAX app JavaScript (includes refreshPage → window.location.reload)
ko_ajax_complete($options)2599Generate AJAX complete handler (global AJAX event dispatcher)
ko_ajax_result($options)2616Generate ServiceResult JavaScript class

12.8 View/Page Functions

FunctionLinePurpose
leds_zm5($options)7271Zoom level 5 viewer
leds_zoom($options)13443Zoom viewer with hotspot navigation
html_zoom_detail($options)8072Zoom detail view with XML hotspot config
leds_ptviewer($options)13368Panorama/tour viewer
leds_ptobject($options)13835Individual panorama object viewer
leds_zview($options)13835ZView display
leds_zview_xml($options)13952ZView XML generation
leds_zview_details($options)13999ZView detail rendering
leds_zview_xmlnew($options)14057Create new ZView XML configuration
leds_zoomxml($options)14181Zoom XML export
html_links($options)13434Links page
pchart_pie($options)4470pChart pie chart display
scrub_view($options)6108Scrub/data cleanup view
scrub_show($options)6859Scrub display with file listing
scrub_upload_form($options)9085Scrub file upload form
scrub_upload($user)9154Process scrub file upload
ko_upload2()9422File upload handler
ko_uploads()9466List uploaded files
leds_update_form($options)8776LED update form
leds_update($options)8992Process LED update

12.9 Special-Purpose Functions

FunctionLinePurpose
im_identify($filemask)4300ImageMagick file identification
key2png($key, $val)4339Key-value to PNG conversion
sqlq($dbfile, $sql, $fld)2801Execute SQL query and return field value
sql_updform(...)4410SQL update form generation
csv2db3($csvfil, $delimiter)3619Import CSV file into database
getfiles($path, $mask)6075List files matching a mask in a directory
fgmenu_head($options)14976Generate fg-menu head HTML
fgmenu_js($options)15032Generate fg-menu JavaScript
fgmenu_htm($options)15075Generate fg-menu HTML
fgmenu_dyn($options)15129Generate dynamic fg-menu
menutree(...)15313Recursive menu tree builder
head_jqui_css($options)14518Generate jQuery UI CSS includes
jqui($jqui)16260jQuery UI component generator
css_rollovers_head($options)14644Generate CSS rollover styles
js_rollover($options)14633Generate JavaScript rollover code
html_btn_hotspots($options, $callback)6673Generate hotspot type buttons
html_btn_orgs($options, $callback)6729Generate organization type buttons
html_btn_preview($options, $callback)6756Generate preview mode toggle button
html_btn_roles($options, $callback)6783Generate role type buttons
html_btn_themes($options, $callback)6812Generate theme selection buttons
html_btn_footer($options)7431Generate footer button row
html_dc_links($option)7664Generate datacenter links
html_kb_links($options)7687Generate KB navigation links
html_nodes_links($options)7707Generate node navigation links
html_scrub($options)7728Generate scrub navigation
ko_sessions_start()14823Session initialization
ko_sessions()14833Session management
ko_validata()14842Validation function
ko_validate_form()14862Form validation
ko_validate_form_user($user)14872Validate username
ko_validate_form_pass($pass)14874Validate password
ko_print_form($errors)14877Print form with error messages
leds_login_form($options)8450Login form with jqGrid integration
ldap_authenticate()8525LDAP authentication (commented out)
ko_dragdrop_redirect($options)2630Drag-and-drop redirect handler
ko_dragdrop($options)2646Drag-and-drop interface
dragdrop_test1($options)2697Drag-and-drop test page
ko_im($options)2778Image manipulation interface
leds_leds($options)3428LED management interface
leds_ko_centerd_rpts($options)13137ko_centerd reports
leds_nodes_rpts($options)13252Node reports
leds_certs_rpts($options)12801Certificate reports
leds_cons_rpts($options)12907Console reports
leds_hosts_rpts($options)13013Host reports
leds_dc_rpts($options)12696Datacenter reports
leds_plans($options)Plan listing and management
leds_hw($options)4560Hardware inventory view
leds_certs($options)12164Certificate listing
leds_cons($options)12282Console listing
leds_hosts($options)12401Host listing
leds_ko_centerd_rpts($options)13137ko_centerd reports
leds_reports_sql($options)3681SQL report interface
leds_reports_csv($dbfile, $sql, $csvfil)3841CSV report export
leds_reports_rpt($options)3931Formatted report generator
leds_menu($options)9645Navigation menu generator
ko_plans_items($options)2819Plan items view
ko_plans_steps($options)2920Plan steps view
ko_plans1($options)3132Plan view v1
ko_plans_save($options)3138Plan save handler
ko_co($options)ko_center main page handler
anonymous_option1/2/3($options)6402-6404Guest anonymous role options
guest_option1/2/3($options)6405-6407Guest role options
user_option1/2/3($options)6408-6410User role options
qc_option1/2/3($options)6411-6413QC role options
manager_option1/2/3($options)6414-6416Manager role options
operator_option1/2/3($options)6417-6419Operator role options
admin_option1/2/3($options)6420-6422Admin role options
iperms($options)6425System permissions (periods_p, periods_pp, job2db)
datediff($interval, $date1, $date2)14939Date difference calculator
datediff_leds($diffdays)14951LED date difference (returns color/speed for LED status)
sql3_select_hallo($db3file, $db3tbl, $ip)6108SQLite3 select for hallo table
sql3_insert_hallo($db3file, $db3tbl)6131SQLite3 insert for hallo table

13. Deployment & Server Configuration

13.1 Apache Virtual Host Configuration

<VirtualHost *:80>
    ServerName ko_center.example.com
    DocumentRoot /os/ai/io

    <Directory /os/ai/io>
        Options +FollowSymLinks
        AllowOverride None
        Require all granted
    </Directory>

    # PHP configuration
    php_value upload_max_filesize 50M
    php_value post_max_size 50M
    php_value max_execution_time 300
    php_value memory_limit 256M

    # SQLite configuration
    php_value sqlite.assoc_case 0

    # Logging
    ErrorLog /var/log/apache2/ko_center_error.log
    CustomLog /var/log/apache2/ko_center_access.log combined

    # Security headers
    Header set X-Content-Type-Options "nosniff"
    Header set X-Frame-Options "SAMEORIGIN"
</VirtualHost>

13.2 Environment Variables

VariableDefaultDescription
KO_THEMEredmondjQuery UI theme name
KO_DB_FILE/os/ai/io/ko_center.db3Database file path
KO_HOSTS_ALLOW/os/ai/io/../safer/hosts.allowAuthentication file path
KO_LOG_DIR/os/ai/io/../ko_saferLog file directory
KO_TRIGGER_FILE/os/ai/io/ko_trigger.datTrigger timestamp file

13.3 PHP Configuration Recommendations

; php.ini or .htaccess settings for ko_center

memory_limit = 256M
max_execution_time = 300
upload_max_filesize = 50M
post_max_size = 50M

; SQLite
sqlite3.extension_dir = ""

; Session
session.gc_maxlifetime = 1440
session.cookie_httponly = 1
session.cookie_samesite = "Lax"

; Error reporting (production)
display_errors = Off
log_errors = On
error_log = /var/log/php_errors.log

14. Python Flask Equivalent

A Python Flask equivalent of ko_center.php has been created at /os/ai/io/ko_center.py. Key differences:

AspectPHP VersionPython Version
Web FrameworkApache + mod_phpFlask (built-in dev server)
Routing?q=page/action/id parsed manually in startup()Flask @app.route decorators
DatabasePDO SQLitePython sqlite3 module
Sessions$_SESSIONFlask session
HTML GenerationString concatenation in functionsString concatenation in functions
Authenticationhosts.allow file checkSame hosts.allow file check
AJAXjQuery AJAX + custom ko_ajax functionsFlask jsonify() + jQuery AJAX
File Upload$_FILES superglobalFlask request.files
Process Executionsystem(), exec(), passthru()subprocess module
Trigger Endpoint?q=trigger (file-based)/trigger route (file-based)

Running the Python version:

python3 /os/ai/io/ko_center.py

Then browse to http://localhost:5000

15. API & URL Routing Reference

15.1 Complete Route Reference

Route PatternMethodHandler FunctionDescription
?q=ledsGETleds_show()Display LED indicators
?q=leds/detail/<name>GETleds_detail()LED detail view
?q=aboutGETleds_about()About page
?q=loginGETleds_login_form()Login form
?q=login_validatePOSTleds_login_validate()Process login
?q=logoutGETleds_logout()Logout
?q=configGETleds_config()Configuration page
?q=triggerGEThandle_trigger()Broadcast trigger (JSON)
?q=ko_ajaxGETko_ajax()AJAX handler
?q=ko_dragdropGETko_dragdrop()Drag and drop interface
?q=ko_imGETko_im()Image manipulation
?q=grid?dbcode=<db>&table=<tbl>GETpdo_grid()Database grid view
?q=reports/sqlGETleds_reports_sql()SQL query interface
?q=reports/rpt/<code>GETleds_reports_rpt()Run named report
?q=kbGETleds_kb()KB listing
?q=kb/newGETkoaac_kb_new_form()New KB entry form
?q=kb/view/<id>GETleds_kb()View KB entry
?q=certsGETleds_certs()Certificate listing
?q=nodesGETleds_hosts()Node listing
?q=hwGETleds_hw()Hardware inventory
?q=hw?cab=<cab>GETleds_hw()Hardware filtered by cabinet
?q=hw?sn=<sn>GETleds_hw()Hardware filtered by serial number
?q=hw?ip=<ip>GETleds_hw()Hardware filtered by IP
?q=hw?hrctag=<tag>GETleds_hw()Hardware filtered by HRC tag
?q=plansGETleds_plans()Plan listing
?q=sqlGETsql_view()SQL query interface
?q=zoom/<code>/<type>/<rowid>GETleds_zoom()Zoom viewer
?q=zview/<file>/<xml>GETleds_zview()Full-screen zoom view
?q=ptviewerGETleds_ptviewer()Panorama viewer
?q=ptobjectGETleds_ptobject()Panorama object viewer
?q=scrubGETscrub_view()Scrub/data cleanup
?q=uploadGET/POSTko_upload2()File upload
?q=pdo_cr_kbGETpdo_cr_kb()Create KB table
?q=pdo_cr_ledsGETpdo_cr_leds()Create leds table
?q=pdo_insert_ledsGETpdo_insert_leds()Insert LED record
?q=pdo_listGETpdo_list()List database tables
?q=pdo_unload?dbcode=<db>&table=<tbl>GETpdo_unload()Unload/export table
?q=pdo_updateGETpdo_update()Update table data
?q=pdo_loadGETpdo_load()Load table data
?q=pdo_gridxml?dbcode=<db>&table=<tbl>GETpdo_gridxml()Grid XML export
?q=dc_rptsGETleds_dc_rpts()Datacenter reports
?q=kb_rptsGETleds_kb_rpts()KB reports
?q=certs_rptsGETleds_certs_rpts()Certificate reports
?q=cons_rptsGETleds_cons_rpts()Console reports
?q=hosts_rptsGETleds_hosts_rpts()Host reports
?q=ko_centerd_rptsGETleds_ko_centerd_rpts()ko_centerd reports
?q=nodes_rptsGETleds_nodes_rpts()Node reports
?q=form_request_accessGETinline HTMLAccess request form
?q=konetGETinline HTMLContact information
?q=pdoGETinline HTMLDatabase table listing
?q=toolsGETinline HTMLTools page
?q=update/<name>GETleds_update_form()LED update form
?q=ipermsGETiperms()System permissions utility
?q=iperms/periods_pGETiperms()Run periods_p Perl script
?q=iperms/job2db/mkwlGETiperms()Run mkwl job
?q=linksGEThtml_links()Links page

15.2 Trigger API

The trigger endpoint provides a JSON API for browser refresh coordination across multiple clients:

Request

GET /ko_center/ko_center.php?q=trigger[&last_check=<timestamp>]

Response

{
  "triggered": true|false,
  "timestamp": "2026-08-01 07:05:00",
  "since": "2026-08-01 07:00:00"
}

Workflow

  1. Browser A polls ?q=trigger every 3 seconds
  2. Browser B calls ?q=trigger (writes timestamp to ko_trigger.dat)
  3. Browser A's next poll detects the new timestamp
  4. Browser A calls window.location.reload()

16. Version History

VersionDateChanges
v0.702026-08-01Current: q=leds_context, ranks, randomus, actions
v0.672025-03-25q=login debug
v0.662025-03-25ERR_210 /etc/hosts.allow fix
v0.652020-10-14fpbimg support
v0.642020-09-25sql3_insert_hallo, sql3_select_hallo
v0.642020-09-23Bug fixes, blank page fixes
v0.642019-08-27leds_dragdrop support
v0.642012-12-10leds_dragdrop initial
v0.642012-12-07ko_ajax, ko_dragdrop, ko_im added
v0.642012-12-02reports/rpts img, cab/cab1/cab2, leds/set/ledcode
v0.632012-12-02reports/sql
v0.622012-12-02reports/sql
v0.612012-11-09defrag/report
v0.602012-10-27passthru() support
v0.592012-10-27hostos win logic
v0.572012-09-27gui mods/allow
v0.562012-09-26datacall support
v0.552012-09-18ko_center_hosts.db3 datacall
v0.542012-09-18ko_center_cons.db3
v0.532012-08-29new /pat url, /nap
v0.522012-08-29?q=kb/rpts/rpt_id&fmt=xml & fmt=csv
v0.512012-08-28rptsxml
v0.502012-08-28jqgrid-4.4.0 integration
v0.492012-08-24errtxt, fixtxt to files, fmt4search
v0.482012-08-24ko_center.db3 nodes tables & reports
v0.472012-08-23ko_center_certs
v0.462012-08-23kb upload size increase
v0.452012-08-22ko_centerd rpts view grids
v0.442012-08-22mod views
v0.432012-08-17mod views
v0.422012-08-16logins for led tweets
v0.412012-08-16?q=certs/rpts
v0.402012-08-16?q=kb/rpts
v0.392012-08-14ko_center main page org
v0.382012-08-13?q=kb/view kb/mod dbgrid links for kb certs
v0.372012-08-09links reorg + certs
v0.362012-08-09?q=kb
v0.352012-08-09itil to links
v0.352012-08-08ko_center_certs.dbe
v0.342012-08-03dyn pchart example link & debug
v0.332012-08-01pchart link
v0.322012-07-30pdo_cr_kb, pdo_cr_flds, new/add/mod/upd/view
v0.312012-07-30pdo_cr_kb, pdo_cr_flds
v0.302012-07-27pdo_cr_kb
v0.292012-07-27newpass1 newpass2
v0.282012-07-27user=hosts.allow[2]
v0.27q=sql/cr/kb
v0.26newpass1 newpass2
v0.25user info from hosts.allow
v0.242012-07-20session role check
v0.232012-07-20es/hs,vg,bp/ ...
v0.222012-07-20es/us/koSYS_us.php ko_center/us/koSYS_us.php
v0.212012-06-27rename scrub update to scrub
v0.202012-06-19korhe_us.db3
v0.192012-06-19koaix_us.db3
v0.182012-06-18add kb, bp tables
v0.172012-06-08add kb, bp tables
v0.162012-06-05add ko_center tables
v0.152012-06-01add hs tables
v0.142012-05-31add grid tables users us
v0.132012-05-31$files=getfilko_center( $path, $mask )
v0.122012-05-31gunzip scrubfile accommodation
v0.112012-05-31add serena link
v0.102012-05-16refresh to kohpx_vg.php kohpx_us.php kohpx_sw.php
v0.092012-04-25db3 grid from /home/ko/vg/kohpx_vg.db3
v0.082012-03-13q=links, sw reports pending
v0.072012-03-13btn_footers
v0.062012-03-13q=scrub consolidate upload examples
v0.052012-02-16ko_upload scrub2
v0.042012-02-16ko_upload scrub
v0.032012-02-07Initial development
v0.022012-02-07Initial version
v0.012012-02-05First release