mirror of
https://github.com/opensourcepos/opensourcepos.git
synced 2026-05-25 00:44:03 -04:00
Compare commits
12 Commits
pr-4522
...
feature/pa
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0ea3ced674 | ||
|
|
896ed87797 | ||
|
|
eb264ad76d | ||
|
|
10a64e7af9 | ||
|
|
6e99f05d63 | ||
|
|
c430c7afb5 | ||
|
|
519347f4f5 | ||
|
|
62d84411b2 | ||
|
|
6bd4bb545d | ||
|
|
66f7d70749 | ||
|
|
bd8b4fa6c1 | ||
|
|
a9669ddf19 |
@@ -205,6 +205,7 @@ class Autoload extends AutoloadConfig
|
||||
'cookie',
|
||||
'tabular',
|
||||
'locale',
|
||||
'security'
|
||||
'security',
|
||||
'plugin'
|
||||
];
|
||||
}
|
||||
|
||||
@@ -8,23 +8,7 @@ use CodeIgniter\HotReloader\HotReloader;
|
||||
use App\Events\Db_log;
|
||||
use App\Events\Load_config;
|
||||
use App\Events\Method;
|
||||
|
||||
/*
|
||||
* --------------------------------------------------------------------
|
||||
* Application Events
|
||||
* --------------------------------------------------------------------
|
||||
* Events allow you to tap into the execution of the program without
|
||||
* modifying or extending core files. This file provides a central
|
||||
* location to define your events, though they can always be added
|
||||
* at run-time, also, if needed.
|
||||
*
|
||||
* You create code that can execute by subscribing to events with
|
||||
* the 'on()' method. This accepts any form of callable, including
|
||||
* Closures, that will be executed when the event is triggered.
|
||||
*
|
||||
* Example:
|
||||
* Events::on('create', [$myInstance, 'myMethod']);
|
||||
*/
|
||||
use App\Libraries\Plugins\PluginManager;
|
||||
|
||||
Events::on('pre_system', static function (): void {
|
||||
if (ENVIRONMENT !== 'testing') {
|
||||
@@ -39,22 +23,19 @@ Events::on('pre_system', static function (): void {
|
||||
ob_start(static fn ($buffer) => $buffer);
|
||||
}
|
||||
|
||||
/*
|
||||
* --------------------------------------------------------------------
|
||||
* Debug Toolbar Listeners.
|
||||
* --------------------------------------------------------------------
|
||||
* If you delete, they will no longer be collected.
|
||||
*/
|
||||
if (CI_DEBUG && ! is_cli()) {
|
||||
Events::on('DBQuery', 'CodeIgniter\Debug\Toolbar\Collectors\Database::collect');
|
||||
service('toolbar')->respond();
|
||||
// Hot Reload route - for framework use on the hot reloader.
|
||||
if (ENVIRONMENT === 'development') {
|
||||
service('routes')->get('__hot-reload', static function (): void {
|
||||
(new HotReloader())->run();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
$pluginManager = new PluginManager();
|
||||
$pluginManager->discoverPlugins();
|
||||
$pluginManager->registerPluginEvents();
|
||||
});
|
||||
|
||||
$config = new Load_config();
|
||||
@@ -64,4 +45,4 @@ $db_log = new Db_log();
|
||||
Events::on('DBQuery', [$db_log, 'db_log_queries']);
|
||||
|
||||
$method = new Method();
|
||||
Events::on('pre_controller', [$method, 'validate_method']);
|
||||
Events::on('pre_controller', [$method, 'validate_method']);
|
||||
99
app/Controllers/Plugins/Manage.php
Normal file
99
app/Controllers/Plugins/Manage.php
Normal file
@@ -0,0 +1,99 @@
|
||||
<?php
|
||||
|
||||
namespace App\Controllers\Plugins;
|
||||
|
||||
use App\Controllers\Secure_Controller;
|
||||
use App\Libraries\Plugins\PluginManager;
|
||||
use CodeIgniter\HTTP\ResponseInterface;
|
||||
|
||||
class Manage extends Secure_Controller
|
||||
{
|
||||
private PluginManager $pluginManager;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct('plugins');
|
||||
$this->pluginManager = new PluginManager();
|
||||
$this->pluginManager->discoverPlugins();
|
||||
}
|
||||
|
||||
public function getIndex(): string
|
||||
{
|
||||
$plugins = $this->pluginManager->getAllPlugins();
|
||||
$enabledPlugins = $this->pluginManager->getEnabledPlugins();
|
||||
|
||||
$pluginData = [];
|
||||
foreach ($plugins as $pluginId => $plugin) {
|
||||
$pluginData[$pluginId] = [
|
||||
'id' => $plugin->getPluginId(),
|
||||
'name' => $plugin->getPluginName(),
|
||||
'description' => $plugin->getPluginDescription(),
|
||||
'version' => $plugin->getVersion(),
|
||||
'enabled' => isset($enabledPlugins[$pluginId]),
|
||||
'has_config' => $plugin->getConfigView() !== null,
|
||||
];
|
||||
}
|
||||
|
||||
echo view('plugins/manage', ['plugins' => $pluginData]);
|
||||
return '';
|
||||
}
|
||||
|
||||
public function postEnable(string $pluginId): ResponseInterface
|
||||
{
|
||||
if ($this->pluginManager->enablePlugin($pluginId)) {
|
||||
return $this->response->setJSON(['success' => true, 'message' => lang('Plugins.plugin_enabled')]);
|
||||
}
|
||||
return $this->response->setJSON(['success' => false, 'message' => lang('Plugins.plugin_enable_failed')]);
|
||||
}
|
||||
|
||||
public function postDisable(string $pluginId): ResponseInterface
|
||||
{
|
||||
if ($this->pluginManager->disablePlugin($pluginId)) {
|
||||
return $this->response->setJSON(['success' => true, 'message' => lang('Plugins.plugin_disabled')]);
|
||||
}
|
||||
return $this->response->setJSON(['success' => false, 'message' => lang('Plugins.plugin_disable_failed')]);
|
||||
}
|
||||
|
||||
public function postUninstall(string $pluginId): ResponseInterface
|
||||
{
|
||||
if ($this->pluginManager->uninstallPlugin($pluginId)) {
|
||||
return $this->response->setJSON(['success' => true, 'message' => lang('Plugins.plugin_uninstalled')]);
|
||||
}
|
||||
return $this->response->setJSON(['success' => false, 'message' => lang('Plugins.plugin_uninstall_failed')]);
|
||||
}
|
||||
|
||||
public function getConfig(string $pluginId): ResponseInterface
|
||||
{
|
||||
$plugin = $this->pluginManager->getPlugin($pluginId);
|
||||
|
||||
if (!$plugin) {
|
||||
return $this->response->setJSON(['success' => false, 'message' => lang('Plugins.plugin_not_found')]);
|
||||
}
|
||||
|
||||
$configView = $plugin->getConfigView();
|
||||
if (!$configView) {
|
||||
return $this->response->setJSON(['success' => false, 'message' => lang('Plugins.plugin_no_config')]);
|
||||
}
|
||||
|
||||
$settings = $plugin->getSettings();
|
||||
echo view($configView, ['settings' => $settings, 'plugin' => $plugin]);
|
||||
return $this->response;
|
||||
}
|
||||
|
||||
public function postSaveConfig(string $pluginId): ResponseInterface
|
||||
{
|
||||
$plugin = $this->pluginManager->getPlugin($pluginId);
|
||||
|
||||
if (!$plugin) {
|
||||
return $this->response->setJSON(['success' => false, 'message' => lang('Plugins.plugin_not_found')]);
|
||||
}
|
||||
|
||||
$settings = $this->request->getPost();
|
||||
unset($settings['_method'], $settings['csrf_token_name']);
|
||||
|
||||
if ($plugin->saveSettings($settings)) {
|
||||
return $this->response->setJSON(['success' => true, 'message' => lang('Plugins.settings_saved')]);
|
||||
}
|
||||
return $this->response->setJSON(['success' => false, 'message' => lang('Plugins.settings_save_failed')]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
namespace App\Database\Migrations;
|
||||
|
||||
use CodeIgniter\Database\Migration;
|
||||
|
||||
class PluginConfigTableCreate extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
log_message('info', 'Migrating plugin_config table started');
|
||||
|
||||
execute_script(APPPATH . 'Database/Migrations/sqlscripts/3.4.1_PluginConfigTableCreate.sql');
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
$this->forge->dropTable('plugin_config', true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
CREATE TABLE IF NOT EXISTS `ospos_plugin_config` (
|
||||
`key` varchar(100) NOT NULL,
|
||||
`value` text NOT NULL,
|
||||
`created_at` timestamp NOT NULL DEFAULT current_timestamp(),
|
||||
`updated_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
|
||||
PRIMARY KEY (`key`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
24
app/Helpers/plugin_helper.php
Normal file
24
app/Helpers/plugin_helper.php
Normal file
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
|
||||
use CodeIgniter\Events\Events;
|
||||
|
||||
if (!function_exists('plugin_content')) {
|
||||
function plugin_content(string $section, array $data = []): string
|
||||
{
|
||||
$results = Events::trigger("view:{$section}", $data);
|
||||
|
||||
if (is_array($results)) {
|
||||
return implode('', array_filter($results, fn($r) => is_string($r)));
|
||||
}
|
||||
|
||||
return is_string($results) ? $results : '';
|
||||
}
|
||||
}
|
||||
|
||||
if (!function_exists('plugin_content_exists')) {
|
||||
function plugin_content_exists(string $section): bool
|
||||
{
|
||||
$observers = Events::listRegistered("view:{$section}");
|
||||
return !empty($observers);
|
||||
}
|
||||
}
|
||||
27
app/Language/en/Plugins.php
Normal file
27
app/Language/en/Plugins.php
Normal file
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
return [
|
||||
// Plugin Management
|
||||
"plugins" => "Plugins",
|
||||
"plugin_management" => "Plugin Management",
|
||||
"plugin_name" => "Plugin Name",
|
||||
"plugin_description" => "Description",
|
||||
"plugin_version" => "Version",
|
||||
"plugin_status" => "Status",
|
||||
"plugin_enabled" => "Plugin enabled successfully",
|
||||
"plugin_enable_failed" => "Failed to enable plugin",
|
||||
"plugin_disabled" => "Plugin disabled successfully",
|
||||
"plugin_disable_failed" => "Failed to disable plugin",
|
||||
"plugin_uninstalled" => "Plugin uninstalled successfully",
|
||||
"plugin_uninstall_failed" => "Failed to uninstall plugin",
|
||||
"plugin_not_found" => "Plugin not found",
|
||||
"plugin_no_config" => "This plugin has no configuration options",
|
||||
"settings_saved" => "Plugin settings saved successfully",
|
||||
"settings_save_failed" => "Failed to save plugin settings",
|
||||
"enable" => "Enable",
|
||||
"disable" => "Disable",
|
||||
"configure" => "Configure",
|
||||
"uninstall" => "Uninstall",
|
||||
"no_plugins_found" => "No plugins found",
|
||||
"active" => "Active",
|
||||
"inactive" => "Inactive",
|
||||
];
|
||||
70
app/Libraries/Plugins/BasePlugin.php
Normal file
70
app/Libraries/Plugins/BasePlugin.php
Normal file
@@ -0,0 +1,70 @@
|
||||
<?php
|
||||
|
||||
namespace App\Libraries\Plugins;
|
||||
|
||||
use App\Models\PluginConfig;
|
||||
|
||||
abstract class BasePlugin implements PluginInterface
|
||||
{
|
||||
protected PluginConfig $configModel;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->configModel = new PluginConfig();
|
||||
}
|
||||
|
||||
public function install(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public function uninstall(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public function isEnabled(): bool
|
||||
{
|
||||
$enabled = $this->configModel->getValue("{$this->getPluginId()}_enabled");
|
||||
return $enabled === '1' || $enabled === 'true';
|
||||
}
|
||||
|
||||
protected function getSetting(string $key, mixed $default = null): mixed
|
||||
{
|
||||
$value = $this->configModel->getValue("{$this->getPluginId()}_{$key}");
|
||||
return $value ?? $default;
|
||||
}
|
||||
|
||||
protected function setSetting(string $key, mixed $value): bool
|
||||
{
|
||||
$stringValue = is_array($value) || is_object($value)
|
||||
? json_encode($value)
|
||||
: (string)$value;
|
||||
|
||||
return $this->configModel->setValue("{$this->getPluginId()}_{$key}", $stringValue);
|
||||
}
|
||||
|
||||
public function getSettings(): array
|
||||
{
|
||||
return $this->configModel->getPluginSettings($this->getPluginId());
|
||||
}
|
||||
|
||||
public function saveSettings(array $settings): bool
|
||||
{
|
||||
$prefixedSettings = [];
|
||||
foreach ($settings as $key => $value) {
|
||||
if (is_array($value) || is_object($value)) {
|
||||
$prefixedSettings["{$this->getPluginId()}_{$key}"] = json_encode($value);
|
||||
} else {
|
||||
$prefixedSettings["{$this->getPluginId()}_{$key}"] = (string)$value;
|
||||
}
|
||||
}
|
||||
|
||||
return $this->configModel->batchSave($prefixedSettings);
|
||||
}
|
||||
|
||||
protected function log(string $level, string $message): void
|
||||
{
|
||||
log_message($level, "[Plugin:{$this->getPluginName()}] {$message}");
|
||||
}
|
||||
}
|
||||
56
app/Libraries/Plugins/PluginInterface.php
Normal file
56
app/Libraries/Plugins/PluginInterface.php
Normal file
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
|
||||
namespace App\Libraries\Plugins;
|
||||
|
||||
interface PluginInterface
|
||||
{
|
||||
public function getPluginId(): string;
|
||||
|
||||
public function getPluginName(): string;
|
||||
|
||||
public function getPluginDescription(): string;
|
||||
|
||||
public function getVersion(): string;
|
||||
|
||||
/**
|
||||
* Register event listeners for this plugin.
|
||||
*
|
||||
* Use Events::on() to register callbacks for OSPOS events.
|
||||
* This method is called when the plugin is loaded and enabled.
|
||||
*
|
||||
* Example:
|
||||
* Events::on('item_sale', [$this, 'onItemSale']);
|
||||
* Events::on('item_change', [$this, 'onItemChange']);
|
||||
*/
|
||||
public function registerEvents(): void;
|
||||
|
||||
/**
|
||||
* Install the plugin.
|
||||
*
|
||||
* Called when the plugin is first enabled. Use this to create database tables,
|
||||
* set default configuration values, and run any setup required.
|
||||
*/
|
||||
public function install(): bool;
|
||||
|
||||
/**
|
||||
* Uninstall the plugin.
|
||||
*
|
||||
* Called when the plugin is being removed. Use this to remove database tables,
|
||||
* clean up configuration, etc.
|
||||
*/
|
||||
public function uninstall(): bool;
|
||||
|
||||
public function isEnabled(): bool;
|
||||
|
||||
/**
|
||||
* Get the path to the plugin's configuration view file.
|
||||
* Returns null if the plugin has no configuration UI.
|
||||
*
|
||||
* Example: 'Plugins/mailchimp/config'
|
||||
*/
|
||||
public function getConfigView(): ?string;
|
||||
|
||||
public function getSettings(): array;
|
||||
|
||||
public function saveSettings(array $settings): bool;
|
||||
}
|
||||
174
app/Libraries/Plugins/PluginManager.php
Normal file
174
app/Libraries/Plugins/PluginManager.php
Normal file
@@ -0,0 +1,174 @@
|
||||
<?php
|
||||
|
||||
namespace App\Libraries\Plugins;
|
||||
|
||||
use App\Models\PluginConfig;
|
||||
use CodeIgniter\Events\Events;
|
||||
use RecursiveDirectoryIterator;
|
||||
use RecursiveIteratorIterator;
|
||||
|
||||
class PluginManager
|
||||
{
|
||||
private array $plugins = [];
|
||||
private array $enabledPlugins = [];
|
||||
private PluginConfig $configModel;
|
||||
private string $pluginsPath;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->configModel = new PluginConfig();
|
||||
$this->pluginsPath = APPPATH . 'Plugins';
|
||||
}
|
||||
|
||||
public function discoverPlugins(): void
|
||||
{
|
||||
if (!is_dir($this->pluginsPath)) {
|
||||
log_message('debug', 'Plugins directory does not exist: ' . $this->pluginsPath);
|
||||
return;
|
||||
}
|
||||
|
||||
$iterator = new RecursiveIteratorIterator(
|
||||
new RecursiveDirectoryIterator($this->pluginsPath, RecursiveDirectoryIterator::SKIP_DOTS),
|
||||
RecursiveIteratorIterator::SELF_FIRST
|
||||
);
|
||||
|
||||
foreach ($iterator as $file) {
|
||||
if ($file->isDir() || $file->getExtension() !== 'php') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$className = $this->getClassNameFromFile($file->getPathname());
|
||||
|
||||
if (!$className) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!class_exists($className)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!is_subclass_of($className, PluginInterface::class)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$plugin = new $className();
|
||||
|
||||
$this->plugins[$plugin->getPluginId()] = $plugin;
|
||||
log_message('debug', "Discovered plugin: {$plugin->getPluginName()}");
|
||||
}
|
||||
}
|
||||
|
||||
private function getClassNameFromFile(string $pathname): ?string
|
||||
{
|
||||
$relativePath = str_replace($this->pluginsPath . DIRECTORY_SEPARATOR, '', $pathname);
|
||||
$relativePath = str_replace(DIRECTORY_SEPARATOR, '\\', $relativePath);
|
||||
$className = 'App\\Plugins\\' . str_replace('.php', '', $relativePath);
|
||||
|
||||
return $className;
|
||||
}
|
||||
|
||||
public function registerPluginEvents(): void
|
||||
{
|
||||
foreach ($this->plugins as $pluginId => $plugin) {
|
||||
if ($this->isPluginEnabled($pluginId)) {
|
||||
$this->enabledPlugins[$pluginId] = $plugin;
|
||||
$plugin->registerEvents();
|
||||
log_message('debug', "Registered events for plugin: {$plugin->getPluginName()}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function getAllPlugins(): array
|
||||
{
|
||||
return $this->plugins;
|
||||
}
|
||||
|
||||
public function getEnabledPlugins(): array
|
||||
{
|
||||
return $this->enabledPlugins;
|
||||
}
|
||||
|
||||
public function getPlugin(string $pluginId): ?PluginInterface
|
||||
{
|
||||
return $this->plugins[$pluginId] ?? null;
|
||||
}
|
||||
|
||||
public function isPluginEnabled(string $pluginId): bool
|
||||
{
|
||||
$enabled = $this->configModel->getValue($this->getEnabledKey($pluginId));
|
||||
return $enabled === '1' || $enabled === 'true';
|
||||
}
|
||||
|
||||
public function enablePlugin(string $pluginId): bool
|
||||
{
|
||||
$plugin = $this->getPlugin($pluginId);
|
||||
if (!$plugin) {
|
||||
log_message('error', "Plugin not found: {$pluginId}");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!$this->configModel->exists($this->getInstalledKey($pluginId))) {
|
||||
if (!$plugin->install()) {
|
||||
log_message('error', "Failed to install plugin: {$pluginId}");
|
||||
return false;
|
||||
}
|
||||
$this->configModel->setValue($this->getInstalledKey($pluginId), '1');
|
||||
}
|
||||
|
||||
$this->configModel->setValue($this->getEnabledKey($pluginId), '1');
|
||||
log_message('info', "Plugin enabled: {$pluginId}");
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public function disablePlugin(string $pluginId): bool
|
||||
{
|
||||
if (!$this->getPlugin($pluginId)) {
|
||||
log_message('error', "Plugin not found: {$pluginId}");
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->configModel->setValue($this->getEnabledKey($pluginId), '0');
|
||||
log_message('info', "Plugin disabled: {$pluginId}");
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public function uninstallPlugin(string $pluginId): bool
|
||||
{
|
||||
$plugin = $this->getPlugin($pluginId);
|
||||
if (!$plugin) {
|
||||
log_message('error', "Plugin not found: {$pluginId}");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!$plugin->uninstall()) {
|
||||
log_message('error', "Failed to uninstall plugin: {$pluginId}");
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->configModel->deleteAllStartingWith($pluginId . '_');
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public function getSetting(string $pluginId, string $key, mixed $default = null): mixed
|
||||
{
|
||||
return $this->configModel->getValue("{$pluginId}_{$key}") ?? $default;
|
||||
}
|
||||
|
||||
public function setSetting(string $pluginId, string $key, mixed $value): bool
|
||||
{
|
||||
return $this->configModel->setValue("{$pluginId}_{$key}", $value);
|
||||
}
|
||||
|
||||
private function getEnabledKey(string $pluginId): string
|
||||
{
|
||||
return "{$pluginId}_enabled";
|
||||
}
|
||||
|
||||
private function getInstalledKey(string $pluginId): string
|
||||
{
|
||||
return "{$pluginId}_installed";
|
||||
}
|
||||
}
|
||||
107
app/Models/PluginConfig.php
Normal file
107
app/Models/PluginConfig.php
Normal file
@@ -0,0 +1,107 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use CodeIgniter\Model;
|
||||
|
||||
class PluginConfig extends Model
|
||||
{
|
||||
protected $table = 'plugin_config';
|
||||
protected $primaryKey = 'key';
|
||||
protected $useAutoIncrement = false;
|
||||
protected $useSoftDeletes = false;
|
||||
protected $allowedFields = [
|
||||
'key',
|
||||
'value'
|
||||
];
|
||||
|
||||
public function exists(string $key): bool
|
||||
{
|
||||
$builder = $this->db->table('plugin_config');
|
||||
$builder->where('key', $key);
|
||||
|
||||
return ($builder->get()->getNumRows() === 1);
|
||||
}
|
||||
|
||||
public function getValue(string $key): ?string
|
||||
{
|
||||
$builder = $this->db->table('plugin_config');
|
||||
$query = $builder->getWhere(['key' => $key], 1);
|
||||
|
||||
if ($query->getNumRows() === 1) {
|
||||
return $query->getRow()->value;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public function setValue(string $key, string $value): bool
|
||||
{
|
||||
$builder = $this->db->table('plugin_config');
|
||||
|
||||
if ($this->exists($key)) {
|
||||
return $builder->update(['value' => $value], ['key' => $key]);
|
||||
}
|
||||
|
||||
return $builder->insert(['key' => $key, 'value' => $value]);
|
||||
}
|
||||
|
||||
public function getPluginSettings(string $pluginId): array
|
||||
{
|
||||
$builder = $this->db->table('plugin_config');
|
||||
$builder->like('key', $pluginId . '_', 'after');
|
||||
$query = $builder->get();
|
||||
|
||||
$settings = [];
|
||||
$prefix = $pluginId . '_';
|
||||
foreach ($query->getResult() as $row) {
|
||||
$key = str_starts_with($row->key, $prefix)
|
||||
? substr($row->key, strlen($prefix))
|
||||
: $row->key;
|
||||
$settings[$key] = $row->value;
|
||||
}
|
||||
|
||||
return $settings;
|
||||
}
|
||||
|
||||
public function deleteKey(string $key): bool
|
||||
{
|
||||
$builder = $this->db->table('plugin_config');
|
||||
return $builder->delete(['key' => $key]);
|
||||
}
|
||||
|
||||
public function deleteAllStartingWith(string $prefix): bool
|
||||
{
|
||||
$builder = $this->db->table('plugin_config');
|
||||
$builder->like('key', $prefix, 'after');
|
||||
return $builder->delete();
|
||||
}
|
||||
|
||||
public function batchSave(array $data): bool
|
||||
{
|
||||
$success = true;
|
||||
|
||||
$this->db->transStart();
|
||||
|
||||
foreach ($data as $key => $value) {
|
||||
$success &= $this->setValue($key, $value);
|
||||
}
|
||||
|
||||
$this->db->transComplete();
|
||||
|
||||
return $success && $this->db->transStatus();
|
||||
}
|
||||
|
||||
public function getAll(): array
|
||||
{
|
||||
$builder = $this->db->table('plugin_config');
|
||||
$query = $builder->get();
|
||||
|
||||
$configs = [];
|
||||
foreach ($query->getResult() as $row) {
|
||||
$configs[$row->key] = $row->value;
|
||||
}
|
||||
|
||||
return $configs;
|
||||
}
|
||||
}
|
||||
193
app/Plugins/MailchimpPlugin.php
Normal file
193
app/Plugins/MailchimpPlugin.php
Normal file
@@ -0,0 +1,193 @@
|
||||
<?php
|
||||
|
||||
namespace App\Plugins;
|
||||
|
||||
use App\Libraries\Plugins\BasePlugin;
|
||||
use App\Libraries\Mailchimp_lib;
|
||||
use CodeIgniter\Events\Events;
|
||||
|
||||
/**
|
||||
* Plugin that integrates OSPOS with Mailchimp for customer newsletter subscriptions.
|
||||
*/
|
||||
class MailchimpPlugin extends BasePlugin
|
||||
{
|
||||
private ?Mailchimp_lib $mailchimpLib = null;
|
||||
|
||||
public function getPluginId(): string
|
||||
{
|
||||
return 'mailchimp';
|
||||
}
|
||||
|
||||
public function getPluginName(): string
|
||||
{
|
||||
return 'Mailchimp';
|
||||
}
|
||||
|
||||
public function getPluginDescription(): string
|
||||
{
|
||||
return $this->lang('mailchimp_description');
|
||||
}
|
||||
|
||||
public function getVersion(): string
|
||||
{
|
||||
return '1.0.0';
|
||||
}
|
||||
|
||||
public function registerEvents(): void
|
||||
{
|
||||
Events::on('customer_saved', [$this, 'onCustomerSaved']);
|
||||
Events::on('customer_deleted', [$this, 'onCustomerDeleted']);
|
||||
|
||||
log_message('debug', 'Mailchimp plugin events registered');
|
||||
}
|
||||
|
||||
public function install(): bool
|
||||
{
|
||||
log_message('info', 'Installing Mailchimp plugin');
|
||||
|
||||
$this->setSetting('api_key', '');
|
||||
$this->setSetting('list_id', '');
|
||||
$this->setSetting('sync_on_save', '1');
|
||||
$this->setSetting('enabled', '0');
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public function uninstall(): bool
|
||||
{
|
||||
log_message('info', 'Uninstalling Mailchimp plugin');
|
||||
return true;
|
||||
}
|
||||
|
||||
public function getConfigView(): ?string
|
||||
{
|
||||
return 'Plugins/mailchimp/config';
|
||||
}
|
||||
|
||||
public function getSettings(): array
|
||||
{
|
||||
return [
|
||||
'api_key' => $this->getSetting('api_key', ''),
|
||||
'list_id' => $this->getSetting('list_id', ''),
|
||||
'sync_on_save' => $this->getSetting('sync_on_save', '1'),
|
||||
'enabled' => $this->getSetting('enabled', '0'),
|
||||
];
|
||||
}
|
||||
|
||||
public function saveSettings(array $settings): bool
|
||||
{
|
||||
if (isset($settings['api_key'])) {
|
||||
$this->setSetting('api_key', $settings['api_key']);
|
||||
}
|
||||
|
||||
if (isset($settings['list_id'])) {
|
||||
$this->setSetting('list_id', $settings['list_id']);
|
||||
}
|
||||
|
||||
if (isset($settings['sync_on_save'])) {
|
||||
$this->setSetting('sync_on_save', $settings['sync_on_save'] ? '1' : '0');
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public function onCustomerSaved(array $customerData): void
|
||||
{
|
||||
if (!$this->shouldSyncOnSave()) {
|
||||
return;
|
||||
}
|
||||
|
||||
log_message('debug', "Customer saved event received for ID: {$customerData['person_id']}");
|
||||
|
||||
try {
|
||||
$this->subscribeCustomer($customerData);
|
||||
} catch (\Exception $e) {
|
||||
log_message('error', "Failed to sync customer to Mailchimp: {$e->getMessage()}");
|
||||
}
|
||||
}
|
||||
|
||||
public function onCustomerDeleted(int $customerId): void
|
||||
{
|
||||
log_message('debug', "Customer deleted event received for ID: {$customerId}");
|
||||
}
|
||||
|
||||
private function subscribeCustomer(array $customerData): bool
|
||||
{
|
||||
$apiKey = $this->getSetting('api_key');
|
||||
$listId = $this->getSetting('list_id');
|
||||
|
||||
if (empty($apiKey) || empty($listId)) {
|
||||
log_message('warning', 'Mailchimp API key or List ID not configured');
|
||||
return false;
|
||||
}
|
||||
|
||||
if (empty($customerData['email'])) {
|
||||
log_message('debug', 'Customer has no email, skipping Mailchimp sync');
|
||||
return false;
|
||||
}
|
||||
|
||||
$mailchimp = $this->getMailchimpLib(['api_key' => $apiKey]);
|
||||
|
||||
$result = $mailchimp->addOrUpdateMember(
|
||||
$listId,
|
||||
$customerData['email'],
|
||||
$customerData['first_name'] ?? '',
|
||||
$customerData['last_name'] ?? '',
|
||||
'subscribed'
|
||||
);
|
||||
|
||||
if ($result) {
|
||||
log_message('info', "Successfully subscribed customer ID {$customerData['person_id']} to Mailchimp");
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private function shouldSyncOnSave(): bool
|
||||
{
|
||||
return $this->getSetting('sync_on_save', '1') === '1';
|
||||
}
|
||||
|
||||
private function getMailchimpLib(array $params = []): Mailchimp_lib
|
||||
{
|
||||
if ($this->mailchimpLib === null) {
|
||||
$this->mailchimpLib = new Mailchimp_lib($params);
|
||||
}
|
||||
return $this->mailchimpLib;
|
||||
}
|
||||
|
||||
public function testConnection(): array
|
||||
{
|
||||
$apiKey = $this->getSetting('api_key');
|
||||
|
||||
if (empty($apiKey)) {
|
||||
return ['success' => false, 'message' => $this->lang('mailchimp_api_key_required')];
|
||||
}
|
||||
|
||||
$mailchimp = $this->getMailchimpLib(['api_key' => $apiKey]);
|
||||
$result = $mailchimp->getLists();
|
||||
|
||||
if ($result && isset($result['lists'])) {
|
||||
return [
|
||||
'success' => true,
|
||||
'message' => $this->lang('mailchimp_key_successfully'),
|
||||
'lists' => $result['lists']
|
||||
];
|
||||
}
|
||||
|
||||
return ['success' => false, 'message' => $this->lang('mailchimp_key_unsuccessfully')];
|
||||
}
|
||||
|
||||
protected function lang(string $key, array $data = []): string
|
||||
{
|
||||
$language = \Config\Services::language();
|
||||
$language->addLanguagePath(APPPATH . 'Plugins/MailchimpPlugin/Language/');
|
||||
return $language->getLine($key, $data);
|
||||
}
|
||||
|
||||
protected function getPluginDir(): string
|
||||
{
|
||||
return 'MailchimpPlugin';
|
||||
}
|
||||
}
|
||||
13
app/Plugins/MailchimpPlugin/Language/en/MailchimpPlugin.php
Normal file
13
app/Plugins/MailchimpPlugin/Language/en/MailchimpPlugin.php
Normal file
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
return [
|
||||
'mailchimp' => 'Mailchimp',
|
||||
'mailchimp_description' => 'Integrate with Mailchimp to sync customers to mailing lists when they are created or updated.',
|
||||
'mailchimp_api_key' => 'Mailchimp API Key',
|
||||
'mailchimp_api_key_required' => 'API key not configured',
|
||||
'mailchimp_configuration' => 'Mailchimp Configuration',
|
||||
'mailchimp_key_successfully' => 'API Key is valid.',
|
||||
'mailchimp_key_unsuccessfully' => 'API Key is invalid.',
|
||||
'mailchimp_lists' => 'Mailchimp List(s)',
|
||||
'mailchimp_tooltip' => 'Click the icon for an API Key.',
|
||||
];
|
||||
528
app/Plugins/README.md
Normal file
528
app/Plugins/README.md
Normal file
@@ -0,0 +1,528 @@
|
||||
# OSPOS Plugin System
|
||||
|
||||
## Overview
|
||||
|
||||
The OSPOS Plugin System allows third-party integrations to extend the application's functionality without modifying core code. Plugins can listen to events, add configuration settings, and integrate with external services.
|
||||
|
||||
## Installation
|
||||
|
||||
### Self-Contained Plugin Packages
|
||||
|
||||
Plugins are self-contained packages that can be installed by simply dropping the plugin folder into `app/Plugins/`:
|
||||
|
||||
```
|
||||
app/Plugins/
|
||||
├── MailchimpPlugin/ # Plugin directory (self-contained)
|
||||
│ ├── MailchimpPlugin.php # Main plugin class (required - must match directory name)
|
||||
│ ├── Language/ # Plugin-specific translations (self-contained)
|
||||
│ │ ├── en/
|
||||
│ │ │ └── MailchimpPlugin.php
|
||||
│ │ └── es-ES/
|
||||
│ │ └── MailchimpPlugin.php
|
||||
│ └── Views/ # Plugin-specific views
|
||||
│ └── config.php
|
||||
```
|
||||
|
||||
### Installation Steps
|
||||
|
||||
1. **Download the plugin** - Copy the plugin folder/file to `app/Plugins/`
|
||||
2. **Auto-discovery** - The plugin will be automatically discovered on next page load
|
||||
3. **Enable** - Enable it from the admin interface (Plugins menu)
|
||||
4. **Configure** - Configure plugin settings if needed
|
||||
|
||||
### Plugin Discovery
|
||||
|
||||
The PluginManager recursively scans `app/Plugins/` directory:
|
||||
|
||||
- **Single-file plugins**: `app/Plugins/MyPlugin.php` with namespace `App\Plugins\MyPlugin`
|
||||
- **Directory plugins**: `app/Plugins/MyPlugin/MyPlugin.php` with namespace `App\Plugins\MyPlugin\MyPlugin`
|
||||
|
||||
Both formats are supported, but directory plugins allow for self-contained packages with their own components.
|
||||
|
||||
## Architecture
|
||||
|
||||
### Plugin Interface
|
||||
|
||||
All plugins must implement `App\Libraries\Plugins\PluginInterface`:
|
||||
|
||||
```php
|
||||
interface PluginInterface
|
||||
{
|
||||
public function getPluginId(): string; // Unique identifier
|
||||
public function getPluginName(): string; // Display name
|
||||
public function getPluginDescription(): string;
|
||||
public function getVersion(): string;
|
||||
public function registerEvents(): void; // Register event listeners
|
||||
public function install(): bool; // First-time setup
|
||||
public function uninstall(): bool; // Cleanup
|
||||
public function isEnabled(): bool;
|
||||
public function getConfigView(): ?string; // Configuration view path
|
||||
public function getSettings(): array;
|
||||
public function saveSettings(array $settings): bool;
|
||||
}
|
||||
```
|
||||
|
||||
### Base Plugin Class
|
||||
|
||||
Extend `App\Libraries\Plugins\BasePlugin` for common functionality:
|
||||
|
||||
```php
|
||||
class MyPlugin extends BasePlugin
|
||||
{
|
||||
public function getPluginId(): string { return 'my_plugin'; }
|
||||
public function getPluginName(): string { return 'My Plugin'; }
|
||||
// ... implement other methods
|
||||
}
|
||||
```
|
||||
|
||||
### Plugin Manager
|
||||
|
||||
The `PluginManager` class handles:
|
||||
- Plugin discovery from `app/Plugins/` directory (recursive scan)
|
||||
- Loading and registering enabled plugins
|
||||
- Managing plugin settings
|
||||
|
||||
**Important:** The PluginManager only calls `registerEvents()` for enabled plugins. Disabled plugins never have their event callbacks registered with `Events::on()`. This means **you do not need to check `$this->isEnabled()` in your callback methods** - if the callback is registered, the plugin is enabled.
|
||||
|
||||
## Available Events
|
||||
|
||||
OSPOS fires these events that plugins can listen to:
|
||||
|
||||
| Event | Arguments | Description |
|
||||
|-------|-----------|-------------|
|
||||
| `item_sale` | `array $saleData` | Fired when a sale is completed |
|
||||
| `item_return` | `array $returnData` | Fired when a return is processed |
|
||||
| `item_change` | `int $itemId` | Fired when an item is created/updated/deleted |
|
||||
| `item_inventory` | `array $inventoryData` | Fired on inventory changes |
|
||||
| `items_csv_import` | `array $importData` | Fired after items CSV import |
|
||||
| `customers_csv_import` | `array $importData` | Fired after customers CSV import |
|
||||
|
||||
## View Hooks (Injecting Plugin Content into Views)
|
||||
|
||||
Plugins can inject UI elements into core views using the event-based view hook system. This allows plugins to add buttons, tabs, or other content without modifying core view files.
|
||||
|
||||
### How It Works
|
||||
|
||||
1. **Core views define hook points** using the `plugin_content()` helper
|
||||
2. **Plugins register listeners** for these view hooks in `registerEvents()`
|
||||
3. **Content is rendered** only when the plugin is enabled
|
||||
|
||||
### Step 1: Adding Hook Points in Core Views
|
||||
|
||||
In your core view files, use the `plugin_content()` helper to define injection points:
|
||||
|
||||
```php
|
||||
// In app/Views/sales/receipt.php
|
||||
<div class="receipt-actions">
|
||||
<!-- Existing buttons -->
|
||||
<?= plugin_content('receipt_actions', ['sale' => $sale]) ?>
|
||||
</div>
|
||||
|
||||
// In app/Views/customers/form.php
|
||||
<ul class="nav nav-tabs">
|
||||
<!-- Existing tabs -->
|
||||
<?= plugin_content('customer_tabs', ['customer' => $customer]) ?>
|
||||
</ul>
|
||||
```
|
||||
|
||||
### Step 2: Plugin Registers View Hook
|
||||
|
||||
In your plugin class, register a listener that returns HTML content:
|
||||
|
||||
```php
|
||||
class MailchimpPlugin extends BasePlugin
|
||||
{
|
||||
public function registerEvents(): void
|
||||
{
|
||||
Events::on('customer_saved', [$this, 'onCustomerSaved']);
|
||||
|
||||
// View hooks - inject content into core views
|
||||
Events::on('view:customer_tabs', [$this, 'injectCustomerTab']);
|
||||
}
|
||||
|
||||
public function injectCustomerTab(array $data): string
|
||||
{
|
||||
return view('Plugins/MailchimpPlugin/Views/customer_tab', $data);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Plugin View Files
|
||||
|
||||
The plugin's view files are self-contained within the plugin directory:
|
||||
|
||||
```php
|
||||
// app/Plugins/MailchimpPlugin/Views/customer_tab.php
|
||||
<li>
|
||||
<a href="#mailchimp_panel" data-toggle="tab">
|
||||
<span class="glyphicon glyphicon-envelope"> </span>
|
||||
Mailchimp
|
||||
</a>
|
||||
</li>
|
||||
```
|
||||
|
||||
### Helper Functions
|
||||
|
||||
The `plugin_helper.php` provides two functions:
|
||||
|
||||
```php
|
||||
// Render plugin content for a hook point
|
||||
plugin_content(string $section, array $data = []): string
|
||||
|
||||
// Check if any plugin has registered for a hook (for conditional rendering)
|
||||
plugin_content_exists(string $section): bool
|
||||
```
|
||||
|
||||
### Standard Hook Points
|
||||
|
||||
Core views should define these standard hook points:
|
||||
|
||||
| Hook Name | Location | Usage |
|
||||
|-----------|----------|-------|
|
||||
| `view:receipt_actions` | Receipt view action buttons | Add receipt-related buttons |
|
||||
| `view:customer_tabs` | Customer form tabs | Add customer-related tabs |
|
||||
| `view:item_form_buttons` | Item form action buttons | Add item-related buttons |
|
||||
| `view:sales_complete` | Sale complete screen | Post-sale integration UI |
|
||||
| `view:reports_menu` | Reports menu | Add custom report links |
|
||||
|
||||
### Benefits
|
||||
|
||||
- **Self-Contained**: Plugin UI stays in plugin directory
|
||||
- **Conditional**: Only renders when plugin is enabled
|
||||
- **Data Access**: Pass context (sale, customer, etc.) to plugin views
|
||||
- **Multiple Plugins**: Multiple plugins can hook the same location
|
||||
- **Clean Separation**: Core views remain unmodified
|
||||
|
||||
## Creating a Plugin
|
||||
|
||||
### Simple Plugin (Single File)
|
||||
|
||||
For plugins that only need to listen to events without complex UI or database tables:
|
||||
|
||||
```php
|
||||
<?php
|
||||
// app/Plugins/MyPlugin.php
|
||||
|
||||
namespace App\Plugins;
|
||||
|
||||
use App\Libraries\Plugins\BasePlugin;
|
||||
use CodeIgniter\Events\Events;
|
||||
|
||||
class MyPlugin extends BasePlugin
|
||||
{
|
||||
public function getPluginId(): string
|
||||
{
|
||||
return 'my_plugin';
|
||||
}
|
||||
|
||||
public function getPluginName(): string
|
||||
{
|
||||
return 'My Integration Plugin';
|
||||
}
|
||||
|
||||
public function getPluginDescription(): string
|
||||
{
|
||||
return 'Integrates OSPOS with external service';
|
||||
}
|
||||
|
||||
public function getVersion(): string
|
||||
{
|
||||
return '1.0.0';
|
||||
}
|
||||
|
||||
public function registerEvents(): void
|
||||
{
|
||||
Events::on('item_sale', [$this, 'onItemSale']);
|
||||
Events::on('item_change', [$this, 'onItemChange']);
|
||||
}
|
||||
|
||||
public function onItemSale(array $saleData): void
|
||||
{
|
||||
log_message('info', "Processing sale: {$saleData['sale_id_num']}");
|
||||
}
|
||||
|
||||
public function onItemChange(int $itemId): void
|
||||
{
|
||||
log_message('info', "Item changed: {$itemId}");
|
||||
}
|
||||
|
||||
public function install(): bool
|
||||
{
|
||||
$this->setSetting('api_key', '');
|
||||
$this->setSetting('enabled', '0');
|
||||
return true;
|
||||
}
|
||||
|
||||
public function getConfigView(): ?string
|
||||
{
|
||||
return 'Plugins/my_plugin/config';
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Complex Plugin (Self-Contained Directory)
|
||||
|
||||
For plugins that need database tables, controllers, models, and views:
|
||||
|
||||
```
|
||||
app/Plugins/
|
||||
└── MailchimpPlugin/ # Plugin directory
|
||||
├── MailchimpPlugin.php # Main class - namespace: App\Plugins\MailchimpPlugin\MailchimpPlugin
|
||||
├── Models/ # Plugin models
|
||||
│ └── MailchimpData.php
|
||||
├── Controllers/ # Plugin controllers
|
||||
│ └── Dashboard.php
|
||||
├── Views/ # Plugin views
|
||||
│ ├── config.php
|
||||
│ └── dashboard.php
|
||||
├── Language/ # Plugin translations (self-contained)
|
||||
│ ├── en/
|
||||
│ │ └── MailchimpPlugin.php
|
||||
│ └── es-ES/
|
||||
│ └── MailchimpPlugin.php
|
||||
└── Libraries/ # Plugin libraries
|
||||
└── ApiClient.php
|
||||
```
|
||||
|
||||
**Main Plugin Class:**
|
||||
|
||||
```php
|
||||
<?php
|
||||
// app/Plugins/MailchimpPlugin/MailchimpPlugin.php
|
||||
|
||||
namespace App\Plugins\MailchimpPlugin;
|
||||
|
||||
use App\Libraries\Plugins\BasePlugin;
|
||||
use App\Plugins\MailchimpPlugin\Models\MailchimpData;
|
||||
use CodeIgniter\Events\Events;
|
||||
|
||||
class MailchimpPlugin extends BasePlugin
|
||||
{
|
||||
private ?MailchimpData $dataModel = null;
|
||||
|
||||
public function getPluginId(): string
|
||||
{
|
||||
return 'mailchimp';
|
||||
}
|
||||
|
||||
public function getPluginName(): string
|
||||
{
|
||||
return 'Mailchimp';
|
||||
}
|
||||
|
||||
public function getPluginDescription(): string
|
||||
{
|
||||
return 'Integrate with Mailchimp to sync customers to mailing lists.';
|
||||
}
|
||||
|
||||
public function getVersion(): string
|
||||
{
|
||||
return '1.0.0';
|
||||
}
|
||||
|
||||
public function registerEvents(): void
|
||||
{
|
||||
Events::on('customer_saved', [$this, 'onCustomerSaved']);
|
||||
Events::on('customer_deleted', [$this, 'onCustomerDeleted']);
|
||||
}
|
||||
|
||||
private function getDataModel(): MailchimpData
|
||||
{
|
||||
if ($this->dataModel === null) {
|
||||
$this->dataModel = new MailchimpData();
|
||||
}
|
||||
return $this->dataModel;
|
||||
}
|
||||
|
||||
public function onCustomerSaved(array $customerData): void
|
||||
{
|
||||
if (!$this->shouldSyncOnSave()) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->getDataModel()->syncCustomer($customerData);
|
||||
}
|
||||
|
||||
public function install(): bool
|
||||
{
|
||||
$this->setSetting('api_key', '');
|
||||
$this->setSetting('list_id', '');
|
||||
$this->setSetting('sync_on_save', '1');
|
||||
return true;
|
||||
}
|
||||
|
||||
public function uninstall(): bool
|
||||
{
|
||||
$this->getDataModel()->dropTable();
|
||||
return true;
|
||||
}
|
||||
|
||||
public function getConfigView(): ?string
|
||||
{
|
||||
return 'Plugins/MailchimpPlugin/Views/config';
|
||||
}
|
||||
|
||||
protected function lang(string $key, array $data = []): string
|
||||
{
|
||||
$language = \Config\Services::language();
|
||||
$language->addLanguagePath(APPPATH . 'Plugins/MailchimpPlugin/Language/');
|
||||
return $language->getLine($key, $data);
|
||||
}
|
||||
|
||||
protected function getPluginDir(): string
|
||||
{
|
||||
return 'MailchimpPlugin';
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Internationalization (Language Files)
|
||||
|
||||
Plugins can include their own language files, making them completely self-contained. This allows plugins to provide translations without modifying core language files.
|
||||
|
||||
### Plugin Language Directory Structure
|
||||
|
||||
```
|
||||
app/Plugins/
|
||||
└── MailchimpPlugin/
|
||||
├── MailchimpPlugin.php
|
||||
├── Language/
|
||||
│ ├── en/
|
||||
│ │ └── MailchimpPlugin.php # English translations
|
||||
│ ├── es-ES/
|
||||
│ │ └── MailchimpPlugin.php # Spanish translations
|
||||
│ └── de-DE/
|
||||
│ └── MailchimpPlugin.php # German translations
|
||||
└── Views/
|
||||
└── config.php
|
||||
```
|
||||
|
||||
### Language File Format
|
||||
|
||||
Each language file returns an array of translation strings:
|
||||
|
||||
```php
|
||||
<?php
|
||||
// app/Plugins/MailchimpPlugin/Language/en/MailchimpPlugin.php
|
||||
|
||||
return [
|
||||
'mailchimp' => 'Mailchimp',
|
||||
'mailchimp_description' => 'Integrate with Mailchimp to sync customers to mailing lists.',
|
||||
'mailchimp_api_key' => 'Mailchimp API Key',
|
||||
'mailchimp_configuration' => 'Mailchimp Configuration',
|
||||
'mailchimp_key_successfully' => 'API Key is valid.',
|
||||
'mailchimp_key_unsuccessfully' => 'API Key is invalid.',
|
||||
];
|
||||
```
|
||||
|
||||
### Loading Language Strings in Plugins
|
||||
|
||||
The `BasePlugin` class can provide a helper method to load plugin-specific language strings:
|
||||
|
||||
```php
|
||||
protected function lang(string $key, array $data = []): string
|
||||
{
|
||||
$language = \Config\Services::language();
|
||||
$language->addLanguagePath(APPPATH . 'Plugins/' . $this->getPluginDir() . '/Language/');
|
||||
return $language->getLine($key, $data);
|
||||
}
|
||||
|
||||
protected function getPluginDir(): string
|
||||
{
|
||||
return 'MailchimpPlugin';
|
||||
}
|
||||
```
|
||||
|
||||
### Benefits of Self-Contained Language Files
|
||||
|
||||
1. **Plugin Independence**: No need to modify core language files
|
||||
2. **Easy Distribution**: Plugin zip includes all translations
|
||||
3. **Fallback Support**: Missing translations fall back to English
|
||||
4. **User Contributions**: Users can add translations to `Language/{locale}/` in the plugin directory
|
||||
|
||||
## Plugin Settings
|
||||
|
||||
Store plugin-specific settings using:
|
||||
|
||||
```php
|
||||
// Get setting
|
||||
$value = $this->getSetting('setting_key', 'default_value');
|
||||
|
||||
// Set setting
|
||||
$this->setSetting('setting_key', 'value');
|
||||
|
||||
// Get all plugin settings
|
||||
$settings = $this->getSettings();
|
||||
|
||||
// Save multiple settings
|
||||
$this->saveSettings(['key1' => 'value1', 'key2' => 'value2']);
|
||||
```
|
||||
|
||||
Settings are prefixed with the plugin ID (e.g., `mailchimp_api_key`) and stored in `ospos_plugin_config` table.
|
||||
|
||||
## Namespace Reference
|
||||
|
||||
| File Location | Namespace |
|
||||
|--------------|-----------|
|
||||
| `app/Plugins/MyPlugin.php` | `App\Plugins\MyPlugin` |
|
||||
| `app/Plugins/MailchimpPlugin/MailchimpPlugin.php` | `App\Plugins\MailchimpPlugin\MailchimpPlugin` |
|
||||
| `app/Plugins/MailchimpPlugin/Models/MailchimpData.php` | `App\Plugins\MailchimpPlugin\Models\MailchimpData` |
|
||||
| `app/Plugins/MailchimpPlugin/Controllers/Dashboard.php` | `App\Plugins\MailchimpPlugin\Controllers\Dashboard` |
|
||||
| `app/Plugins/MailchimpPlugin/Libraries/ApiClient.php` | `App\Plugins\MailchimpPlugin\Libraries\ApiClient` |
|
||||
| `app/Plugins/MailchimpPlugin/Language/en/MailchimpPlugin.php` | *(Language file - returns array, no namespace)* |
|
||||
|
||||
## Database
|
||||
|
||||
Plugin settings are stored in the `ospos_plugin_config` table:
|
||||
|
||||
```sql
|
||||
CREATE TABLE IF NOT EXISTS `ospos_plugin_config` (
|
||||
`key` varchar(100) NOT NULL,
|
||||
`value` text NOT NULL,
|
||||
`created_at` timestamp NOT NULL DEFAULT current_timestamp(),
|
||||
`updated_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
|
||||
PRIMARY KEY (`key`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
```
|
||||
|
||||
For custom tables, plugins can create them during `install()` and drop them during `uninstall()`.
|
||||
|
||||
## Event Flow
|
||||
|
||||
1. Application triggers event: `Events::trigger('item_sale', $data)`
|
||||
2. PluginManager recursively scans `app/Plugins/` directory
|
||||
3. Each enabled plugin registers its listeners via `registerEvents()`
|
||||
4. Events::on() callbacks are invoked automatically
|
||||
|
||||
## Testing
|
||||
|
||||
Enable plugin logging to debug:
|
||||
|
||||
```php
|
||||
log_message('debug', 'Debug message');
|
||||
log_message('info', 'Info message');
|
||||
log_message('error', 'Error message');
|
||||
```
|
||||
|
||||
Check logs in `writable/logs/`.
|
||||
|
||||
## Distributing Plugins
|
||||
|
||||
Plugin developers can package their plugins as zip files:
|
||||
|
||||
```
|
||||
MailchimpPlugin-1.0.0.zip
|
||||
└── MailchimpPlugin/
|
||||
├── MailchimpPlugin.php
|
||||
├── Models/
|
||||
├── Controllers/
|
||||
├── Views/
|
||||
├── Language/
|
||||
│ ├── en/
|
||||
│ │ └── MailchimpPlugin.php
|
||||
│ └── es-ES/
|
||||
│ └── MailchimpPlugin.php
|
||||
└── README.md # Plugin documentation
|
||||
```
|
||||
|
||||
Users extract the zip to `app/Plugins/` and the plugin is ready to use.
|
||||
119
app/Views/plugins/manage.php
Normal file
119
app/Views/plugins/manage.php
Normal file
@@ -0,0 +1,119 @@
|
||||
<?= view('partial/header') ?>
|
||||
|
||||
<div class="container-fluid">
|
||||
<div class="row">
|
||||
<div class="col-md-12">
|
||||
<div class="panel panel-default">
|
||||
<div class="panel-heading">
|
||||
<h3 class="panel-title">
|
||||
<span class="glyphicon glyphicon-puzzle"></span> <?= lang('Plugins.plugin_management') ?>
|
||||
</h3>
|
||||
</div>
|
||||
<div class="panel-body">
|
||||
<?php if (empty($plugins)): ?>
|
||||
<div class="alert alert-info">
|
||||
<?= lang('Plugins.no_plugins_found') ?>
|
||||
</div>
|
||||
<?php else: ?>
|
||||
<table class="table table-striped table-hover">
|
||||
<thead>
|
||||
<tr>
|
||||
<th><?= lang('Plugins.plugin_name') ?></th>
|
||||
<th><?= lang('Plugins.plugin_description') ?></th>
|
||||
<th><?= lang('Plugins.plugin_version') ?></th>
|
||||
<th><?= lang('Plugins.plugin_status') ?></th>
|
||||
<th><?= lang('Common.actions') ?></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<?php foreach ($plugins as $pluginId => $plugin): ?>
|
||||
<tr id="plugin-row-<?= esc($pluginId) ?>">
|
||||
<td>
|
||||
<strong><?= esc($plugin['name']) ?></strong>
|
||||
<br><small class="text-muted"><?= esc($plugin['id']) ?></small>
|
||||
</td>
|
||||
<td><?= esc($plugin['description']) ?></td>
|
||||
<td><span class="label label-default"><?= esc($plugin['version']) ?></span></td>
|
||||
<td>
|
||||
<?php if ($plugin['enabled']): ?>
|
||||
<span class="label label-success"><?= lang('Plugins.active') ?></span>
|
||||
<?php else: ?>
|
||||
<span class="label label-default"><?= lang('Plugins.inactive') ?></span>
|
||||
<?php endif; ?>
|
||||
</td>
|
||||
<td>
|
||||
<?php if ($plugin['enabled']): ?>
|
||||
<button class="btn btn-warning btn-xs plugin-action"
|
||||
data-action="disable"
|
||||
data-plugin-id="<?= esc($pluginId) ?>">
|
||||
<span class="glyphicon glyphicon-pause"></span> <?= lang('Plugins.disable') ?>
|
||||
</button>
|
||||
<?php else: ?>
|
||||
<button class="btn btn-success btn-xs plugin-action"
|
||||
data-action="enable"
|
||||
data-plugin-id="<?= esc($pluginId) ?>">
|
||||
<span class="glyphicon glyphicon-play"></span> <?= lang('Plugins.enable') ?>
|
||||
</button>
|
||||
<?php endif; ?>
|
||||
|
||||
<?php if ($plugin['has_config'] && $plugin['enabled']): ?>
|
||||
<button class="btn btn-primary btn-xs plugin-config"
|
||||
data-plugin-id="<?= esc($pluginId) ?>">
|
||||
<span class="glyphicon glyphicon-cog"></span> <?= lang('Plugins.configure') ?>
|
||||
</button>
|
||||
<?php endif; ?>
|
||||
</td>
|
||||
</tr>
|
||||
<?php endforeach; ?>
|
||||
</tbody>
|
||||
</table>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Plugin Config Modal -->
|
||||
<div class="modal fade" id="plugin-config-modal" tabindex="-1" role="dialog">
|
||||
<div class="modal-dialog" role="document">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<button type="button" class="close" data-dismiss="modal">×</button>
|
||||
<h4 class="modal-title"><?= lang('Plugins.plugins') ?></h4>
|
||||
</div>
|
||||
<div class="modal-body" id="plugin-config-content">
|
||||
<!-- Config form loaded dynamically -->
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script type="text/javascript">
|
||||
$(document).ready(function() {
|
||||
$('.plugin-action').on('click', function() {
|
||||
var btn = $(this);
|
||||
var action = btn.data('action');
|
||||
var pluginId = btn.data('plugin-id');
|
||||
|
||||
$.post('plugins/manage/' + action + '/' + pluginId, {
|
||||
<?= esc(csrf_token()) ?>: '<?= esc(csrf_hash()) ?>'
|
||||
}, function(response) {
|
||||
if (response.success) {
|
||||
$.notify({ message: response.message }, { type: 'success' });
|
||||
setTimeout(function() { location.reload(); }, 1000);
|
||||
} else {
|
||||
$.notify({ message: response.message }, { type: 'danger' });
|
||||
}
|
||||
}, 'json');
|
||||
});
|
||||
|
||||
$('.plugin-config').on('click', function() {
|
||||
var pluginId = $(this).data('plugin-id');
|
||||
$('#plugin-config-content').load('plugins/manage/config/' + pluginId);
|
||||
$('#plugin-config-modal').modal('show');
|
||||
});
|
||||
});
|
||||
</script>
|
||||
|
||||
<?= view('partial/footer') ?>
|
||||
Reference in New Issue
Block a user