ko_center System Administrator Documentation

Version: v0.70 (2026-08-01)
Type: PHP/Perl Web Application (Single-File Architecture)
Primary File: /os/ai/io/ko_center.php (16,322 lines, 205 functions)
Database: SQLite 3 (ko_center.db3, ~39.6 MB)
Web Server: Apache (with PHP) or Python Flask (equivalent: ko_center.py)
Document Type: System Administrator Guide

Table of Contents

1. System Architecture

1.1 Overview

ko_center is a single-file PHP web application that provides a centralized dashboard for managing LED indicators, database grids, knowledge base articles, hardware inventory, and various system monitoring tools.

The application follows a traditional LAMP-style architecture:

1.2 Request Flow

Browser Request
    |
    v
Apache/PHP (ko_center.php)
    |
    +--> startup()          [Initialize session, globals, paths]
    |
    +--> Parse ?q= parameter
    |       Split by "/" into options[] array
    |       options[0] = page, options[1] = action, options[2] = id, etc.
    |
    +--> Route to handler function
            |
            +--> leds_show()     - Display LED indicators
            +--> pdo_grid()      - Database grid view
            +--> leds_kb()       - Knowledge Base
            +--> leds_reports_*  - Reports (SQL, CSV, XML)
            +--> leds_config()   - Configuration
            +--> leds_login_*    - Authentication
            +--> trigger()       - Broadcast refresh
            +--> iperms()        - System utilities
            +--> ko_upload*      - File uploads
            +--> pdo_cr_*        - Table creation
            +--> pdo_insert_*    - Data insertion
            +--> ... (205 functions total)
    |
    +--> Generate HTML output
    |       html_header()   -  section
    |       html_btn_squares() - Navigation buttons
    |       [page content]
    |       html_footer()   - 
    |
    v
Browser renders HTML

1.3 Key Design Patterns

2. Installation & Setup

2.1 Prerequisites

ComponentRequirement
Web ServerApache 2.x with mod_php, or Python 3.x with Flask
PHPPHP 5.3+ (uses PDO, sessions, $_REQUEST)
SQLiteSQLite 3 with PHP PDO extension
ImageMagickRequired for LED GIF generation (cr_leds.py)
PerlRequired for iperms utility functions
Disk Space~50 MB minimum (database + images + logs)

2.2 Installation Steps

Step 1: Deploy files

cp ko_center.php /var/www/html/ko_center/
cp ko_center.db3 /var/www/html/ko_center/db3/
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
mkdir -p /var/www/html/ko_center/kb
mkdir -p /var/www/html/ko_center/db3

Step 2: Set permissions

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

Step 3: Configure hosts.allow

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

allow all
# or format: allow user role

Step 4: Initialize database (if new install)

Access http://<host>/ko_center/ko_center.php in a browser. If the database file doesn't exist, the leds_install("new") function is called automatically, creating all core tables.

Step 5: Verify installation

Navigate to ?q=about or ?q=pdo to verify the database connection and table creation.

2.3 First-Time Install (leds_install)

The leds_install() function (line 9707) creates all database tables and inserts default data:

TableFunctionDescription
ledspdo_cr_leds() + pdo_insert_leds()LED indicator records
nodespdo_cr_nodes() + pdo_insert_nodes()Network nodes
rolespdo_cr_roles() + pdo_insert_roles()User roles
userspdo_cr_users() + pdo_insert_users()User accounts
fppdo_cr_fp() + pdo_insert_fp()Floor plan data
gridpdo_cr_grid() + pdo_insert_grid()Grid configuration
uspdo_cr_us() + pdo_insert_us()User-specific data
hwpdo_cr_hw() + pdo_insert_hw()Hardware inventory
n11pdo_cr_n11() + pdo_insert_n11()N11 monitoring
objpdo_cr_obj() + pdo_insert_obj()Object data
panopdo_cr_pano() + pdo_insert_pano()Panorama data
dbspdo_cr_dbs() + pdo_insert_dbs()Database registry
menuspdo_cr_menus() + pdo_insert_menus()Menu definitions
ko_plansCreated via pdo_crProject plans
ko_hwCreated via pdo_crHardware details
koaac_kbpdo_cr_kb()Knowledge Base
ko_center_certsCreated via pdo_crCertificates

3. Configuration

3.1 Global Configuration Variables

All configuration is set in the startup() function (line 101) via $GLOBALS:

VariableDefault ValueDescription
$GLOBALS['dbfile']$document_root/ko_center/db3/ko_center.db3Path to SQLite database
$GLOBALS['kbfile']$document_root/ko_center/db3/koaac_kb.db3Path to KB database
$GLOBALS['kb_rootpath']$document_root/ko_center/kbKB file storage path
$GLOBALS['kbpath']$document_root/ko_center/kbKB path (alias of kb_rootpath)
$GLOBALS['hosts_allow']$document_root/../safer/hosts.allowAuthentication file
$GLOBALS['ko_center_certsfile']$document_root/ko_center/db3/ko_center_certs.db3Certificates database
$GLOBALS['logfil']$logfil_rootpath/ko_center_YYYYMM.logLog file path
$GLOBALS['progid']"ko_center"Program identifier
$GLOBALS['tblname']"leds"Default table name for LED operations
$GLOBALS['dbfiles']Array of database configsMulti-database registry for role-based access
$GLOBALS['roles']Array of role definitionsRole-based access control
$GLOBALS['themes']Array of jQuery UI theme namesAvailable UI themes
$GLOBALS['allowflag']From hosts.allow fileAccess control flag
$GLOBALS['kb_user']From hosts.allow field 2KB user identifier
$GLOBALS['screenshots_pcharts']"" (empty)pChart screenshot path
$GLOBALS['js_output']falseJavaScript output flag

3.2 Configuration Settings

SettingLocationDescription
path_btnstartup() line 130Button images path: /ko_center/images/btn
path_anistartup() line 131Animated GIF path: /ko_center/images/ani
path_fpbleds_show() line 6905Floor plan button images: /ko_center/images/fpb
themeSession variablejQuery UI theme: redmond, humanity, frog, swanky, etc.
previewSession variablePreview mode on/off
grid_zoomSession variableGrid zoom toggle
hs_typeSession variableHotspot type filter
org_typeSession variableOrganization type filter

4. Database Administration

4.1 Database File

PropertyValue
File/os/ai/io/ko_center.db3
TypeSQLite 3
Size~39.6 MB
Tables30+ tables
AccessVia PHP PDO (newpdo() function)

4.2 Database Connection

The newpdo() function (line 6595) creates SQLite connections:

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

4.3 Key Database Tables

TablePurposeKey Columns
ledsLED indicator recordsled_id, led_name, led_color, led_speed, led_type, led_dttm, led_cmd, led_desc
randomusRandom user datagender, title, fname, lname_last, email, login_user, login_pass, etc.
leds_randomusCombined LED + randomusAll leds columns (NULL) + all randomus columns
ko_plansProject plansid, name, status, steps, items
ko_hwHardware inventoryled_name, cab, item, model, sn, ip, hrctag, hostname, machinename, amps, btu
koaac_kbKnowledge Basekb_id, kb_title, kb_body, kb_dttm, kb_user, kb_type
nodesNetwork nodesnode_id, node_code, node_name, node_status, node_city, node_bldg
rolesUser rolesrole definitions and permissions
usersUser accountsuser credentials and role assignments
cabsCabinet/rack dataCabinet information
cfgConfigurationSystem configuration key-value pairs
dbsDatabase registryMulti-database connection configs
menusMenu definitionsNavigation menu structure
fpFloor plan dataFloor plan references
gridGrid configurationGrid view settings
usUser-specific dataPer-user preferences
n11N11 monitoringN11 alert data
panoPanorama dataPanorama/tour references
objObject dataObject references
zoomZoom configurationZoom viewer settings
zoomxmlZoom XML dataHotspot XML configurations
shelvesShelf dataShelf/rack shelf data
halloHallo dataHallo records
haloHalo dataHalo records
nimbusNimbus dataNimbus records
aureoleAureole dataAureole records
leds_defaultsLED defaultsDefault LED settings
leds_racksLED rack mappingsLED-to-rack mappings
periodsTime periodsReporting periods
rptsReport definitionsReport SQL and metadata
hrc_datacenters_equipmentDC equipmentDatacenter equipment inventory
defrag_planDefrag plansDefragmentation plans
defrag_plansumDefrag plan summariesSummary data for defrag plans
hrc_dc_*Various DC tablesDatacenter-specific data
es_ipIP dataIP address tracking
es_hwExtended HW dataExtended hardware info
kohw_*Hardware variantsHardware table variants
kocabCabinet dataCabinet details
kohwHardware dataHardware records
koplansPlan dataPlan records

4.4 Database Maintenance Commands

# Check database integrity
sqlite3 /os/ai/io/ko_center.db3 "PRAGMA integrity_check;"

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

# Get table row counts
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 the database (reclaim space)
sqlite3 /os/ai/io/ko_center.db3 "VACUUM;"

# Backup the database
cp /os/ai/io/ko_center.db3 /os/ai/io/ko_center.db3.backup.$(date +%Y%m%d)

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

4.5 Creating New Tables

Use the pdo_create() function (line 9785) or the pdo_cr_*() functions for table creation:

function pdo_create( $dbfile, $tblname, $sql ) {
    $pdo = newpdo( $dbfile );
    $pdo->exec("DROP TABLE IF EXISTS $tblname");
    $pdo->exec($sql);
    $pdo = null;
}

5. User & Role Management

5.1 Authentication Flow

  1. User accesses ?q=loginleds_login_form()
  2. User submits credentials → leds_login_validate()
  3. Credentials checked against hosts.allow file
  4. On success: $_SESSION['user'] and $_SESSION['role'] set
  5. On failure: Login form redisplayed

5.2 Role-Based Access

The system supports the following roles (from the PHP code):

RoleDescriptionAccess Level
guestUnauthenticated userRead-only, limited features
userStandard authenticated userView LED status, basic navigation
qcQuality controlView + QC-specific features
managerManagerView + management features
operatorOperatorView + operational features
adminAdministratorFull access, all features

5.3 Session Variables

VariableSet ByDescription
$_SESSION['user']leds_login_validate()Username
$_SESSION['role']leds_login_validate()User role
$_SESSION['preview']User togglePreview mode (on/off)
$_SESSION['theme']User selectionUI theme
$_SESSION['grid_zoom']User toggleGrid zoom state
$_SESSION['hs_type']User selectionHotspot type
$_SESSION['org_type']User selectionOrganization type
$_SESSION['gridimgpath']js_scripts()Theme image path

6. Security

Security Warning: ko_center.php is a legacy application with several known security concerns. Review and address these before deploying in a production environment.

6.1 Known Security Issues

IssueLocationRiskMitigation
SQL Injection leds_show() line 6939, multiple grid functions High Use prepared statements instead of string interpolation in SQL queries
No CSRF Protection All form submissions Medium Add CSRF tokens to all forms
No XSS Filtering All user input displayed Medium Use htmlspecialchars() on all user-supplied output
Plain Text Passwords randomus table (login_pass column) High Hash passwords with bcrypt or Argon2
No Rate Limiting Login form, all endpoints Medium Implement rate limiting on authentication endpoints
Directory Traversal File operations in kb, upload High Sanitize all file paths, restrict to allowed directories
Error Reporting Disabled startup() line 107: error_reporting(0) Low Enable error logging to file in production; disable display
Shell Command Injection leds_process(), iperms(), localcmds() Critical Avoid passing user input to shell commands; use escapeshellarg()

6.2 Authentication

The authentication system uses a simple hosts.allow file check:

$allowflag = file_get_contents($GLOBALS['hosts_allow']);
$allowflag_fields = explode(" ", $allowflag);
$user = $allowflag_fields[2];

This is a very basic authentication mechanism. For production use, consider implementing proper password hashing and database-based authentication.

6.3 Session Security

The PHP session configuration is minimal. Consider adding:

7. Logging & Debugging

7.1 Log File Configuration

Log files are created in the ko_safer directory with a monthly naming convention:

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

The log file path is constructed in startup() (line 145-148):

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

7.2 Logging Functions

FunctionLineDescription
logwrite($logfil, $logrec)4673Write a record to the log file
logdump($logfil)4683Dump entire log file contents
bugfile($options)10993Write debug info to fp_bugs.txt (dbfile, url_table, page, etc.)

7.3 Debugging

Debug output is controlled by commented-out print statements throughout the code. To enable debugging:

  1. Remove the // comment markers from debug print statements
  2. Set error_reporting(E_ALL) in startup() (currently set to 0)
  3. Check the log file: /os/ai/io/../ko_safer/ko_center_YYYYMM.log
  4. Use ?q=about or ?q=pdo for basic diagnostics

7.4 Error Handling

The PHP error reporting is disabled (error_reporting(0) at line 107). Errors are silently suppressed. The application uses custom error messages embedded in HTML output rather than PHP exceptions.

8. Backup & Recovery

8.1 Backup Strategy

# Daily backup script
#!/bin/bash
DB="/os/ai/io/ko_center.db3"
BACKUP_DIR="/os/ai/io/backups"
DATE=$(date +%Y%m%d_%H%M%S)

mkdir -p $BACKUP_DIR
cp $DB "$BACKUP_DIR/ko_center_$DATE.db3"
gzip "$BACKUP_DIR/ko_center_$DATE.db3"

# Keep only last 30 days
find $BACKUP_DIR -name "ko_center_*.db3.gz" -mtime +30 -delete

8.2 Recovery Procedure

  1. Stop the web server
  2. Copy backup file to database location:
    cp /os/ai/io/backups/ko_center_YYYYMMDD_HHMMSS.db3.gz /os/ai/io/ko_center.db3.gz
  3. Decompress: gunzip /os/ai/io/ko_center.db3.gz
  4. Verify integrity: sqlite3 /os/ai/io/ko_center.db3 "PRAGMA integrity_check;"
  5. Set correct permissions: chown www-data:www-data /os/ai/io/ko_center.db3
  6. Start the web server

8.3 Important Files to Backup

FileDescription
/os/ai/io/ko_center.db3Main SQLite database
/os/ai/io/ko_center_certs.db3Certificates database
/os/ai/io/koaac_kb.db3Knowledge Base database
/os/ai/io/safer/hosts.allowAuthentication/authorization file
/os/ai/io/ko_center.phpApplication source code
/os/ai/io/images/Button, animation, and floor plan images
/os/ai/io/ko_center/kb/Knowledge Base file attachments
/os/ai/io/../ko_safer/Log files

9. Maintenance Tasks

9.1 Routine Maintenance

TaskFrequencyCommand/Action
Database backupDailyCopy ko_center.db3 to backup directory
Log rotationMonthlyCompress old log files, delete logs older than 90 days
Database vacuumMonthlysqlite3 ko_center.db3 "VACUUM;"
Disk space checkWeeklydf -h /os/ai/io/
File permissions checkWeeklyVerify db3 file is writable by web server
Image asset checkMonthlyVerify btn/, ani/, fpb/ directories have expected images
KB cleanupMonthlyRemove old or unused KB entries
LED record cleanupMonthlyArchive or delete old LED records (led_dttm != 'current')

9.2 LED Record Management

LED records use led_dttm = 'current' to mark active records. Historical records can be archived or deleted:

-- Archive old LED records
INSERT INTO leds_archive SELECT * FROM leds WHERE led_dttm != 'current';
DELETE FROM leds WHERE led_dttm != 'current';

9.3 Database Optimization

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

# Analyze tables for query optimization
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;"

10. Troubleshooting

10.1 Common Issues

SymptomCauseSolution
Blank page PHP error suppressed by error_reporting(0) Enable error reporting temporarily: change error_reporting(0) to error_reporting(E_ALL) in startup()
Database not found error ko_center.db3 missing or wrong path Verify $GLOBALS['dbfile'] path in startup(); run leds_install("new")
Permission denied Web server user cannot write to db3 file or directories chown www-data:www-data ko_center.db3; chmod 666 ko_center.db3
LED images not showing Missing ani_*.gif files in images/ani/ Run python3 cr_leds.py to generate LED GIF images
Button images not showing Missing btn_*.gif files in images/btn/ Verify button images exist in /os/ai/io/images/btn/
Login fails hosts.allow file missing or wrong format Check /os/ai/io/../safer/hosts.allow exists and has correct format
Trigger not working ko_trigger.dat file not writable touch /os/ai/io/ko_trigger.dat && chmod 666 /os/ai/io/ko_trigger.dat
Grid view empty Table doesn't exist or has no data Verify table exists in database; check SQL query
Report export fails CSV/XML export path issues Check file write permissions in report output directory
Slow page loads Large database (39.6 MB), complex queries Run VACUUM and ANALYZE; add indexes to frequently queried columns

10.2 Debug Checklist

  1. Check if PHP is running: php -v
  2. Check if database exists: ls -la /os/ai/io/ko_center.db3
  3. Check database integrity: sqlite3 ko_center.db3 "PRAGMA integrity_check;"
  4. Check web server error log: tail -f /var/log/apache2/error.log
  5. Check application log: ls -la /os/ai/io/../ko_safer/
  6. Verify file permissions on all directories
  7. Test with ?q=about to verify basic functionality
  8. Test with ?q=pdo to verify database connectivity

11. File Structure & Assets

11.1 Directory Layout

/os/ai/io/
├── ko_center.php          # Main application (16,322 lines)
├── ko_center.db3          # SQLite database (39.6 MB)
├── ko_center.md           # Documentation (markdown)
├── ko_center.txt          # Documentation (text)
├── ko_center.py           # Python Flask equivalent
├── new_leds.py            # Create leds_randomus table
├── new_leds_tbl.py        # Generalized table creation script
├── cr_leds.py             # LED GIF generation script
├── ko_trigger.dat         # Trigger timestamp file (runtime)
├── prompt_*.txt           # Original task prompts
├── response_*.txt         # Response documents
├── images/
│   ├── btn/               # Button images (btn_black.gif, btn_white.gif, etc.)
│   ├── ani/               # Animated LED GIFs (ani_red0.gif, etc.)
│   ├── 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
├── ../safer/
│   └── hosts.allow        # Authentication/authorization file
├── ../ko_safer/
│   └── ko_center_YYYYMM.log  # Monthly log files
├── 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
│   └── tooltip/           # Tooltip JavaScript
└── css/
    └── (theme CSS files)

11.2 Image Assets

DirectoryContentGenerated By
images/btn/Button GIFs (btn_black.gif, btn_white.gif, btn_red.gif, etc.)Manual creation
images/ani/LED animated GIFs (ani_red0.gif through ani_trans3.gif)cr_leds.py
images/fpb/Floor plan button images and thumbnailsManual creation
images/cab/Cabinet/rack imagesManual creation

12. PHP Function Reference

12.1 Core Functions

FunctionLinePurpose
startup()101Application initialization: session, globals, paths, config
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 function - queries DB and renders LED grid
leds_detail()7759LED detail view with associated hardware items
leds_about()6323About page
leds_login_form()8450Login form HTML
leds_login_validate()8568Login credential validation
leds_logout()8739Session cleanup and redirect
leds_config()6653Configuration page with theme/org/role/preview buttons
leds_install()9707Database initialization - creates all tables and default data

12.2 Database Functions

FunctionLinePurpose
newpdo($dbfile)6595Create SQLite PDO connection
pdo_create($dbfile, $tblname, $sql)9785Create a new database table
pdo_insert($dbfile, $tblname, $data)9799Insert a row into a table
pdo_cr_leds()9929Create the leds table
pdo_cr_kb()9981Create the 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_grid()10220Create the grid 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_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_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
pdo_load($options)11794Load table data

12.3 Report Functions

FunctionLinePurpose
leds_reports_sql($options)3681SQL query interface for reports
leds_reports_csv($dbfile, $sql, $csvfil)3841Export report data as CSV
leds_reports_rpt($options)3931Generate formatted report
rptsxml($options)16043XML report generation
rpts($options)16134Report listing and management

12.4 KB 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
kbwrite($kbfil, $kbrec)4661Write KB record to file
kb_ls($options, $path)4701List KB files
kb_mkdir($kbpath, $kbid)6031Create KB directory

12.5 Utility Functions

FunctionLinePurpose
logwrite($logfil, $logrec)4673Write to log file
logdump($logfil)4683Dump log file contents
bugfile($options)10993Write debug info to file
ko_unique()14904Generate UUID
ko_unique1()14909Generate short unique ID
pc_encode($data)14918PC encoding (obfuscation)
pc_decode($data, $hash)14923PC decoding
datediff($interval, $date1, $date2)14939Calculate date difference
datediff_leds($diffdays)14951LED-specific date difference (color/speed calculation)
iperms($options)6425System permissions/utility functions
localcmds($options)15887Local command execution
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 output
leds_process_psv($title, $cmd, $cwd)6519Execute Perl script process
leds_process_value($title, $cmd, $cwd)6560Execute command and return value

12.6 AJAX Functions

FunctionLinePurpose
ko_ajax($options)2508AJAX request handler
ko_ajax_controller($options)2532Generate AJAX controller JavaScript
ko_ajax_listener($options)2555Generate AJAX listener JavaScript
ko_ajax_app($options)2580Generate AJAX app JavaScript (includes refreshPage handler)
ko_ajax_complete($options)2599Generate AJAX complete handler
ko_ajax_result($options)2616Generate ServiceResult class JavaScript

13. Deployment

13.1 Apache 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

    ErrorLog /var/log/apache2/ko_center_error.log
    CustomLog /var/log/apache2/ko_center_access.log combined
</VirtualHost>

13.2 Python Flask Deployment

The Python Flask equivalent (ko_center.py) can be deployed with:

# Development server
python3 /os/ai/io/ko_center.py

# Production with Gunicorn
gunicorn -w 4 -b 0.0.0.0:5000 ko_center:app

# Production with systemd service
# Create /etc/systemd/system/ko_center.service:
[Unit]
Description=ko_center Python Web Application
After=network.target

[Service]
User=www-data
Group=www-data
WorkingDirectory=/os/ai/io
ExecStart=/usr/bin/python3 /os/ai/io/ko_center.py
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target

13.3 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

14. Python Flask Equivalent

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

AspectPHP VersionPython Version
Web FrameworkApache + mod_phpFlask (built-in development server)
Routing?q=page/action/id parsed manuallyFlask @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

Running the Python version:

python3 /os/ai/io/ko_center.py

15. API Endpoints

15.1 Query Parameter Routes

RouteMethodDescription
?q=ledsGETDisplay LED indicators
?q=leds/detail/<name>GETLED detail view
?q=loginGETLogin form
?q=login_validatePOSTProcess login
?q=logoutGETLogout
?q=triggerGETBroadcast trigger (JSON response)
?q=grid?dbcode=<db>&table=<tbl>GETDatabase grid view
?q=reports/sqlGETSQL query interface
?q=reports/rpt/<code>GETRun named report
?q=kbGETKnowledge Base listing
?q=kb/newGETNew KB entry form
?q=kb/view/<id>GETView KB entry
?q=certsGETCertificate listing
?q=nodesGETNode listing
?q=hwGETHardware inventory
?q=hw?cab=<cab>GETHardware filtered by cabinet
?q=hw?sn=<sn>GETHardware filtered by serial number
?q=hw?ip=<ip>GETHardware filtered by IP address
?q=hw?hrctag=<tag>GETHardware filtered by HRC tag
?q=plansGETPlan listing
?q=configGETConfiguration page
?q=zoom/<code>/<type>/<rowid>GETZoom viewer
?q=zview/<file>/<xml>GETFull-screen zoom view
?q=ptviewerGETPanorama viewer
?q=ptobjectGETPanorama object viewer
?q=scrubGETScrub/data cleanup
?q=uploadGET/POSTFile upload
?q=sqlGETSQL query interface
?q=aboutGETAbout page
?q=konetGETContact information
?q=form_request_accessGETAccess request form
?q=pdo_cr_kbGETCreate KB table
?q=pdo_cr_ledsGETCreate leds table
?q=pdo_insert_ledsGETInsert LED record
?q=pdo_listGETList database tables
?q=pdo_unload?dbcode=<db>&table=<tbl>GETUnload/export table
?q=pdo_updateGETUpdate table data
?q=pdo_loadGETLoad table data
?q=pdo_gridxml?dbcode=<db>&table=<tbl>GETGrid XML export

15.2 Trigger API

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

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"
}

Example

# First call (no last_check)
GET /ko_center/ko_center.php?q=trigger
→ {"triggered": true, "timestamp": "2026-08-01 07:05:00", "since": ""}

# Subsequent call (no new trigger)
GET /ko_center/ko_center.php?q=trigger&last_check=2026-08-01 07:05:00
→ {"triggered": false, "timestamp": "2026-08-01 07:05:00", "since": "2026-08-01 07:05:00"}

# Another browser calls trigger
GET /ko_center/ko_center.php?q=trigger
→ Writes new timestamp to ko_trigger.dat

# First browser's poll detects the change
GET /ko_center/ko_center.php?q=trigger&last_check=2026-08-01 07:05:00
→ {"triggered": true, "timestamp": "2026-08-01 07:06:00", "since": "2026-08-01 07:05:00"}
# Browser reloads the page

Appendix A: Version History

VersionDateChanges
v0.702026-08-01Current version: 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.622012-11-09defrag/report support
v0.602012-10-27passthru() support
v0.522012-08-29?q=kb/rpts/rpt_id&fmt=xml & fmt=csv
v0.502012-08-28jqgrid-4.4.0 integration
v0.482012-08-24ko_center.db3 nodes tables & reports
v0.322012-07-30pdo_cr_kb, pdo_cr_flds, new/add/mod/upd/view
v0.102012-05-16refresh to kohpx_vg.php kohpx_us.php kohpx_sw.php
v0.012012-02-05Initial version

Appendix B: Python Scripts Reference

ScriptPurposeUsage
ko_center.pyPython Flask equivalent of ko_center.phppython3 ko_center.py
new_leds.pyCreate leds_randomus table from leds + randomuspython3 new_leds.py
new_leds_tbl.pyGeneralized: create leds_<tbl2> from leds + any tablepython3 new_leds_tbl.py <tbl2>
cr_leds.pyCreate blinking LED GIF images with ImageMagickpython3 cr_leds.py <static.png> <dynamic.png>