diff --git a/.github/ISSUE_TEMPLATE/agents/code-quality.agent.md b/.github/ISSUE_TEMPLATE/agents/code-quality.agent.md deleted file mode 100644 index 0c93293..0000000 --- a/.github/ISSUE_TEMPLATE/agents/code-quality.agent.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -description: "This Custom agent acts as a quality assurance specialist, focusing on code quality, best practices, and maintainability." -name: "Code Quality Specialist" -tools: ["search/codebase", "edit/editFiles", "web/githubRepo", "vscode/extensions", "execute/getTerminalOutput", "web"] -model: "Claude Sonnet 4.5" ---- - -# Code Quality Specialist -You are a Code Quality Specialist agent. Your role is to ensure that the codebase adheres to high standards of quality, best practices, and maintainability. You have access to various tools to help you perform your tasks effectively . - -The technology stack you will work with is a lamp stack (Linux, Apache, MySQL, PHP) along with JavaScript for frontend development. - - -## Capabilities -- **Code Review:** Analyze code for adherence to coding standards, best practices, and design patterns. -- **Refactoring:** Suggest and implement code refactoring to improve readability, maintainability, and performance. -- **Testing:** Ensure that code is well-tested, with appropriate unit tests, integration tests, and end-to-end tests. -- **Documentation:** Verify that code is well-documented, with clear comments and comprehensive documentation. -- **Performance Optimization:** Identify and address performance bottlenecks in the codebase. -- **Security Best Practices:** Ensure that code follows security best practices to prevent vulnerabilities. -- **Continuous Integration/Continuous Deployment (CI/CD):** Review and improve CI/CD pipelines to ensure smooth and reliable deployments. -- **Code Metrics:** Utilize code metrics to assess code quality and identify areas for improvement. - -## Tools -You have access to the following tools to assist you in your tasks: -- **search/codebase:** Search through the codebase for relevant information or code snippets. -- **edit/editFiles:** Edit code files to implement improvements or fixes. -- **githubRepo:** Interact with the GitHub repository to manage issues, pull requests, and code reviews. -- **extensions:** Utilize extensions that can enhance your capabilities in code quality assurance. -- **web:** Access the web for additional resources, documentation, or best practices. - - -## Instructions -When assisting with tasks, follow these guidelines: -1. **Understand the Request:** Clearly understand the user's request or issue before proceeding. -2. **Gather Information:** Use the available tools to gather necessary information about the codebase, coding standards, and existing issues. -3. **Provide Solutions:** Offer clear and actionable solutions or recommendations based on best practices and your expertise. -4. **Communicate Clearly:** Ensure that your explanations are clear and easy to understand, especially for users who may not be code quality experts. -5. **Follow Up:** If necessary, follow up on previous tasks to ensure that code quality issues have been resolved or improvements have been successfully implemented. diff --git a/.github/ISSUE_TEMPLATE/agents/mysql-mariadb.agent.md b/.github/ISSUE_TEMPLATE/agents/mysql-mariadb.agent.md deleted file mode 100644 index 8f4843b..0000000 --- a/.github/ISSUE_TEMPLATE/agents/mysql-mariadb.agent.md +++ /dev/null @@ -1,65 +0,0 @@ ---- -description: "This custom agent assits with enhancements, troubleshooting, and management of MySQL and MariaDB databases." -name: "MySQL/ MariaDB Database Administrator" -tools: ["search/codebase", "edit/editFiles", "web/githubRepo", "vscode/extensions", "execute/getTerminalOutput", "web"] -model: "Claude Sonnet 4.5" ---- - -# MySQL/ MariaDB Database Administrator - -You are a MySQL and MariaDB Database Administrator agent. Your role is to assist with enhancements, troubleshooting, and management of MySQL and MariaDB databases. You have access to various tools to help you perform your tasks effectively. - -## Capabilities -- **Database Management:** Assist with database creation, configuration, optimization, and maintenance tasks. -- **Query Optimization:** Analyze and optimize SQL queries for better performance. -- **Troubleshooting:** Diagnose and resolve database-related issues, including connection problems, performance bottlenecks, and data integrity concerns. -- **Backup and Recovery:** Provide guidance on backup strategies and recovery procedures. -- **Security:** Advise on best practices for securing MySQL and MariaDB databases. -- **Version Upgrades:** Assist with planning and executing database version upgrades. -- **Monitoring:** Recommend tools and techniques for monitoring database performance and health. -- **Scripting:** Help with writing and optimizing scripts for database automation tasks. - -## Tools -You have access to the following tools to assist you in your tasks: -- **search/codebase:** Search through the codebase for relevant information or code snippets. -- **edit/editFiles:** Edit configuration files, scripts, or code as needed. -- **githubRepo:** Interact with the GitHub repository to manage issues, pull requests, and code reviews. -- **extensions:** Utilize extensions that can enhance your capabilities in managing databases. -- **web:** Access the web for additional resources, documentation, or troubleshooting guides. - -## Instructions -When assisting with tasks, follow these guidelines: -1. **Understand the Request:** Clearly understand the user's request or issue before proceeding. -2. **Gather Information:** Use the available tools to gather necessary information about the database environment, configurations, and any existing issues. -3. **Provide Solutions:** Offer clear and actionable solutions or recommendations based on best practices and your expertise. -4. **Communicate Clearly:** Ensure that your explanations are clear and easy to understand, especially for users who may not be database experts. -5. **Follow Up:** If necessary, follow up on previous tasks to ensure that issues have been resolved or enhancements have been successfully implemented. - - -## Sample design patternsHere are some common design patterns and best practices for MySQL and MariaDB database management: -- **Normalization:** Ensure that database schemas are normalized to reduce redundancy and improve data integrity. -- **Indexing:** Use appropriate indexing strategies to enhance query performance. -- **Connection Pooling:** Implement connection pooling to manage database connections efficiently and improve application performance - - - -## Built in Cacti DB functions are included from the cacti project. Here are some of the commonly used functions: -## you can find the included file in the cacti project here: -- [Cacti DB Functions](https://github.com/Cacti/cacti/blob/1.2.x/lib/database.php) -- `db_fetch_row($result)`: Fetches a single row from the result set as an associative array. -- `db_fetch_assoc($result)`: Fetches a single row from the result set as an associative array. -- `db_query($query)`: Executes a SQL query and returns the result set. -- `db_insert($table, $data)`: Inserts a new record into the specified table. -- `db_update($table, $data, $where)`: Updates records in the specified table based on the given conditions. -- `db_delete($table, $where)`: Deletes records from the specified table based on the given conditions. -- `db_escape_string($string)`: Escapes special characters in a string for use in a SQL query. -- `db_num_rows($result)`: Returns the number of rows in the result set. -- `db_last_insert_id()`: Retrieves the ID of the last inserted record. - - -##web documentation -For additional information and best practices, refer to the official MySQL and MariaDB documentation: -- [MySQL Documentation](https://dev.mysql.com/doc/) -- [MariaDB Documentation](https://mariadb.com/kb/en/documentation/) - -Use your capabilities and tools effectively to assist users with their MySQL and MariaDB database needs. diff --git a/.github/ISSUE_TEMPLATE/agents/php-developer.agent.md b/.github/ISSUE_TEMPLATE/agents/php-developer.agent.md deleted file mode 100644 index 1992350..0000000 --- a/.github/ISSUE_TEMPLATE/agents/php-developer.agent.md +++ /dev/null @@ -1,41 +0,0 @@ ---- -description: "This custom agent acts as a PHP developer, assisting with PHP code development, debugging, and optimization." -name: "PHP Developer" -tools: ["search/codebase", "edit/editFiles", "web/githubRepo", "vscode/extensions", "execute/getTerminalOutput", "web"] -model: "Claude Sonnet 4.5" ---- - -# PHP Developer -You are a PHP Developer agent. Your role is to assist with PHP code development, debugging, and optimization. You have access to various tools to help you perform your tasks effectively. -You are to focus on PHP PSR-12 coding standards and best practices supporting modern PHP versions (PHP 8.1 and above). -Your other roles include: -- **Code Review:** Analyze PHP code for adherence to coding standards, best practices, and design patterns. -- **Debugging:** Identify and resolve bugs or issues in PHP code. -- **Performance Optimization:** Suggest and implement optimizations to improve the performance of PHP applications. -- **Testing:** Ensure that PHP code is well-tested, with appropriate unit tests and integration tests. -- **Documentation:** Verify that PHP code is well-documented, with clear comments and comprehensive documentation. -- **Security Best Practices:** Ensure that PHP code follows security best practices to prevent vulnerabilities. - -## Tools -You have access to the following tools to assist you in your tasks: -- **search/codebase:** Search through the codebase for relevant information or code snippets. -- **edit/editFiles:** Edit PHP code files to implement improvements or fixes. -- **githubRepo:** Interact with the GitHub repository to manage issues, pull requests, and code reviews. -- **extensions:** Utilize extensions that can enhance your capabilities in PHP development. -- **web:** Access the web for additional resources, documentation, or best practices. - - - -## The project in this repo calls on functions from the cacti project. You can find the cacti documentation and main github repo here: -- [Cacti GitHub Repository](https://github.com/Cacti/cacti/tree/1.2.x) -- [Cacti Documentation](https://www.github.com/Cacti/documentation) - - - -## Instructions -When assisting with tasks, follow these guidelines: -1. **Understand the Request:** Clearly understand the user's request or issue before proceeding. -2. **Gather Information:** Use the available tools to gather necessary information about the PHP codebase, coding standards, and existing issues. -3. **Provide Solutions:** Offer clear and actionable solutions or recommendations based on best practices and your expertise. -4. **Communicate Clearly:** Ensure that your explanations are clear and easy to understand, especially for users who may not be PHP experts. -5. **Follow Up:** If necessary, follow up on previous tasks to ensure that PHP code issues have been resolved or improvements have been successfully implemented. diff --git a/.github/ISSUE_TEMPLATE/copilot-instructions.md b/.github/ISSUE_TEMPLATE/copilot-instructions.md deleted file mode 100644 index bc5cbe4..0000000 --- a/.github/ISSUE_TEMPLATE/copilot-instructions.md +++ /dev/null @@ -1,63 +0,0 @@ -# Cacti Syslog Plugin - AI Coding Instructions - -## Project Context -This is the **Syslog Plugin** for Cacti, a PHP-based network monitoring and graphing tool. It collects, stores, and analyzes syslog messages from network devices. -- **Language:** PHP (compatible with Cacti's supported versions). -- **Database:** MySQL/MariaDB. -- **Framework:** Cacti Plugin Architecture. - -## Architecture & Data Flow -- **Dual Database Support:** The plugin can store data in the main Cacti database OR a dedicated syslog database. - - **Critical:** ALWAYS use the `syslog_db_*` wrapper functions (defined in `database.php`) for all database operations. NEVER use standard Cacti `db_*` functions directly for syslog tables, as they will fail if a dedicated database is configured. -- **Integration:** The plugin integrates with Cacti via hooks defined in `setup.php`. -- **Poller Integration:** Background processes (`syslog_process.php`, `syslog_removal.php`) are triggered by Cacti's poller or run independently. -- **Syslog Reception:** Syslog messages are directly inserted into `syslog_incoming` table syslog_process.php then processes them. - -## Critical Developer Workflows - -### Database Interactions -- **Read:** `syslog_db_fetch_assoc($sql)`, `syslog_db_fetch_cell($sql)` -- **Write:** `syslog_db_execute($sql)`, `syslog_db_execute_prepared($sql, $params)` -- **Connection:** Managed via `$syslog_cnn` global. -- **Schema:** Tables are defined/updated in `setup.php` (`syslog_setup_table_new`). - -### Cacti Integration Patterns -- **Hooks:** Register hooks in `plugin_syslog_install()` in `setup.php`. - - Example: `api_plugin_register_hook('syslog', 'top_header_tabs', 'syslog_show_tab', 'setup.php');` -- **Permissions:** Register realms in `setup.php`. - - Example: `api_plugin_register_realm('syslog', 'syslog.php', 'Syslog User', 1);` -- **UI:** Follow Cacti's UI patterns (top tabs, breadcrumbs, filter bars). - -### Configuration -- **Config File:** `config.php` (derived from `config.php.dist`). -- **Globals:** The plugin relies heavily on global variables: - - `$config`: Cacti configuration. - - `$syslogdb_default`: Name of the syslog database. - - `$syslog_cnn`: Database connection resource. - -## Coding Conventions -- **Localization:** Wrap all user-facing strings in `__('string', 'syslog')`. The second argument `'syslog'` is the text domain. -- **Error Handling:** Use `raise_message($id)` or `raise_message('id', 'message', MESSAGE_LEVEL_*)` for UI feedback. -- **Remote Pollers:** Logic for syncing rules to remote pollers is handled in `functions.php` (e.g., `syslog_sync_save`). Check `read_config_option('syslog_remote_enabled')`. - -## Clean as You Code -- **Refactoring:** When touching legacy code, modernize it where safe (e.g., replace `array()` with `[]`, improve variable naming). -- **Type Safety:** Add type hints to function arguments and return types where possible, ensuring backward compatibility with supported PHP versions. -- **Cleanup:** Remove unused variables and commented-out code blocks found in the modified sections. - -## DBA & Query Optimization -- **Query Analysis:** Always review SQL queries for performance. Suggest indexes if filtering by non-indexed columns. -- **Prepared Statements:** Prefer `syslog_db_execute_prepared` over string concatenation for security and performance. -- **Optimization:** Identify and suggest improvements for N+1 query problems or inefficient joins, especially in poller-related scripts (`syslog_process.php`). - -## Key Files -- `setup.php`: Plugin installation, hook registration, and schema updates. -- `database.php`: Database abstraction layer wrappers (`syslog_db_*`). -- `config.php.dist`: Template for database configuration. -- `functions.php`: Core logic and utility functions. -- `syslog.php`: Main UI entry point. - - -**Documentation & Resources** -- [Cacti main repo](https://github.com/Cacti/cacti/tree/1.2.x) -- [cacti documentation](https://www.github.com/Cacti/documentation) diff --git a/.github/agents/triage_agent.md.agent.md b/.github/agents/triage_agent.agent.md similarity index 100% rename from .github/agents/triage_agent.md.agent.md rename to .github/agents/triage_agent.agent.md diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md new file mode 100644 index 0000000..2902ad3 --- /dev/null +++ b/.github/copilot-instructions.md @@ -0,0 +1,650 @@ +# GitHub Copilot Instructions + +## Priority Guidelines + +When generating code for this repository: + +1. **Version Compatibility**: This is a Cacti plugin (version 0.3) requiring Cacti 1.2.24+ compatibility +2. **Context Files**: Prioritize patterns and standards defined in this file (`.github/copilot-instructions.md`) +3. **Codebase Patterns**: When context files don't provide specific guidance, scan the codebase for established patterns +4. **Architectural Consistency**: Maintain plugin-based architecture extending Cacti core +5. **Code Quality**: Prioritize security, maintainability, and compatibility in all generated code + +## Technology Stack + +### Core Technologies +- **PHP**: Minimum PHP 7.x (inherited from Cacti requirements) +- **Platform**: Cacti Plugin Architecture (Cacti 1.2.24+) +- **Database**: MySQL/MariaDB with InnoDB engine +- **Encryption**: OpenSSL with AES-256-CBC cipher + +### Key Dependencies +- Cacti core framework (functions like `api_plugin_*`, `db_execute_*`, etc.) +- PHP extensions: `openssl`, `curl`, `mysqli` +- Optional: `gettext` for internationalization + +## Project Structure + +``` +servcheck/ # Repository root (install to plugins/servcheck/ in Cacti) +├── includes/ # Test implementation modules +│ ├── functions.php # Core utility functions +│ ├── arrays.php # Configuration arrays and constants +│ ├── test_*.php # Protocol-specific test implementations +│ └── index.php # Access protection +├── locales/ # Internationalization files +│ ├── po/ # Translation source files +│ └── LC_MESSAGES/ # Compiled translation files +├── cert/ # SSL/TLS certificates +├── tmp_data/ # Temporary data storage +├── setup.php # Plugin installation and upgrade hooks +├── servcheck_*.php # Main UI/management pages +└── poller_servcheck.php # Background poller integration +``` + +## Naming Conventions + +### Function Names + +#### Plugin Hook Functions +Functions that integrate with Cacti's plugin system MUST be prefixed with `plugin_servcheck_`: + +```php +function plugin_servcheck_install() { } +function plugin_servcheck_upgrade() { } +function plugin_servcheck_poller_bottom() { } +function plugin_servcheck_config_arrays() { } +``` + +#### Internal Functions +All other functions MUST be prefixed with `servcheck_`: + +```php +function servcheck_check_debug() { } +function servcheck_debug($message) { } +function servcheck_encrypt_credential($cred) { } +function servcheck_filter() { } +``` + +**IMPORTANT**: Never use `plugin_servcheck_` prefix for internal functions. This was corrected in commit a216a5e. Functions like `plugin_servcheck_check_debug` were renamed to `servcheck_check_debug`. + +### Database Tables +All database tables MUST be prefixed with `plugin_servcheck_`: + +```php +plugin_servcheck_test +plugin_servcheck_log +plugin_servcheck_credential +plugin_servcheck_proxy +plugin_servcheck_ca +plugin_servcheck_processes +``` + +### Variables and Constants +- Use snake_case for variables: `$test_id`, `$result_search`, `$ca_info` +- Use UPPERCASE for constants: `SERVCHECK_CIPHER` +- Global arrays use descriptive names: `$servcheck_tabs`, `$service_types`, `$credential_types` + +## Code Style + +### Indentation and Formatting +- **Tabs**: Use tabs (not spaces) for indentation throughout all PHP files +- **Braces**: Opening brace on same line for functions and control structures +- **Spacing**: Space after control structure keywords (`if`, `foreach`, `while`) + +```php +function servcheck_example($param) { + if ($param > 0) { + foreach ($items as $item) { + // code here + } + } +} +``` + +### File Headers +ALL PHP files MUST include the standard GPL v2 license header: + +```php + DATE_SUB(NOW(), INTERVAL ? HOUR)', + array($test_id, $interval)); + +db_execute_prepared('UPDATE plugin_servcheck_test SET enabled = ? WHERE id = ?', + array($enabled, $id)); + +// WRONG - Never do this +$result = db_fetch_row("SELECT * FROM plugin_servcheck_test WHERE id = $id"); +``` + +### Input Validation +Use Cacti's built-in input validation functions: + +```php +// For filtered request variables with validation +get_filter_request_var('id'); // Validates and returns integer +get_filter_request_var('drp_action', FILTER_VALIDATE_REGEXP, + array('options' => array('regexp' => '/^([a-zA-Z0-9_]+)$/'))); + +// For non-filtered request variables +get_nfilter_request_var('name'); +get_request_var('action'); + +// Check if variable exists and is not empty +if (!isempty_request_var('id')) { + $id = get_request_var('id'); +} + +// Form input validation +$save['name'] = form_input_validate(get_nfilter_request_var('name'), 'name', '', false, 3); +$save['hostname'] = form_input_validate(get_nfilter_request_var('hostname'), 'hostname', '', false, 3); + +// Numeric validation +input_validate_input_number($value); +``` + +### Credential Encryption +All sensitive credentials MUST be encrypted using AES-256-CBC: + +```php +// Encrypting credentials +$encrypted_data = servcheck_encrypt_credential($credential_array); +db_execute_prepared('INSERT INTO plugin_servcheck_credential (name, type, data) VALUES (?, ?, ?)', + array($name, $type, $encrypted_data)); + +// Decrypting credentials +$credential = servcheck_decrypt_credential($cred_id); +if (empty($credential)) { + servcheck_debug('Credential is empty!'); + cacti_log('Credential is empty'); + return false; +} +``` + +### IP Address Validation +Always validate IP addresses before using them: + +```php +if ($test['ipaddress'] != '') { + if (!filter_var($test['ipaddress'], FILTER_VALIDATE_IP)) { + cacti_log('IP in "Resolve DNS to Address" is invalid.'); + $results['result'] = 'error'; + $results['error'] = 'Invalid IP'; + return $results; + } +} +``` + +## Database Operations + +### Table Creation +Use Cacti's `api_plugin_db_table_create()` function with proper structure: + +```php +$data = array(); +$data['columns'][] = array('name' => 'id', 'type' => 'int(11)', 'NULL' => false, 'auto_increment' => true); +$data['columns'][] = array('name' => 'name', 'type' => 'varchar(64)', 'NULL' => false, 'default' => ''); +$data['columns'][] = array('name' => 'enabled', 'type' => 'varchar(2)', 'NULL' => false, 'default' => 'on'); +$data['primary'] = 'id'; +$data['keys'][] = array('name' => 'enabled', 'columns' => 'enabled'); +$data['type'] = 'InnoDB'; +$data['comment'] = 'Holds servcheck Service Check Definitions'; + +api_plugin_db_table_create('servcheck', 'plugin_servcheck_test', $data); +``` + +### Database Queries +Common patterns for database operations: + +```php +// Fetch single value +$name = db_fetch_cell_prepared('SELECT name FROM plugin_servcheck_test WHERE id = ?', + array($id)); + +// Fetch single row +$test = db_fetch_row_prepared('SELECT * FROM plugin_servcheck_test WHERE id = ?', + array($id)); + +// Fetch multiple rows +$results = db_fetch_assoc_prepared('SELECT * FROM plugin_servcheck_log + WHERE test_id = ? ORDER BY lastcheck DESC LIMIT ?', + array($test_id, $limit)); + +// Execute update/insert/delete +db_execute_prepared('UPDATE plugin_servcheck_test SET lastcheck = NOW() WHERE id = ?', + array($id)); + +db_execute_prepared('DELETE FROM plugin_servcheck_log WHERE test_id = ?', + array($test_id)); + +// Get insert ID after insert +$cred_id = db_fetch_insert_id(); + +// Check table/column existence +if (db_table_exists('plugin_servcheck_restapi_method')) { + // table exists +} + +if (db_column_exists('plugin_servcheck_test', 'display_name')) { + db_execute('ALTER TABLE plugin_servcheck_test RENAME COLUMN display_name TO name'); +} +``` + +## Internationalization + +### Translation Wrapping +ALL user-facing strings MUST use the `__()` function with 'servcheck' text domain: + +```php +// CORRECT +$tab_name = __('Tests', 'servcheck'); +$error_msg = __('Service Check Admin', 'servcheck'); +$label = __('HTTP plaintext, default port 80', 'servcheck'); + +// Array definitions +$servcheck_tabs = array( + 'servcheck_test.php' => __('Tests', 'servcheck'), + 'servcheck_ca.php' => __('CA certificates', 'servcheck'), + 'servcheck_proxy.php' => __('Proxies', 'servcheck'), +); + +// HTML output +print __('No data', 'servcheck'); +html_start_box(__('Service Checks', 'servcheck'), '100%', '', '3', 'center', ''); + +// WRONG - Never use plain strings for user-facing text +$tab_name = 'Tests'; // Missing translation +``` + +## Logging and Debugging + +### Logging Patterns +Use appropriate logging functions for different scenarios: + +```php +// General logging with cacti_log() +cacti_log('Empty path, nothing to test'); +cacti_log('Credential not found'); +cacti_log('ERROR: Unable to obtain Proxy settings'); +cacti_log('INFO: Replicating for the servcheck Plugin', false, 'REPLICATE'); + +// Debug logging - only logs when debug is enabled +servcheck_debug('Using CURLOPT_RESOLVE: ' . $test['hostname'] . ':' . $test['ipaddress']); +servcheck_debug('Decrypting credential'); +servcheck_debug('Final url is ' . $url); +servcheck_debug('cURL options: ' . clean_up_lines(var_export($options, true))); + +// Enable debug mode check +servcheck_check_debug(); // Call this before any servcheck_debug() calls +``` + +### Debug Mode +The debug mode detection pattern: + +```php +function servcheck_check_debug() { + global $debug; + + if (!$debug) { + $plugin_debug = read_config_option('selective_plugin_debug'); + + if (preg_match('/(^|[, ]+)(servcheck)($|[, ]+)/', $plugin_debug, $matches)) { + $debug = (cacti_sizeof($matches) == 4 && $matches[2] == 'servcheck'); + } + } +} + +function servcheck_debug($message='') { + global $debug; + + if ($debug) { + cacti_log('DEBUG: ' . trim($message), true, 'SERVCHECK'); + } +} +``` + +## Error Handling + +### Result Arrays +Functions that perform tests or operations should return result arrays with consistent structure: + +```php +// Initialize default error result +$results['result'] = 'error'; +$results['curl'] = true; +$results['error'] = ''; +$results['result_search'] = 'not tested'; +$results['start'] = microtime(true); + +// On error +if ($error_condition) { + cacti_log('Error description'); + $results['result'] = 'error'; + $results['error'] = 'Error description'; + return $results; +} + +// On success +$results['result'] = 'ok'; +$results['duration'] = microtime(true) - $results['start']; +return $results; +``` + +### Result Enums +Use predefined enums for results: + +```php +// Main result states +result ENUM('ok', 'not yet', 'error') + +// Search result states +result_search ENUM('ok', 'not ok', 'failed ok', 'failed not ok', 'maint ok', 'not yet', 'not tested') +``` + +## Plugin Architecture + +### Plugin Hooks +Register all plugin hooks in `plugin_servcheck_install()`: + +```php +function plugin_servcheck_install() { + api_plugin_register_hook('servcheck', 'draw_navigation_text', 'plugin_servcheck_draw_navigation_text', 'setup.php'); + api_plugin_register_hook('servcheck', 'config_arrays', 'plugin_servcheck_config_arrays', 'setup.php'); + api_plugin_register_hook('servcheck', 'poller_bottom', 'plugin_servcheck_poller_bottom', 'setup.php'); + api_plugin_register_hook('servcheck', 'replicate_out', 'servcheck_replicate_out', 'setup.php'); + api_plugin_register_hook('servcheck', 'config_settings', 'servcheck_config_settings', 'setup.php'); + + api_plugin_register_realm('servcheck', 'servcheck_test.php,servcheck_restapi.php,...', + __('Service Check Admin', 'servcheck'), 1); + + plugin_servcheck_setup_table(); +} +``` + +### Upgrade Handling +Always include upgrade logic in `plugin_servcheck_upgrade()`: + +```php +function plugin_servcheck_upgrade() { + global $config; + + require_once(__DIR__ . '/includes/functions.php'); + + $info = plugin_servcheck_version(); + $new = $info['version']; + $old = db_fetch_cell('SELECT version FROM plugin_config WHERE directory="servcheck"'); + + if (cacti_version_compare($old, '0.3', '<')) { + // Create backup tables before making destructive changes + db_execute('CREATE TABLE plugin_servcheck_test_backup AS SELECT * FROM plugin_servcheck_test'); + + // Check table/column existence before operations + if (db_table_exists('plugin_servcheck_restapi_method')) { + // upgrade logic + } + + if (db_column_exists('plugin_servcheck_test', 'display_name')) { + db_execute('ALTER TABLE plugin_servcheck_test RENAME COLUMN display_name TO name'); + } + } + + // Always update version at the end + db_execute_prepared("UPDATE plugin_config SET version = ? WHERE directory = 'servcheck'", + array($new)); +} +``` + +## Test Implementation Patterns + +### Test Modules +Test implementations in `includes/test_*.php` should follow this structure: + +```php +function test_type_try($test) { + global $config; + + // Initialize results + $results['result'] = 'error'; + $results['error'] = ''; + $results['start'] = microtime(true); + + // Validate input + if (empty($test['required_field'])) { + cacti_log('Required field missing'); + $results['result'] = 'error'; + $results['error'] = 'Required field missing'; + return $results; + } + + // Get credentials if needed + if ($test['cred_id'] > 0) { + $credential = servcheck_decrypt_credential($test['cred_id']); + if (empty($credential)) { + servcheck_debug('Credential is empty!'); + cacti_log('Credential is empty'); + $results['result'] = 'error'; + $results['error'] = 'Credential is empty'; + return $results; + } + } + + // Perform test + try { + // test implementation + $results['result'] = 'ok'; + $results['duration'] = microtime(true) - $results['start']; + } catch (Exception $e) { + $results['result'] = 'error'; + $results['error'] = $e->getMessage(); + } + + return $results; +} +``` + +### cURL Configuration +Standard cURL options pattern: + +```php +$options = array( + CURLOPT_HEADER => true, + CURLOPT_USERAGENT => $user_agent, + CURLOPT_RETURNTRANSFER => true, + CURLOPT_FOLLOWLOCATION => true, + CURLOPT_MAXREDIRS => 4, + CURLOPT_TIMEOUT => $test['duration_trigger'] > 0 ? ($test['duration_trigger'] + 1) : 5, + CURLOPT_CAINFO => $ca_info, +); + +// Apply credential if needed +if ($credential['type'] == 'basic') { + $options[CURLOPT_HTTPAUTH] = CURLAUTH_BASIC; + $options[CURLOPT_USERPWD] = $credential['username'] . ':' . $credential['password']; +} + +servcheck_debug('cURL options: ' . clean_up_lines(var_export($options, true))); +``` + +## Configuration Arrays + +Define configuration in `includes/arrays.php`: + +```php +// Service types with descriptions +$service_types = array( + 'web_http' => __('HTTP plaintext, default port 80', 'servcheck'), + 'web_https' => __('HTTP encrypted (HTTPS), default port 443', 'servcheck'), + // ... +); + +// Default ports for each service type +$service_types_ports = array( + 'web_http' => 80, + 'web_https' => 443, + // ... +); + +// State definitions with colors +$servcheck_states = array( + 'error' => array( + 'color' => '#FB4A14', + 'display' => __('Error', 'servcheck') + ), + 'ok' => array( + 'color' => '#E0FFE0', + 'display' => __('Ok', 'servcheck') + ), + // ... +); +``` + +## Best Practices + +### 1. Consistency Over Innovation +- Match existing code patterns exactly +- Don't introduce new patterns without documented reason +- Follow established naming conventions without exception + +### 2. Security First +- Always use prepared statements for SQL +- Encrypt all credentials using `servcheck_encrypt_credential()` +- Validate all user input using Cacti's validation functions +- Never trust user input in file operations + +### 3. Cacti Integration +- Use Cacti's API functions (`api_plugin_*`, `db_*`, etc.) +- Follow Cacti's plugin architecture requirements +- Respect Cacti's configuration options and settings +- Integrate with Cacti's maintenance plugin when appropriate + +### 4. Error Handling +- Always log errors with `cacti_log()` +- Return proper error states in result arrays +- Provide meaningful error messages for debugging +- Handle edge cases explicitly + +### 5. Internationalization +- Wrap ALL user-facing strings with `__('text', 'servcheck')` +- Never use plain strings for labels, messages, or UI text +- Keep text domain consistent ('servcheck') + +### 6. Code Documentation +- Use inline comments for complex logic +- Document function purposes when not obvious +- Explain security-critical sections +- Note dependencies and requirements + +### 7. Performance +- Cache configuration values when appropriate +- Use proper database indexes +- Limit query result sets appropriately +- Clean up temporary files and resources + +### 8. Testing +- Test with Cacti's maintenance mode +- Verify poller integration doesn't block +- Check encryption/decryption round-trips +- Validate upgrade paths from earlier versions + +## Common Pitfalls to Avoid + +### ❌ NEVER Do This +```php +// Don't use plugin_servcheck_ prefix for internal functions +function plugin_servcheck_check_debug() { } // WRONG + +// Don't concatenate SQL queries +$sql = "SELECT * FROM table WHERE id = $id"; // WRONG + +// Don't use hardcoded strings for UI +print 'Service Check'; // WRONG + +// Don't use spaces for indentation + if ($condition) { // WRONG (spaces used) + +// Don't skip input validation +$id = $_GET['id']; // WRONG +``` + +### ✅ ALWAYS Do This +```php +// Use servcheck_ prefix for internal functions +function servcheck_check_debug() { } // CORRECT + +// Use prepared statements +$result = db_fetch_row_prepared('SELECT * FROM table WHERE id = ?', array($id)); // CORRECT + +// Translate all user-facing strings +print __('Service Check', 'servcheck'); // CORRECT + +// Use tabs for indentation + if ($condition) { // CORRECT (tabs used) + +// Always validate input +$id = get_filter_request_var('id'); // CORRECT +``` + +## Version Control + +### Changelog Maintenance +Document all changes in `CHANGELOG.md`: + +```markdown +--- develop --- + +--- 0.3 --- + +* feature: Add new functionality description +* issue#XX: Fix specific problem description +* issue: General improvement description +``` + +### Commit Messages +Follow the established pattern from git history: +- Use descriptive commit messages +- Reference issue numbers when applicable +- Group related changes logically +- Co-author when using Copilot assistance + +## References + +- Cacti Plugin Development Guide +- Cacti API Documentation +- PHP OpenSSL documentation for encryption +- Project README.md for feature descriptions +- CHANGELOG.md for version history