| Both sides previous revision Previous revision | |
| en:entwickler:plugin_development [2026/12/05 08:50] – old revision restored (2026/08/31 00:09) fasse | en:entwickler:plugin_development [2026/12/05 13:47] (current) – kainhofer |
|---|
| ====== Writing a plugin for Admidio ====== | ====== Writing a plugin for Admidio ====== |
| |
| Admidio can be extended with plugins. A plugin lives in its own directory under ''plugins/'', is | Admidio can be extended with plugins. A plugin lives in its own folder below ''plugins/'', is switched |
| switched on and off per organization, and can be removed again without leaving anything behind. You | on and off per organization, and can be removed again without leaving anything behind. You never |
| never change Admidio itself. | change Admidio itself. |
| |
| Plugins cover a wide range: | Plugins cover a wide range: |
| * **A small adjustment.** Two files and a few lines: hang a callback on a hook and change a headline, add a note to a form, supply a translation, hide a menu entry. | * **A small adjustment.** Two files and a few lines: hang a callback on a hook and change a headline, add a note to a form, supply a translation, hide a menu entry. |
| * **A card on the overview page.** A widget with its own settings, like the birthday list or "who is online" that ship with Admidio. | * **A card on the overview page.** A widget with its own settings, like the birthday list or "who is online" that ship with Admidio. |
| * **A page of its own.** An ordinary Admidio page with a form, a list, and the usual permission checks, reachable from the menu. | * **A page of its own.** An ordinary Admidio page with a form, a list and the usual permission checks, reachable from the menu. |
| * **A complete module.** Several pages, your own classes and services, your own database tables with their own update scripts, entries in the change history, command line tasks — everything a built-in Admidio module has. | * **A complete module.** Several pages, your own classes and services, your own database tables with their own update scripts, entries in the change history, command line tasks: everything a built-in Admidio module has. |
| |
| Nothing forces you up that ladder. A plugin that only registers one hook stays two files forever. | Nothing forces you up that ladder. A plugin that only registers one hook stays two files forever, and |
| | one that only brings translations or a page does not even need code that runs on every request. |
| |
| **Important:** This describes the plugin system of **Admidio 5.1**. Plugins written for 5.0 and earlier use a | <WRAP center round important 80%> |
| different mechanism and do not work unchanged. | This page describes the plugin system of **Admidio 6.0 and later**. Plugins written for Admidio 5.0 |
| | and earlier, including the first plugin manager of 5.0, use a different mechanism and do not work |
| | unchanged. See [[#changes_since_the_plugin_manager_of_admidio_50|Changes since the plugin manager of Admidio 5.0]]. |
| | |
| | How administrators install, configure, update and remove plugins is described in |
| | [[en:2.0:plugins|Installing and managing plugins]]. |
| | </WRAP> |
| | |
| | A complete, commented example plugin is part of the Admidio distribution: **plugins/hello-world/**. |
| | It shows the conventions of this page in one working plugin, and its ''README.md'' is the short form |
| | of this page. Copy the folder, rename it, and start deleting what you do not need. |
| |
| ===== The smallest plugin ===== | ===== The smallest plugin ===== |
| |
| Two files. Create ''plugins/hello/'': | A manifest and the one thing the plugin contributes. Here that is a hook, so the plugin is two files. |
| | Create ''plugins/hello/'': |
| |
| <code javascript plugin.json> | <code javascript plugin.json> |
| <?php | <?php |
| use Admidio\Hooks\Hooks; | use Admidio\Hooks\Hooks; |
| | |
| | if (realpath($_SERVER['SCRIPT_FILENAME'] ?? '') === __FILE__) { |
| | exit('This page may not be called directly!'); |
| | } |
| |
| Hooks::addFilter('page_headline', function (string $headline): string { | Hooks::addFilter('page_headline', function (string $headline): string { |
| return $headline . ' 👋'; | return $headline . ' 👋'; |
| }); | }, 20, 1, 'hello'); |
| </code> | </code> |
| |
| That is a working plugin. Open **Preferences → Plugins**, switch it on, and every page headline gets | That is a working plugin. Open **Administration → Plugin manager**, switch it on, and every page |
| a wave. | headline gets a wave. |
| |
| Three things are worth taking from this: | Three things are worth taking from this: |
| |
| * **The directory name is the plugin.** ''plugins/hello/'' means the plugin is called ''hello''. There is no ID anywhere else, and renaming the directory renames the plugin. | * **The folder name is the plugin.** ''plugins/hello/'' means the plugin ID is ''hello''. It is the only identity a plugin has: it is used in preference names, in URLs and in the components table. The display name may change, be translated or be shared with another plugin without any consequence. |
| * **''plugin.json'' and ''plugin.php'' are the only required files**, and they always have those names. | * **''plugin.json'' is the only required file.** ''plugin.php'' is optional: a plugin only needs it if it has code to run on every request, such as registering a hook. A plugin that only brings a page (''modules/index.php''), language files or settings consists of ''plugin.json'' and those files. |
| * **''plugin.php'' registers things and returns nothing.** There is no plugin class to extend, no interface to implement and no lifecycle to fill in. | * **''plugin.php'' registers things and returns nothing.** There is no plugin class to extend, no interface to implement and no lifecycle to fill in. |
| |
| ===== A full-featured plugin ===== | ===== Folder structure ===== |
| |
| Everything a plugin may contain. Only the first two entries are required — take what you need. | Everything a plugin may contain. Only ''plugin.json'' is required; take what you need. |
| |
| <code> | <code> |
| plugins/my-plugin/ | plugins/my-plugin/ |
| ├── plugin.json the manifest: name, version, requirements, settings | ├── plugin.json the manifest: name, version, requirements, settings |
| ├── plugin.php the entry file, included once when the plugin is loaded | ├── plugin.php the entry file, included once when the plugin is loaded (optional) |
| | ├── cli.php registers command line tasks of the plugin |
| ├── README.md for whoever finds your plugin | ├── README.md for whoever finds your plugin |
| | ├── composer.json, composer.lock third-party libraries, see "Third-party libraries" |
| │ | │ |
| ├── modules/ pages, each an ordinary Admidio page | ├── modules/ pages, each an ordinary Admidio page |
| │ ├── index.php plugins/my-plugin/modules/index.php | │ ├── index.php the start page; the menu entry of the plugin leads here |
| │ └── edit.php | │ └── edit.php |
| │ | │ |
| │ │ └── Item.php extends Admidio\Infrastructure\Entity\Entity | │ │ └── Item.php extends Admidio\Infrastructure\Entity\Entity |
| │ ├── Service/ | │ ├── Service/ |
| │ │ └── ItemService.php the save and delete logic of a form | │ │ ├── ItemService.php the save and delete logic of a form |
| | │ │ └── UpdateStepsCode.php PHP methods called by the update scripts |
| │ └── Presenter/ | │ └── Presenter/ |
| │ └── ItemPresenter.php builds the pages and forms | │ └── ItemPresenter.php builds the pages and forms |
| │ └── plugin.my-plugin.tpl the overview widget | │ └── plugin.my-plugin.tpl the overview widget |
| │ | │ |
| ├── assets/ css, js, images shipped with the plugin | ├── assets/ css, js and images shipped with the plugin |
| │ └── my-plugin.css | │ └── my-plugin.css |
| │ | │ |
| ├── tests/ run together with Admidio's own suite | ├── db_scripts/ database and lifecycle scripts, see "Database and lifecycle scripts" |
| │ ├── Unit/ | │ ├── install.sql creates the newest schema |
| │ │ └── ManifestTest.php | │ ├── install.php setup that SQL cannot do |
| │ └── Integration/ | │ ├── update_1_1.xml the changes of version 1.1 |
| │ └── ItemServiceTest.php | │ ├── uninstall.php cleanup that SQL cannot do |
| | │ └── uninstall.sql drops the tables |
| │ | │ |
| └── db_scripts/ your own database tables | └── tests/ run together with Admidio's own suite, not distributed |
| ├── install.sql runs when the plugin is installed | ├── Unit/ |
| ├── uninstall.sql runs when it is removed | └── Integration/ |
| └── update_1_1.xml upgrades an installed plugin to 1.1 | |
| </code> | </code> |
| |
| The directory names are fixed — Admidio looks for ''modules'', ''languages'', ''templates'', | None of the subfolders has to exist and **none of them has to be declared** in the manifest. The |
| ''assets'' and ''db_scripts'' by name. Inside ''src/'' you may arrange things however you like; the | names ''modules'', ''languages'', ''templates'', ''assets'' and ''db_scripts'' are fixed: Admidio looks |
| example follows Admidio's own split into entities, services and presenters. | for them by name. Inside ''src/'' you may arrange things however you like; the example follows |
| | Admidio's own split into entities, services and presenters. |
| | |
| | ==== Naming conventions ==== |
| | |
| | * The **plugin ID**, the folder name, consists of letters, digits and single hyphens or underscores (''my-plugin'', ''search_member''). Use lower case letters and hyphens for a new plugin. Upper case letters are only accepted because some plugins of Admidio 5 used them. |
| | * Two IDs that only differ in case, hyphens or underscores (''my-plugin'' and ''My_Plugin'') would share their preferences, so Admidio refuses to load either of them. |
| | * Other folder and file names with several words use **kebab-case** (''my-plugin.list.tpl''). |
| | * Class files below the autoload folder use **UpperCamelCase** and contain no ''-'' or ''_''. |
| |
| ===== How a plugin is found and loaded ===== | ===== How a plugin is found and loaded ===== |
| |
| Admidio reads ''plugins/*/plugin.json'' on every request. That is a directory scan and a | Admidio reads ''plugins/*/plugin.json'' on every request. That is a folder scan and a |
| ''json_decode'', nothing more — **discovery never runs plugin code**. A plugin with a broken manifest | ''json_decode'', nothing more: **discovery never runs plugin code**. A plugin with a broken manifest is |
| is reported in the plugin manager and skipped; it can never break the rest of Admidio. | listed in the plugin manager and can be removed there, but it is never loaded and cannot be installed. |
| |
| ''plugin.php'' is included only for a plugin that is **installed and enabled for the current | A plugin is only loaded if it is **installed and enabled for the current organization**, once, after |
| organization**, once, after the database, the session and the current user are ready. So the entry | the database, the session and the current user are ready. So the entry file may call any Admidio API. |
| file may call any Admidio API. | Loading one plugin means four things and nothing else: |
| |
| A plugin that throws while loading is logged and skipped. The rest of the request continues. | - its ''autoload'' mappings become resolvable classes, |
| | - its ''languages/'' folder is added to the language search path, |
| | - its ''settings'' and the preference that enables it are registered as ordinary Admidio preferences, |
| | - its ''plugin.php'' is included once, if the plugin has one. |
| |
| ==== The states a plugin can be in ==== | The entry file is included in a scope of its own, so a variable it assigns cannot collide with |
| | anything else. Keep top-level code cheap: it runs in **every request** of every organization the |
| | plugin is enabled for. |
| |
| ^ State ^ Meaning ^ | ==== When a plugin fails ==== |
| | Available | The files are there. The plugin does nothing. | | |
| | Enabled | Switched on for this organization. | | * **An exception while loading** is logged, the plugin is skipped, and the rest of the request continues. A broken extension must not be able to take the whole installation down, because then it could not be disabled any more. |
| | Update available | The files are newer than the database, or the plugin store publishes a newer version. | | * **A fatal error while loading** (a parse error, a class whose method signature no longer matches the Admidio class it extends, ...) ends the request. The **crash guard** records the crash in ''adm_my_files/plugins-failed.json'', and from the next request on Admidio does not load the plugin, nor any plugin that requires it. Administrators see the crash and can **Try again**. A record only applies to the plugin version and the Admidio version it was recorded with, so updating either gives the plugin a new chance. After all plugins are loaded, only errors in the code itself (parse and compile errors in a file of the plugin) count as a crash, never what a visitor sends with a request. |
| | Faulty | The manifest is missing or malformed, or a requirement is not met. | | * **A failing hook callback** fails the operation it extends. That is deliberate: an operation can be aborted, and leaving it half done is worse. A failing plugin **load** is only reported, because a request that never reaches the plugin manager cannot be repaired. |
| | Files missing | Admidio still has the plugin in its database, but the directory is gone. | | |
| | ==== Installed and enabled ==== |
| | |
| | A plugin has **two independent states**: |
| | |
| | * **installed** is global, because the database schema of a plugin is global. It is a row in the components table with ''com_type = PLUGIN'' and ''com_name_intern = <plugin ID>''. |
| | * **enabled** is per organization, because one Admidio installation may serve several organizations that do not want the same extensions. It is the preference ''plugin_<id>_enabled''. |
| | |
| | The plugin manager groups the plugins by these states: |
| | |
| | ^ State ^ Constant ^ Meaning ^ |
| | | Enabled | ''enabled'' | Installed and enabled for the current organization. | |
| | | Update available | ''update'' | Installed, but the files declare a newer version than the database. The plugin is not loaded until it is updated. | |
| | | Available extensions | ''available'', ''disabled'' | The files are there, but the plugin is not installed, or not enabled for this organization. | |
| | | Plugins whose files are missing | ''orphaned'' | Installed in the database, but the folder is gone. | |
| | | Incompatible plugins | ''broken'' | The manifest is missing or malformed, or a requirement is not met. | |
| | |
| | The operations are deliberately separate: |
| | |
| | ^ Operation ^ Scope ^ What it does ^ |
| | | install | installation | runs the install scripts, creates the component record, seeds the preferences in every organization, publishes the pages, adds the menu entry to ''modules/index.php'' and links the menu entries of the plugin's own | |
| | | update | installation | runs ''db_scripts/update_x_y.xml'' up to the new version, fetching newer files from the plugin store first where it publishes them | |
| | | enable | organization | sets the preference that loads the plugin and fires ''plugin_enabled''; installs it first if that has not happened yet | |
| | | disable | organization | clears that preference and fires ''plugin_disabled''; nothing else | |
| | | remove | installation | runs the uninstall scripts, removes the pages, the menu entries, the preferences, the component record and the files | |
| | |
| | **Disabling is always safe and reversible.** Installing from the plugin directory or from an archive |
| | installs and enables the plugin in one step, so the administrator has one decision to make, not two. |
| | Removing is the only destructive operation: it takes the plugin away from **every** organization at |
| | once. A plugin of the Admidio distribution cannot be removed, because the next Admidio update would put |
| | its files back and quietly undo the decision. |
| | |
| | ==== Reacting to enabling and disabling ==== |
| | |
| | The install scripts run once for the whole installation. What your plugin has to prepare **per |
| | organization**, such as a category, a role or a scheduled task, belongs in a callback of the action |
| | ''plugin_enabled''; ''plugin_disabled'' is the place to stop what only runs while the plugin is |
| | enabled. Both actions are passed the plugin, and the current organization is the one whose decision |
| | changed. Every plugin receives them, so check the ID: |
| | |
| | <code php plugin.php> |
| | Hooks::addAction('plugin_enabled', function (Plugin $plugin): void { |
| | if ($plugin->id === 'my-plugin') { |
| | MyService::prepareOrganization(); |
| | } |
| | }, Hooks::DEFAULT_PRIORITY, null, 'my-plugin'); |
| | </code> |
| |
| Installing is not a separate step. The first organization that switches a plugin on is what prepares | * The actions fire only when the state really changes: enabling a plugin that is already enabled fires nothing. |
| it; every other organization only flips its own switch. | * A plugin that was not loaded in the request is loaded before ''plugin_enabled'', so it receives the action about itself, also right after its installation. A plugin that is kept out after a crash or waits for its update is not loaded and does not receive it. |
| | * A callback that throws refuses the change: the preference keeps its old value and the administrator sees the error. |
| | * Disabling keeps everything. Do not delete data in ''plugin_disabled'': the plugin may be enabled again. Data that has to go when the plugin is removed belongs in ''uninstall.sql'' or ''uninstall.php''. |
| | * Write the callback so that it copes with what an earlier enabling left behind, because an organization may enable the plugin, disable it and enable it again. |
| |
| ===== The manifest ===== | ===== The manifest ===== |
| <code javascript plugin.json> | <code javascript plugin.json> |
| { | { |
| | "id": "my-plugin", |
| "name": "PLG_MY_PLUGIN_NAME", | "name": "PLG_MY_PLUGIN_NAME", |
| "description": "PLG_MY_PLUGIN_DESCRIPTION", | "description": "PLG_MY_PLUGIN_DESCRIPTION", |
| "url": "https://example.org/my-plugin", | "url": "https://example.org/my-plugin", |
| "icon": "bi-emoji-smile", | "icon": "bi-emoji-smile", |
| | "menuParent": "extensions", |
| "requires": { | "requires": { |
| "admidio": ">=5.1 <6.0", | "admidio": ">=6.0", |
| "php": ">=8.2", | "php": ">=8.2", |
| "extensions": ["json"], | "extensions": ["json"], |
| </code> | </code> |
| |
| Only ''name'' and ''version'' are required. | ^ Key ^ Required ^ Description ^ |
| | | ''name'' | yes | Display name. May be a language key. | |
| | | ''version'' | yes | Version of the files, compared with the installed version to detect an update. See below. | |
| | | ''id'' | | The plugin ID once more. If present, it must equal the folder name. In an archive it names the plugin, whatever the folder in the archive is called. **Recommended for every plugin released from a repository.** | |
| | | ''description'' | | Short description shown in the plugin manager. May be a language key. | |
| | | ''author'' | | The author of the plugin. | |
| | | ''url'' | | A web page of the plugin, e.g. its page in the plugin directory. | |
| | | ''icon'' | | Bootstrap icon name, e.g. ''bi-cake2''. Default ''bi-puzzle-fill''. | |
| | | ''menu'' | | ''false'' suppresses the menu entry. A plugin without ''modules/index.php'' never gets one anyway. | |
| | | ''menuParent'' | | Below which menu node the entry is created: ''extensions'' (default), ''administration'' for a tool for administrators, ''modules'' for a module of its own. Any other value makes the manifest broken. | |
| | | ''requires'' | | Version constraints and dependencies, see below. | |
| | | ''autoload'' | | PSR-4 mappings, as namespace prefix => folder inside the plugin. | |
| | | ''preferences'' | | Where the settings panel of the plugin appears: ''section'' and ''sequence''. | |
| | | ''settings'' | | The preferences the plugin owns. | |
| | |
| | A manifest may carry further keys of its own; they are kept and readable through ''$plugin->manifest''. |
| | |
| | ==== version ==== |
| | |
| | The version is written ''X'', ''X.Y'' or ''X.Y.Z'', optionally followed by a prerelease |
| | ''-(dev|alpha|beta|rc).N'', e.g. ''2.0.0-beta.1'', at most 32 characters. A prerelease is older than |
| | the release it leads up to (''dev < alpha < beta < rc < release''), and the plugin catalogue must use the |
| | same string. Missing components count as zero when Admidio chooses the update scripts. A manifest |
| | without a valid version makes the plugin broken. |
| |
| ==== Language keys instead of text ==== | ==== Language keys instead of text ==== |
| |
| Wherever this page says a value **may be a language key**, you can write either a piece of text or | Wherever this page says a value **may be a language key**, you can write either text or the name of a |
| the name of a string from a language file. Admidio decides by looking at the value itself. | string from a language file. Admidio decides by looking at the value: |
| |
| A value counts as a language key when it is **three upper case letters, an underscore, and then upper | A value counts as a language key when it is **three upper case letters, an underscore, and then upper |
| case letters, digits and single underscores** — ''PLG_MY_PLUGIN_NAME''. Anything else is shown | case letters, digits and single underscores**, like ''PLG_MY_PLUGIN_NAME''. Anything else is shown |
| exactly as written: | exactly as written: |
| |
| | ''"SYS_SAVE"'' | looked up in Admidio's own files | | | ''"SYS_SAVE"'' | looked up in Admidio's own files | |
| | ''"My plugin"'' | shown as it is | | | ''"My plugin"'' | shown as it is | |
| | ''"MY_PLUGIN_NAME"'' | shown as it is — only **two** letters before the first underscore | | | ''"MY_PLUGIN_NAME"'' | shown as it is: only **two** letters before the first underscore | |
| | ''"PLUGIN_NAME"'' | shown as it is — six letters before the first underscore | | | ''"PLUGIN_NAME"'' | shown as it is: six letters before the first underscore | |
| |
| So a plugin for one language can simply write its text into the manifest, and a plugin that wants to | So a plugin for one language can write its text into the manifest, and a plugin that wants to be |
| be translated puts a key there and defines it in ''languages/en.xml'', ''languages/de.xml'' and so | translated puts a key there and defines it in ''languages/en.xml'', ''languages/de.xml'' and so on. The |
| on. The same applies to the ''label'' and ''description'' of a setting and to the names of the values | same applies to the ''label'' and ''description'' of a setting and to the names of the values of an |
| of an ''enum''. | ''enum''. Use ''PLG_'' followed by your plugin name: a key such as ''MYPLUGIN_NAME'' is never looked |
| | up and appears in the interface as raw text. |
| **Important:** The three-letter prefix is not a convention, it is the rule. A key such as ''MYPLUGIN_NAME'' is never | |
| looked up and appears in the interface as raw text. Use ''PLG_'' followed by your plugin name. | |
| |
| ==== requires ==== | ==== requires ==== |
| |
| * ''admidio'' and ''php'' take a space separated list of terms that must **all** match, e.g. ''">=5.1 <6.0"''. A term without an operator means ''>=''. | A constraint is a **space separated list of terms that all have to match**, e.g. ''>=6.0 <7.0''. A term |
| * ''extensions'' are PHP extensions. | is an operator (''>='', ''>'', ''<='', ''<'', ''='', ''!='') followed by a version; a term without an |
| * ''plugins'' are other plugins, as ID → version constraint. | operator means ''>=''. |
| * ''modules'' are Admidio modules the plugin needs — ''events'', ''photos'', ''documents-files'' and so on. A **switched-off module does not make the plugin faulty**: the plugin manager says so beside the plugin, and it starts working again when the module is switched on. | |
| |
| An unmet ''admidio'', ''php'', ''extensions'' or ''plugins'' requirement makes the plugin faulty and | * ''admidio'' and ''php'' take a constraint. |
| it cannot be used. | * ''extensions'' lists PHP extensions. |
| | * ''plugins'' maps other plugin IDs to a constraint. The other plugin has to be installed and enabled. |
| | * ''modules'' lists Admidio modules the plugin needs, named the way Admidio names the component (''events'', ''photos'', ''documents-files'', ''messages''), not the way its preference is spelled. |
| | |
| | An unmet ''admidio'', ''php'', ''extensions'' or ''plugins'' requirement makes the plugin broken: it |
| | cannot be installed. ''modules'' is deliberately **not** a requirement. A switched-off module is |
| | neither the plugin's fault nor permanent, so the plugin manager tells the administrator about it and |
| | the plugin starts working again when the module is switched on. |
| | |
| | ==== autoload ==== |
| | |
| | <code javascript>"autoload": { "AdmidioPlugin\\MyPlugin\\": "src/" }</code> |
| | |
| | The prefix **must not start with ''Admidio\''**, which belongs to the core and could otherwise be |
| | shadowed, and the folder has to stay inside the plugin. Both are checked when the manifest is read; a |
| | violation makes the plugin broken. No ''composer dump-autoload'' is needed. |
| | |
| | ==== preferences ==== |
| | |
| | <code javascript>"preferences": { "section": "overview_extensions", "sequence": 20 }</code> |
| | |
| | ''section'' names one of the tabs of the preferences: ''system'', ''login_security'', |
| | ''user_management'', ''communication'', ''content_management'', ''overview_extensions'' or |
| | ''extensions''. ''sequence'' places the panel inside it. A plugin is not restricted to the last two: a |
| | module that used to be part of the core keeps its own tab once it becomes a plugin. A plugin that names |
| | no section, or one that no longer exists, lands in ''extensions''. |
| |
| ==== settings ==== | ==== settings ==== |
| |
| Every setting becomes an ordinary Admidio preference: registered when the plugin loads, given a row | Every setting becomes an **ordinary Admidio preference**: registered when the plugin is loaded, given a |
| in every organization when it is installed, removed when the plugin is removed. It is validated and | row in every organization when it is installed, removed when it is removed. It is validated and written |
| written to the change history like any other preference. | to the change history like any other preference. A setting without a ''default'' is ignored. |
| |
| <code javascript> | <code javascript> |
| "settings": { | "settings": { |
| "my_count": { "type": "integer", "default": 3, "min": 1, "max": 20, "step": 1, | "my_plugin_count": { "type": "integer", "default": 3, "min": 1, "max": 20, "step": 1, |
| "label": "PLG_MY_PLUGIN_COUNT" }, | "label": "PLG_MY_PLUGIN_COUNT" }, |
| "my_shout": { "type": "boolean", "default": false, "label": "PLG_MY_PLUGIN_SHOUT" }, | "my_plugin_shout": { "type": "boolean", "default": false, "label": "PLG_MY_PLUGIN_SHOUT" }, |
| "my_order": { "type": "enum", "default": "ASC", | "my_plugin_order": { "type": "enum", "default": "ASC", |
| "values": { "ASC": "PLG_MY_PLUGIN_ASCENDING", "DESC": "PLG_MY_PLUGIN_DESCENDING" }, | "values": { "ASC": "PLG_MY_PLUGIN_ASCENDING", "DESC": "PLG_MY_PLUGIN_DESCENDING" }, |
| "label": "PLG_MY_PLUGIN_ORDER" }, | "label": "PLG_MY_PLUGIN_ORDER" }, |
| "my_names": { "type": "array", "default": [], "label": "PLG_MY_PLUGIN_NAMES" } | "my_plugin_names": { "type": "array", "default": [], "label": "PLG_MY_PLUGIN_NAMES" }, |
| | "my_plugin_roles": { "type": "roles", "default": [], "label": "PLG_MY_PLUGIN_ROLES" } |
| } | } |
| </code> | </code> |
| |
| * Types are ''string'', ''boolean'', ''integer'', ''enum'' and ''array''. | * Types are ''string'', ''boolean'', ''integer'', ''enum'', ''array'' and ''roles''. |
| * An ''integer'' may bound its input with ''min'', ''max'' and ''step''. | * An ''integer'' may bound the input field with ''min'', ''max'' and ''step''. The value is stored as an integer either way. |
| * An ''enum'' may just list its values (''["ASC", "DESC"]'') or name them, as above. Names may be language keys. | * An ''enum'' may just list its values (''["ASC", "DESC"]'') or name them, as above. Names may be language keys. |
| * **A setting without a ''label'' is not shown in the generated form.** Use that for a preference the plugin owns but nobody should type into — the position of an overview widget, for example. | * A ''roles'' setting is a selection of roles of the organization, edited as a multi-select and read as a list of role IDs. An empty list means that no role was chosen, which a plugin usually reads as "no restriction". |
| | * **A setting without a ''label'' is not shown in the generated form.** Use that for a preference the plugin owns but nobody should type into, the position of an overview widget, for example. |
| |
| Admidio builds the settings form from this. You only write a preferences panel of your own when you | Admidio builds the settings form from this, both in the preferences and in the settings dialog of the |
| need something the manifest cannot express, such as a role selection. | plugin manager. You only write a preferences panel of your own when you need something the manifest |
| | cannot express. |
| | |
| | Read the settings through the plugin, not through ''$gSettingsManager'': |
| |
| **Tip:** Read settings through the plugin, not through ''$gSettingsManager'': | |
| <code php>$values = PluginRegistry::get('my-plugin')->getSettingValues();</code> | <code php>$values = PluginRegistry::get('my-plugin')->getSettingValues();</code> |
| A setting whose row does not exist yet — a new setting in a new version, before the update ran — | |
| answers the default from the manifest instead of throwing. | |
| |
| ==== preferences ==== | Each value is cast to its declared type. A setting whose row does not exist yet, a new setting in a new |
| | version before the update ran, answers its default instead of throwing. |
| |
| Where the settings of the plugin appear. ''section'' is one of ''system'', ''login_security'', | Three preference names are conventions the core understands. In ''<id>'' the hyphens of the plugin ID |
| ''user_management'', ''communication'', ''content_management'', ''overview_extensions'' or | are replaced by underscores: |
| ''extensions'', and ''sequence'' places the panel inside that tab. A plugin that names nothing lands | |
| in **Extensions**. | ^ Preference ^ Meaning ^ |
| | | ''plugin_<id>_enabled'' | Registered by the core for every installed plugin. It enables the plugin for one organization; a plugin does not declare it. | |
| | | ''<id>_plugin_enabled'' | Who may see the plugin: ''0'' nobody, ''1'' everybody, ''2'' only logged-in users. Declare it if your plugin follows the convention. | |
| | | ''<id>_overview_sequence'' | Position of the overview widget on the overview page. | |
| | |
| | **Never rename a setting** in a new version: the stored row is keyed by the name, and nothing migrates |
| | it, so every administrator would lose that setting. |
| | |
| | ===== The entry file ===== |
| | |
| | ''plugin.php'' is **optional**. A plugin needs it only if it has code to run on every request: hooks, |
| | an overview widget, a preferences panel of its own. A plugin that only brings pages, language files, |
| | settings or database scripts leaves it out. |
| | |
| | The entry file registers what the plugin contributes and returns nothing. It runs inside the fully |
| | initialized Admidio request, so it can call any public Admidio API. Normally it registers hooks: |
| | |
| | <code php plugin.php> |
| | <?php |
| | use Admidio\Hooks\Hooks; |
| | use AdmidioPlugin\HelloWorld\Greeting; |
| | |
| | /* |
| | * This file is included by the plugin loader and is never an entry point of its own. Without the |
| | * Admidio bootstrap it could do nothing anyway; the guard only turns a PHP error into a message. |
| | */ |
| | if (realpath($_SERVER['SCRIPT_FILENAME'] ?? '') === __FILE__) { |
| | exit('This page may not be called directly!'); |
| | } |
| | |
| | Hooks::addFilter('page_headline', array(Greeting::class, 'decorateHeadline'), 20, 2, 'hello-world'); |
| | </code> |
| | |
| | A plugin with more to announce puts that into a class of its own and calls it from the entry file, as |
| | the built-in plugins do: |
| | |
| | <code php> |
| | use AdmidioPlugin\Birthday\Birthday; |
| | |
| | Birthday::register(); |
| | </code> |
| | |
| | Installing a plugin must not change what the installation looks like. If a hook changes what the core |
| | produces, guard it with a setting that is off by default, as the example plugin does. |
| |
| ===== Hooks ===== | ===== Hooks ===== |
| |
| Hooks are how a plugin reaches into Admidio without changing it. An **action** is told that something | Hooks are how a plugin reaches into Admidio without changing it. ''Admidio\Hooks\Hooks'' offers three |
| happened; a **filter** is given a value and returns it, changed or not. | primitives: |
| | |
| | ^ Primitive ^ Purpose ^ Register ^ Dispatch ^ |
| | | **Action** | Notify that something is happening or has happened. Every callback is called, return values are ignored. | ''Hooks::addAction()'' | ''Hooks::doAction()'' | |
| | | **Filter** | Transform a value. Every callback receives the result of the previous one. | ''Hooks::addFilter()'' | ''Hooks::applyFilters()'' | |
| | | **Resolver** | Ask for one answer. Callbacks are asked in priority order until one returns something other than ''null''. | ''Hooks::addResolver()'' | ''Hooks::resolve()'' | |
| |
| <code php> | <code php> |
| Hooks::addFilter('page_headline', array(Greeting::class, 'decorate'), 100, 2, 'my-plugin'); | Hooks::addFilter('page_headline', array(Greeting::class, 'decorate'), 100, 2, 'my-plugin'); |
| Hooks::addAction('user_created', array(MyPlugin::class, 'onUserCreated'), 100, 1, 'my-plugin'); | Hooks::addAction('user_created', array(MyPlugin::class, 'onUserCreated'), 100, 1, 'my-plugin'); |
| | Hooks::addResolver('translation_missing', array(MyPlugin::class, 'translate'), 100, null, 'my-plugin'); |
| </code> | </code> |
| |
| The arguments are the hook name, your callback, a priority, how many arguments the callback accepts, | The arguments are the hook name, your callback, a priority, how many arguments the callback accepts, |
| and — **for a plugin, always** — your plugin ID, so that Admidio can attribute a failing callback to | and an ID. A lower priority runs earlier; registrations of the same priority run in registration order. |
| your plugin. | The ID is unique within one hook, so registering the same ID again replaces the earlier registration. |
| | **For a plugin, always pass your plugin ID**, so that Admidio can attribute a failing callback to |
| | your plugin. A callback's exception is logged and rethrown. |
| |
| ==== The hooks a plugin reaches for most often ==== | ==== The hooks a plugin reaches for most often ==== |
| |
| ^ Hook ^ Kind ^ What it is for ^ | ^ Hook ^ Kind ^ What it is for ^ |
| | ''overview_widgets'' | filter | Put a card on the overview page. | | | ''overview_widgets'' | filter | Put a card on the overview page, see [[#an_overview_widget|An overview widget]]. | |
| | ''preferences_panels'' | filter | Add a settings panel of your own. | | | ''preferences_panels'' | filter | Add a settings panel of your own. | |
| | ''page_headline'' | filter | Change the headline of a page. | | | ''page_headline'', ''page_title'' | filter | Change the headline or the title of a page. | |
| | ''page_title'' | filter | Change the title of a page. | | | ''page_before_render'' | action | The page is about to be rendered: add CSS or JavaScript. | |
| | ''page_before_render'' | action | The page is about to be rendered — add CSS or JavaScript. | | | ''page_header_items'' | filter | Add a button or menu to the header bar. | |
| | | ''page_user_menu_items'' | filter | Add an entry to the menu of the logged-in user. | |
| | | ''page_notices'' | filter | Show a notice at the top of every page. | |
| | | ''list_row_actions'' | filter | Add, hide, reorder or change the action icons of a row in any list. | |
| | ''form_built'' | filter | Change a form Admidio has just assembled. | | | ''form_built'' | filter | Change a form Admidio has just assembled. | |
| | ''component_visible'' | filter | Decide whether a module or plugin is visible. | | | ''component_visible'', ''component_administrable'' | filter | Decide whether a module or plugin is visible, or may be administrated by the current user. | |
| | ''component_administrable'' | filter | Decide whether the current user may administrate it. | | |
| | ''translation_text'' | filter | Supply or override a translated string. | | | ''translation_text'' | filter | Supply or override a translated string. | |
| | ''user_created'' | action | A user was created. | | | ''user_created'', ''user_changes_cumulated'' | action | A user was created; the changes to a user, collected into one event. | |
| | ''user_changes_cumulated'' | action | The changes to a user, collected into one event. | | |
| | ''email_recipients'' | filter | Change the recipients of an email. | | | ''email_recipients'' | filter | Change the recipients of an email. | |
| | | ''plugin_removal_warnings'' | filter | Tell the administrator what removing your plugin leaves behind, see [[#removal|Removal]]. | |
| | ''plugins_loaded'' | action | Every plugin has been loaded. | | | ''plugins_loaded'' | action | Every plugin has been loaded. | |
| | | ''plugin_enabled'', ''plugin_disabled'' | action | A plugin was enabled or disabled in the current organization, see [[#reacting_to_enabling_and_disabling|Reacting to enabling and disabling]]. | |
| |
| That is a selection, not the list. | That is a selection, not the list: |
| |
| * [[en:entwickler:hooks:catalogue|**The full hooks catalogue**]] — every hook, with its arguments and when it fires. | * [[en:entwickler:hooks:catalogue|The hooks catalogue]]: every hook, with its arguments and when it fires. |
| * [[en:entwickler:hooks|Hooks — the developer guide]] — the three primitives, priorities, vetoing an operation, and the engine API. | * [[en:entwickler:hooks|Hooks: the developer guide]]: the three primitives, priorities, vetoing an operation and the engine API. |
| |
| A failing hook callback fails the operation it extends — that is deliberate, because an operation can | |
| be aborted. A failing plugin **load** is only reported and skipped, because a request that never | |
| reaches the plugin manager cannot be repaired. | |
| ===== Growing a plugin ===== | ===== Growing a plugin ===== |
| |
| ==== Your own classes ==== | ==== Your own classes ==== |
| |
| Declare a namespace and a directory: | Declare a namespace and a folder in ''autoload'' and put the classes there: |
| | |
| <code javascript>"autoload": { "AdmidioPlugin\\MyPlugin\\": "src/" }</code> | |
| |
| <code php src/Greeting.php> | <code php src/Greeting.php> |
| } | } |
| </code> | </code> |
| |
| The prefix **must not start with ''Admidio\''** — that belongs to the core — and the directory has to | |
| stay inside the plugin. No ''composer dump-autoload'' is needed. | |
| |
| ==== Language files ==== | ==== Language files ==== |
| </code> | </code> |
| |
| The directory is added to the language search path when the plugin loads, so ''$gL10n->get()'' finds | The folder is added to the language search path when the plugin is loaded, so ''$gL10n->get()'' finds |
| your keys like any other. Prefix them with ''PLG_'' and your plugin name so they cannot collide. | your keys like any other. Prefix them with ''PLG_'' and your plugin name so they cannot collide. |
| | Language strings carry no HTML: write plain text and use ''\n\n'' for a paragraph break. |
| **Note:** Language strings carry no HTML. Write plain text; use ''\n\n'' for a paragraph break. | |
| |
| * [[en:entwickler:how_to_make_your_plugin_translatable|How to make your plugin translatable]] | * [[en:entwickler:how_to_make_your_plugin_translatable|How to make your plugin translatable]] |
| * [[en:entwickler:mehrsprachigkeit|Multilingualism in Admidio]] | * [[en:entwickler:mehrsprachigkeit|Multilingualism in Admidio]] |
| |
| ==== A page ==== | ==== Pages ==== |
| |
| A page is an ordinary Admidio page in ''modules/'' inside your plugin: | A page is an ordinary Admidio page in ''modules/'': |
| |
| <code php modules/list.php> | <code php modules/index.php> |
| <?php | <?php |
| require_once(__DIR__ . '/../../../system/common.php'); | use Admidio\Infrastructure\Plugins\PluginRegistry; |
| | use Admidio\UI\Presenter\PagePresenter; |
| |
| $page = new PagePresenter('adm_my_plugin'); | try { |
| $page->setHeadline($gL10n->get('PLG_MY_PLUGIN_NAME')); | require_once(__DIR__ . '/../../../system/common.php'); |
| // ... admFuncVariableIsValid(), FormPresenter, services, entities as in any module | |
| $page->show(); | $plugin = PluginRegistry::get('my-plugin'); |
| | $page = PagePresenter::withHtmlIDAndHeadline('adm_my_plugin', $gL10n->get('PLG_MY_PLUGIN_NAME')); |
| | $gNavigation->addStartUrl(CURRENT_URL, $page->getHeadline(), $plugin->icon); |
| | // admFuncVariableIsValid(), FormPresenter, services and entities as in any module |
| | $page->show(); |
| | } catch (Throwable $e) { |
| | handleException($e); |
| | } |
| </code> | </code> |
| |
| It is always reachable at ''plugins/my-plugin/modules/list.php''. When the administrator switches on | Nothing about it is plugin-specific. The bootstrap already refuses a page of a plugin that is not |
| **short web addresses for plugin pages**, the same page is also reachable at the shorter | installed and enabled for the current organization, before your code runs; your page still checks the |
| ''modules/my-plugin/list.php''. | rights of the user, like any module. |
| |
| Because that depends on the installation, **never hardcode either address**. Ask instead: | Only the files **directly below** ''modules/'' are entry points; the folder is not searched |
| | recursively, so what a page includes stays private. Everything else in the plugin (the entry file, |
| | the classes below ''src/'') is refused when it is requested directly. |
| |
| <code php>$url = PluginRegistry::get('my-plugin')->getUrl('list.php');</code> | A page is always reachable at its real location, ''plugins/my-plugin/modules/index.php''. When the |
| | administrator switches on **Short web addresses for plugin pages** (preference ''plugin_module_pages''), |
| | Admidio additionally publishes it at ''modules/my-plugin/index.php''. Admidio has no front controller, |
| | so this writes one small generated file per page into the ''modules'' folder, which a Git-managed or |
| | read-only deployment does not want: it is **off by default**. A generated folder carries a marker file |
| | naming its plugin, and nothing without that marker is ever deleted. |
| | |
| | <WRAP center round tip 80%> |
| | **Never hardcode either address.** Ask the plugin: ''$plugin->getUrl('index.php')''. |
| | </WRAP> |
| | |
| | ==== The menu entry ==== |
| | |
| | ''modules/index.php'' is the **start page** of a plugin. When the plugin is installed, Admidio creates |
| | a menu entry that leads there, below the node its ''menuParent'' names, and removes it again when the |
| | plugin is removed. The entry is only shown in organizations where the plugin is enabled. |
| | |
| | * A plugin **without** ''modules/index.php'' gets no menu entry, even if it has other pages. |
| | * A plugin whose start page is not a destination (the calendar answers one month of itself for its own buttons) says ''"menu": false'' in its manifest. |
| | * A plugin that needs a menu entry for another page, or several entries, creates them itself in ''db_scripts/install.php''. Admidio links them to the plugin, so they behave like the entry to ''modules/index.php'', see [[#a_menu_entry_of_your_own|A menu entry of your own]]. |
| |
| A page of a plugin is an Admidio page like any other, so everything the core pages do applies: | A page of a plugin is an Admidio page like any other, so everything the core pages do applies: |
| |
| * [[en:entwickler:index:forms|Forms — create, validate and save]] | * [[en:entwickler:index:forms|Forms: create, validate and save]] |
| * [[en:entwickler:uebergabevariablen_pruefen|Checking of passed variables]] | * [[en:entwickler:uebergabevariablen_pruefen|Checking of passed variables]] |
| * [[en:entwickler:url_call_with_csrf_token|URL call with CSRF token]] | * [[en:entwickler:url_call_with_csrf_token|URL call with CSRF token]] |
| * [[en:entwickler:navigation_ueber_mehrere_seiten|Navigation across multiple pages]] | * [[en:entwickler:navigation_ueber_mehrere_seiten|Navigation across multiple pages]] |
| * [[en:entwickler:message-klasse_fuer_hinweistexte|The message class for note texts]] | * [[en:entwickler:message-klasse_fuer_hinweistexte|The message class for note texts]] |
| | |
| | ==== Templates and assets ==== |
| | |
| | Put Smarty templates in ''templates/'' and render them through the plugin: |
| | |
| | <code php>return $plugin->renderTemplate($page, 'plugin.my-plugin.tpl', array('greeting' => $greeting));</code> |
| | |
| | A theme overrides a template of a plugin by putting a file of the same name into |
| | ''themes/<theme>/templates/plugins/<plugin ID>/''. Do not use the deprecated ''HtmlPage'' and |
| | ''HtmlTable'' classes. |
| | |
| | CSS, JavaScript and images go into ''assets/''. ''$plugin->getAssetUrl('my-plugin.css')'' answers the |
| | URL of one; it carries the modification time of the file as a version, so browsers load the file again |
| | after an update instead of using their cached copy. |
| |
| ==== An overview widget ==== | ==== An overview widget ==== |
| | |
| | The overview page asks for its cards through the ''overview_widgets'' filter. A plugin that follows the |
| | conventions (one widget, a ''<id>_plugin_enabled'' preference for who may see it and an |
| | ''<id>_overview_sequence'' preference for its position) does not write the hook itself: |
| |
| <code php> | <code php> |
| </code> | </code> |
| |
| The widget is shown according to the preference ''my_plugin_plugin_enabled'', which takes the usual | ^ Option ^ Default ^ |
| values 0 (off), 1 (everybody) and 2 (only registered users). Declare it in your manifest. | | ''name'' | The name of the plugin, translated if it is a language key | |
| | | ''icon'' | The icon of the plugin | |
| | | ''sequencePreference'' | ''<id>_overview_sequence'' | |
| | | ''enabledPreference'' | ''<id>_plugin_enabled'' | |
| | | ''sequence'' | Position of a widget whose preference has no value | |
| |
| ==== Templates ==== | The render callback receives the overview page and the plugin and returns the HTML of the widget, or |
| | an empty string for a widget with nothing to show. ''PluginWidget::render($page, $plugin, $template, |
| | $variables)'' renders a template of the plugin for it. The widget is listed in the overview preferences |
| | even while it is switched off, so it can be switched on again. |
| |
| Put Smarty templates in ''templates/'' and render them through the plugin, so a theme can override | A plugin that needs more control adds the hook itself: |
| them: | |
| |
| <code php> | <code php> |
| return $plugin->renderTemplate($page, 'plugin.my-plugin.tpl', array('greeting' => $greeting)); | Hooks::addFilter(PluginWidget::HOOK, function (array $widgets, PagePresenter $page): array { |
| | global $gValidLogin, $gL10n; |
| | |
| | if (!$gValidLogin) { |
| | return $widgets; // a widget that decides not to appear simply does not add itself |
| | } |
| | |
| | $plugin = PluginRegistry::get('my-plugin'); |
| | $widgets[] = array( |
| | 'id' => $plugin->id, |
| | 'name' => $gL10n->get($plugin->name), |
| | 'sequence' => 20, |
| | 'html' => PluginWidget::render($page, $plugin, 'plugin.my-plugin.tpl', array('rows' => $rows)) |
| | ); |
| | |
| | return $widgets; |
| | }, 20, 2, 'my-plugin'); |
| </code> | </code> |
| |
| ==== Database tables ==== | ==== A preferences panel of your own ==== |
| |
| A plugin that needs its own tables puts them in ''db_scripts/'': | For a plugin whose form is generated from the manifest, the manifest is all there is. A plugin that |
| | builds its form itself, for example with a role selection the manifest cannot express, registers the |
| | callback that builds it: |
| |
| * ''install.sql'' runs when the plugin is installed, | <code php> |
| * ''uninstall.sql'' runs when it is removed, | Hooks::addFilter( |
| * ''update_x_y.xml'' upgrades an installed plugin, in the same format as Admidio's own update scripts. | PluginPanel::HOOK, |
| | static function (array $panels) use ($plugin): array { |
| | global $gL10n; |
| |
| Use ''%PREFIX%'' for the table prefix, one statement per update step, and Admidio's generic SQL — | $panels[] = array( |
| the same rules as for the core. Give tables the usual ''xxx_usr_id_create'', | 'id' => PluginPanel::normalizeId($plugin->id), |
| ''xxx_timestamp_create'', ''xxx_usr_id_change'' and ''xxx_timestamp_change'' columns. | 'title' => $gL10n->get($plugin->name), |
| | 'icon' => $plugin->icon, |
| | 'sequence' => 20, |
| | 'create' => array(MyPreferencesPresenter::class, 'createForm') |
| | ); |
| |
| Read and write your rows through an entity that extends ''Admidio\Infrastructure\Entity\Entity'', so | return $panels; |
| that changes reach the change history. | }, |
| | PluginPanel::DEFAULT_SEQUENCE, |
| | 1, |
| | $plugin->id |
| | ); |
| | </code> |
| | |
| | The panel takes its section and its sequence from the manifest of the plugin it is named after, so only |
| | a plugin that declares **several** panels names a ''section'' here as well. The ''create'' callback |
| | receives the ''PreferencesPresenter'' and returns the HTML of the panel; it is only called for the panel |
| | the administrator opens. The same panel is shown in the settings dialog of the plugin manager. |
| | |
| | ==== The change history ==== |
| | |
| | Changes made through an entity that extends ''Admidio\Infrastructure\Entity\Entity'' reach the change |
| | history. Give your tables the columns ''xxx_usr_id_create'', ''xxx_timestamp_create'', |
| | ''xxx_usr_id_change'' and ''xxx_timestamp_change'' if your entities use Admidio's creation and |
| | modification metadata. |
| | |
| | How your tables appear there (their labels, field names, links and who may see them) is customised |
| | with ''ChangelogService::registerCallback()''. Besides labels and links, a plugin can declare tables |
| | where users only see their own changes (''getOwnChangeTables''), and hide individual entries of a table |
| | from some users with an SQL condition (''getVisibilityRestriction''). Restrictions of several modules all |
| | apply together. |
| |
| * [[en:entwickler:aenderungen_in_der_datenbank_einbauen|Installing changes to the database]] | |
| * [[en:entwickler:tabellenzugriffsklassen|Table access classes and their methods]] | |
| * [[en:entwickler:datenbankzugriffsklasse|The database access class]] | |
| * [[en:entwickler:sql-injektion|Avoiding SQL injection]] | |
| * [[en:entwickler:changelog_implementation|Implementing a change log]] | * [[en:entwickler:changelog_implementation|Implementing a change log]] |
| |
| ==== Command line tasks ==== | ==== Command line tasks ==== |
| |
| Register commands from ''plugin.php''. A plugin owns the command namespace named after its | A plugin owns the command namespace named after its folder, exactly like a module. It registers its |
| directory, so ''my-plugin'' may register ''my-plugin:sync'' and nothing else. | commands in **plugins/<plugin>/cli.php**, which is loaded for every enabled plugin after the plugin |
| | runtime, so its classes, settings and languages are available: |
| |
| * [[en:entwickler:cli|Adding CLI commands to Admidio modules]] — how a command is registered | <code php cli.php> |
| * [[en:2.0:cli:usage|The Admidio command line — usage]] | CliTaskRegistry::register( |
| * [[en:2.0:cli:commands|The command reference]] | 'my-plugin:greet', |
| | 'PLUGINS', |
| | array(Greeting::class, 'cliGreet'), |
| | 'Print the greeting of the plugin.', |
| | 'my-plugin:greet [--name=NAME]' |
| | ); |
| | </code> |
| | |
| | The file only registers metadata and callbacks; the command runs later, after the actor and the |
| | component have been authorized. A plugin cannot replace a command that is already registered, and a |
| | broken ''cli.php'' is reported without taking the rest of the command line down. |
| | |
| | * [[en:entwickler:cli|Adding CLI commands to Admidio modules]] |
| | * [[en:2.0:cli:usage|The Admidio command line: usage]] and [[en:2.0:cli:commands|the command reference]] |
| | |
| | ==== Third-party libraries ==== |
| | |
| | A plugin may use Composer libraries. Commit ''composer.json'' **and** ''composer.lock'' to the plugin |
| | repository, and load the autoloader yourself at the top of ''plugin.php'' (Admidio does not do it for |
| | you): |
| | |
| | <code php>require_once __DIR__ . '/vendor/autoload.php';</code> |
| | |
| | A plugin without ''plugin.php'' does it in the pages that use a library. Do the same in |
| | ''db_scripts/install.php'' or ''uninstall.php'' if they use one. The |
| | [[#releasing_from_github|release workflow]] installs the production dependencies from ''composer.lock'' |
| | and puts ''vendor/'' into the archive. ''admidio plugin:archive'' does **not**: it leaves ''vendor/'' |
| | out. An archive that contains ''vendor/'' is installed with it. |
| | |
| | Keep the libraries few and small. Every plugin's ''vendor/'' is loaded into the same PHP process as |
| | Admidio's own libraries, and two different versions of one library cannot be loaded side by side. |
| | |
| | ===== Database and lifecycle scripts ===== |
| | |
| | A plugin that keeps data of its own puts its scripts in ''db_scripts/''. All of them are optional: |
| | |
| | ^ File ^ When it runs ^ |
| | | ''install.sql'' | When the plugin is installed. Creates the **newest** schema, as ''db.sql'' does for Admidio itself. | |
| | | ''install.php'' | Right after ''install.sql'', for setup that SQL cannot do, such as copying example files into ''adm_my_files''. | |
| | | ''update_x_y.xml'' | When the version in ''plugin.json'' is raised: the changes of version ''x.y''. One file per minor version. | |
| | | ''uninstall.php'' | First when the plugin is removed, while its data, pages and menu entries still exist, for cleanup that SQL cannot do, such as files in ''adm_my_files'' or accounts on another system. | |
| | | ''uninstall.sql'' | When the plugin is removed. Drops its tables. | |
| | |
| | The SQL files hold statements that each end with '';'' at the end of a line. Write ''%PREFIX%'' in |
| | front of every table name (''%PREFIX%_my_plugin_items'') and SQL that works on MySQL, MariaDB and |
| | PostgreSQL. |
| | |
| | ==== Installation ==== |
| | |
| | Installing a plugin runs, in this order: ''install.sql'', ''install.php'', the component record, the |
| | preferences of the plugin in every organization, the published pages, the menu entry to |
| | ''modules/index.php'' if the plugin has that page, and the linking of the menu entries |
| | ''install.php'' created (see [[#a_menu_entry_of_your_own|A menu entry of your own]]). If the |
| | administrator installed it from the plugin directory or from an archive, it is then enabled for the |
| | current organization. |
| | |
| | **The update scripts do not run on a new installation.** Admidio records the version of the plugin |
| | and the last step of its update file, so that a later update only runs what it adds. ''install.sql'' |
| | therefore has to be kept up to date with every update script. |
| | |
| | If ''install.sql'' or ''install.php'' fails, the plugin has no component record yet, so the next |
| | attempt starts over with ''install.sql''. Both have to cope with what an earlier attempt left behind: |
| | use ''CREATE TABLE IF NOT EXISTS'' and check whether seed data exists before you insert it. |
| | |
| | ==== Updates ==== |
| | |
| | When ''version'' in ''plugin.json'' is raised, the update runs the update scripts from the installed |
| | version up to the new one, each step once. A patch release may add steps to the update file of its |
| | minor version; only the new steps run. |
| | |
| | <code xml db_scripts/update_1_1.xml> |
| | <?xml version="1.0" encoding="UTF-8"?> |
| | <update> |
| | <step id="10">ALTER TABLE %PREFIX%_my_plugin_items ADD COLUMN mpi_language varchar(10)</step> |
| | <step id="20" database="pgsql">CREATE INDEX %PREFIX%_idx_mpi_language ON %PREFIX%_my_plugin_items (mpi_language)</step> |
| | <step id="30">UpdateStepsCode::updateStep30FillTheLanguage</step> |
| | <step>stop</step> |
| | </update> |
| | </code> |
| | |
| | * Each step holds one SQL statement or one PHP method call. Give it a positive numeric ''id'' and list the IDs in ascending order. **Never change the IDs of released steps.** |
| | * ''database="mysql"'' (MySQL and MariaDB) or ''database="pgsql"'' limits a step to one database. |
| | * ''error="ignore"'' keeps a failing SQL statement from stopping the update. |
| | * A failing step stops the update. The plugin then waits for its update, and the next attempt resumes at that step. |
| | |
| | ''UpdateStepsCode::methodName'' calls a public static method without arguments. Admidio looks for the |
| | class ''UpdateStepsCode'' in the namespace ''Service\'' below the first prefix of ''autoload''; for |
| | ''"AdmidioPlugin\\MyPlugin\\": "src/"'' that is ''AdmidioPlugin\MyPlugin\Service\UpdateStepsCode'' in |
| | ''src/Service/UpdateStepsCode.php''. Admidio passes the database connection to ''setDatabase()'' |
| | before each call: |
| | |
| | <code php src/Service/UpdateStepsCode.php> |
| | <?php |
| | namespace AdmidioPlugin\MyPlugin\Service; |
| | |
| | use Admidio\Infrastructure\Database; |
| | |
| | final class UpdateStepsCode |
| | { |
| | private static Database $db; |
| | |
| | public static function setDatabase(Database $database): void |
| | { |
| | self::$db = $database; |
| | } |
| | |
| | public static function updateStep30FillTheLanguage(): void |
| | { |
| | self::$db->queryPrepared( |
| | 'UPDATE ' . TABLE_PREFIX . '_my_plugin_items SET mpi_language = ? WHERE mpi_language IS NULL', |
| | array('en') |
| | ); |
| | } |
| | } |
| | </code> |
| | |
| | ==== Taking over a plugin from before Admidio 6.0 ==== |
| | |
| | A plugin may replace a version from before the plugin system: a folder without ''plugin.json'', with |
| | its settings in a ''config.php'', maybe with tables of its own and with a menu entry it inserted itself. |
| | Then the update scripts **do** run, from the first one on, after ''install.sql'', and convert what the |
| | old version left behind. Because ''install.sql'' has run before them, these steps meet a database that |
| | may already be in the newest shape, so a step that changes a table is written with |
| | ''error="ignore"''. |
| | |
| | The settings of the old ''config.php'' are taken over once, by an update step of the plugin: |
| | |
| | <code php> |
| | LegacyConfig::import('birthday', array( |
| | 'plg_show_age' => array('birthday_show_age', 'boolval'), |
| | 'plg_show_zeitraum' => array('birthday_show_past', 'intval') |
| | )); |
| | </code> |
| | |
| | Admidio treats an installation as such a takeover when |
| | |
| | * the plugin directory installs the plugin over a folder without a ''plugin.json'', or |
| | * the plugin manager or ''plugin:install --replace'' replaces such a folder that had a ''config.php'', or |
| | * the update of Admidio to 6.0 converts one of its own plugins, or |
| | * an old ''config.php'' is still in ''adm_plugins/'' below the plugin ID. |
| | |
| | A ''config.php'' beside the ''plugin.json'' is an ordinary file of the plugin and is never taken over. |
| | |
| | ==== Removal ==== |
| | |
| | Removing a plugin runs, in this order: ''uninstall.php'', the removal of the published pages and the |
| | menu entries, ''uninstall.sql'', the removal of the preferences and of the component record, and the |
| | deletion of the folder. It takes the plugin away from every organization and destroys its data. An |
| | administrator who only wants to stop using a plugin disables it instead, which keeps everything. |
| | |
| | If ''uninstall.php'' fails, nothing has been removed yet, and removing the plugin again runs the script |
| | again: write it so that it copes with what an earlier attempt already cleaned up. If it keeps failing, |
| | the administrator may remove the plugin without it; what the script should have cleaned up then stays |
| | behind. A plugin whose files are gone is removed without its scripts. |
| | |
| | If removing your plugin leaves something behind that the administrator should know about, such as |
| | accounts on another system, say so through the ''plugin_removal_warnings'' filter. The warnings are |
| | shown in the confirmation of the removal and never prevent it: |
| | |
| | <code php> |
| | Hooks::addFilter('plugin_removal_warnings', function (array $warnings, Plugin $plugin): array { |
| | if ($plugin->id === 'my-plugin' && MyService::hasRemoteData()) { |
| | $warnings[] = 'The accounts on the remote system are no longer managed.'; |
| | } |
| | return $warnings; |
| | }, 10, 2, 'my-plugin'); |
| | </code> |
| | |
| | ==== What the scripts can use ==== |
| | |
| | ''install.php'', ''uninstall.php'' and the update steps run whether the plugin is enabled in any |
| | organization or not, so they cannot rely on anything ''plugin.php'' registers: **the entry file is not |
| | included for them**. The classes of the plugin (through its ''autoload'' mapping) and its language |
| | files are available. A PHP script sees the plugin as ''$plugin''; Admidio's globals such as ''$gDb'' are |
| | reached with ''global''. It reports a failure by throwing. Like ''plugin.php'', it has to refuse to run |
| | when it is requested directly: |
| | |
| | <code php db_scripts/install.php> |
| | <?php |
| | use Admidio\Infrastructure\Utils\FileSystemUtils; |
| | |
| | if (realpath($_SERVER['SCRIPT_FILENAME'] ?? '') === __FILE__) { |
| | exit('This page may not be called directly!'); |
| | } |
| | |
| | // Copy the example templates. A retry after a failed installation finds them already there |
| | // and keeps them, including anything an administrator has changed since. |
| | $target = ADMIDIO_PATH . FOLDER_DATA . '/my-plugin'; |
| | if (!is_dir($target)) { |
| | FileSystemUtils::copyDirectory($plugin->path . '/examples', $target); |
| | } |
| | </code> |
| | |
| | ==== A menu entry of your own ==== |
| | |
| | Admidio only creates a menu entry for ''modules/index.php''. A plugin that wants an entry for another |
| | page, or several entries, creates them in ''install.php''. Give each entry an **internal name that |
| | starts with your plugin ID and a hyphen**, such as ''my-plugin-list'': |
| | |
| | <code php db_scripts/install.php> |
| | <?php |
| | use Admidio\Menu\Entity\MenuEntry; |
| | |
| | if (realpath($_SERVER['SCRIPT_FILENAME'] ?? '') === __FILE__) { |
| | exit('This page may not be called directly!'); |
| | } |
| | |
| | global $gDb; |
| | |
| | // A retry after a failed installation may find the entry already there. |
| | $exists = $gDb->queryPrepared( |
| | 'SELECT men_id FROM ' . TBL_MENU . ' WHERE men_name_intern = ?', |
| | array('my-plugin-list') |
| | )->fetchColumn(); |
| | |
| | if ($exists === false) { |
| | $parentId = (int)$gDb->queryPrepared( |
| | 'SELECT men_id FROM ' . TBL_MENU . ' WHERE men_name_intern = ?', |
| | array('extensions') // or 'modules' or 'administration' |
| | )->fetchColumn(); |
| | |
| | $menuEntry = new MenuEntry($gDb); |
| | $menuEntry->setValue('men_men_id_parent', $parentId); |
| | $menuEntry->setValue('men_name', 'PLG_MY_PLUGIN_LIST'); |
| | $menuEntry->setValue('men_description', 'PLG_MY_PLUGIN_LIST_DESC'); |
| | $menuEntry->setValue('men_url', FOLDER_PLUGINS . '/my-plugin/modules/list.php'); |
| | $menuEntry->setValue('men_icon', 'bi-list-ul'); |
| | $menuEntry->save(); |
| | |
| | // A new entry gets an internal name derived from men_name when it is first saved, |
| | // so the name of the plugin is set afterwards, as Admidio does for its own entries. |
| | $menuEntry->readDataById((int)$menuEntry->getValue('men_id')); |
| | $menuEntry->setValue('men_name_intern', 'my-plugin-list'); |
| | $menuEntry->save(); |
| | } |
| | </code> |
| | |
| | ''install.php'' runs before the plugin has a component record, so the entry cannot name the plugin |
| | yet. When the installation is complete, Admidio **links every entry whose internal name starts with |
| | the plugin ID and a hyphen**, and that does not belong to anything else yet, to the plugin. From then |
| | on it behaves like the entry to ''modules/index.php''. (An entry named after another plugin whose ID |
| | continues yours, such as ''my-plugin-extra-list'' of the plugin ''my-plugin-extra'', is left to that |
| | plugin.) |
| | |
| | * It is only shown in organizations where the plugin is enabled. |
| | * It is removed together with the plugin; ''uninstall.php'' does not have to. |
| | * An administrator may rename, move or delete it in the menu administration. |
| | |
| | The same holds for an entry an update step creates. Its address is the real location below |
| | ''plugins/'', which always works, also when short addresses for plugin pages are switched on. |
| | |
| | * [[en:entwickler:aenderungen_in_der_datenbank_einbauen|Installing changes to the database]] |
| | * [[en:entwickler:tabellenzugriffsklassen|Table access classes and their methods]] |
| | * [[en:entwickler:datenbankzugriffsklasse|The database access class]] |
| | * [[en:entwickler:sql-injektion|Avoiding SQL injection]] |
| |
| ===== Setting up a development environment ===== | ===== Setting up a development environment ===== |
| |
| You need an Admidio to develop against and a database to test against. They are separate things and | You need an Admidio to develop in and a database to test against. Keep them separate: the test suite |
| it is worth keeping them separate: the test database is dropped and recreated by the test suite. | drops and recreates the test database. |
| |
| ==== An Admidio to develop in ==== | ==== An Admidio to develop in ==== |
| </code> | </code> |
| |
| ''install:check'' reports whether the PHP version, the extensions and the directory permissions are | ''install:check'' reports whether the PHP version, the extensions and the folder permissions are right. |
| right. ''install:run'' asks for anything you leave out, so you can also just run it bare and answer | ''install:run'' asks for anything you leave out. Your plugin then goes into ''plugins/'' and appears in |
| the questions. Your plugin then goes into ''plugins/'' and appears in **Preferences → Plugins**. | **Administration → Plugin manager**. |
| |
| ==== Development-only settings in config.php ==== | ==== Development-only settings in config.php ==== |
| |
| A few settings exist for developing and are not in the shipped ''config_example.php'' by default. Add | A few settings exist for developing and are not in ''config_example.php''. Add them to |
| them to ''adm_my_files/config.php'' by hand: | ''adm_my_files/config.php'' by hand: |
| |
| <code php> | <code php> |
| |
| // Point the plugin store at a catalogue of your own while you work on a plugin. | // Point the plugin store at a catalogue of your own while you work on a plugin. |
| // A relative path is resolved from the Admidio directory, so this also works inside a container. | // A relative path is resolved from the Admidio folder, so this also works inside a container. |
| $gPluginStoreUrl = 'adm_my_files/plugin-store/plugins.json'; | $gPluginStoreUrl = 'adm_my_files/plugin-store/plugins.json'; |
| | |
| | // Also offer prereleases: rc, beta, alpha or dev (default: stable). |
| | $gPluginStoreChannel = 'beta'; |
| </code> | </code> |
| |
| **Important:** ''$gPluginStoreUrl'' **only applies while ''$gDebug'' is on**. That is not a security boundary — | ''$gPluginStoreUrl'' and ''$gPluginStoreChannel'' **only apply while ''$gDebug'' is on**, so a line |
| anybody who can edit ''config.php'' can do anything — but it means a line left over from development | left over from development cannot quietly repoint a production installation's plugin store at a host |
| cannot quietly repoint a production installation's plugin store at a host nobody is watching. | nobody is watching. |
| |
| A local catalogue is an ordinary ''plugins.json'' whose ''download'' names a file inside the | A local catalogue is an ordinary ''plugins.json'' whose ''download'' names a file inside the |
| installation. It does not have to be reachable from a browser: Admidio reads it from disk. | installation. Admidio reads it from disk, so it does not have to be reachable from a browser: |
| |
| <code javascript adm_my_files/plugin-store/plugins.json> | <code javascript adm_my_files/plugin-store/plugins.json> |
| { | { |
| "version": "1.0.0", | "version": "1.0.0", |
| "requires": { "admidio": ">=5.1" }, | "requires": { "admidio": ">=6.0" }, |
| "download": "adm_my_files/plugin-store/my-plugin-1.0.0.zip" | "download": "adm_my_files/plugin-store/my-plugin-1.0.0.zip" |
| } | } |
| </code> | </code> |
| |
| Build the archive with ''./admidio plugin:archive my-plugin --output=adm_my_files/plugin-store'', | Build the archive with ''./admidio plugin:archive my-plugin --output=adm_my_files/plugin-store'', and |
| then **Add plugin** offers it from the store. That is the whole publishing chain, locally. | **Add from plugin directory** offers it. That is the whole publishing chain, locally. |
| |
| ==== Databases in Docker ==== | ==== Databases in Docker ==== |
| The repository ships a compose file with the databases the test suite uses: | The repository ships a compose file with the databases the test suite uses: |
| |
| <code bash> | <code bash>docker-compose -f docker-compose.test.yml up -d</code> |
| docker-compose -f docker-compose.test.yml up -d | |
| </code> | |
| | |
| That gives you MariaDB on ''3306'' and PostgreSQL on ''5432'', both with the database | |
| ''admidio_test'' and the user ''admidio''. Testing a plugin against both is the cheapest way to find | |
| SQL that only works on one of them. | |
| |
| **Note:** If Admidio itself runs in a container, remember that it sees the container network. A host name like | That gives you MariaDB on ''3306'' and PostgreSQL on ''5432'', both with the database ''admidio_test'' |
| ''localhost'' in ''config.php'' means the container, and a path from your host does not exist inside | and the user ''admidio''. Testing a plugin against both is the cheapest way to find SQL that only works |
| it — which is why ''$gPluginStoreUrl'' takes a path relative to the Admidio directory. | on one of them. If Admidio itself runs in a container, ''localhost'' in ''config.php'' means the |
| | container, and a path on your computer does not exist inside it. |
| |
| * [[en:entwickler:testumgebung_einrichten|Setting up a test environment]] | * [[en:entwickler:testumgebung_einrichten|Setting up a test environment]] |
| ===== Writing tests ===== | ===== Writing tests ===== |
| |
| Admidio has a regression test suite and your plugin can use the same tools. | Admidio has a regression test suite, and your plugin uses the same tools. |
| |
| * [[en:entwickler:regression_test_suite|The Admidio regression test suite]] | * [[en:entwickler:regression_test_suite|The Admidio regression test suite]] |
| |
| The suite refuses to run against a database whose name does not contain ''test'' as a separate word, | The suite refuses to run against a database whose name does not contain ''test'' as a separate word, |
| so it cannot destroy a development database by accident. It reinstalls the schema as it goes. | so it cannot destroy a development database by accident. |
| |
| ==== What to test, and how ==== | ==== Where your tests live ==== |
| |
| Split your tests the way the suite does: | Put them beside your plugin, in the three suites the core uses: |
| |
| * **Unit tests** touch no database and no network. Everything about your manifest, your value objects and your pure logic belongs here — these run in a second and you will run them constantly. | <code> |
| * **Integration tests** use a real database through Admidio's entities and services. Anything that saves, reads or deletes a row belongs here. | plugins/my-plugin/tests/Unit/ |
| | plugins/my-plugin/tests/Integration/ |
| | plugins/my-plugin/tests/Cli/ |
| | </code> |
| | |
| | Each suite of ''phpunit.xml'' also reads ''plugins/*/tests/<suite>'', so ''composer test:unit'' runs |
| | your tests together with Admidio's. A plugin that is merely present in ''plugins/'' is tested; it does |
| | not have to be enabled. In turn, **a broken test in your plugin breaks the run for everybody working in |
| | that installation**. Keep unit tests free of the database and the network. The tests are not |
| | distributed: the archive leaves them out. |
| | |
| | ==== What to test, and how ==== |
| | |
| | * **Unit tests** touch no database and no network: your manifest, your value objects and your pure logic. They run in a second. |
| | * **Integration tests** use a real database through Admidio's entities and services: anything that saves, reads or deletes a row. Each one runs inside a transaction that is rolled back afterwards. |
| |
| The base classes are in ''tests/Support/'': ''AdmidioTestCase'' for a unit test, ''DatabaseTestCase'' | The base classes are in ''tests/Support/'': ''AdmidioTestCase'' for a unit test, ''DatabaseTestCase'' |
| for one that needs the database, and ''AdministratorTestCase'' when the code under test requires | for one that needs the database, and ''AdministratorTestCase'' when the code under test requires |
| rights. Each integration test runs inside a transaction that is rolled back afterwards, so tests do | rights. A unit test of a plugin can set where the plugins folder is and what the database says is |
| not see each other's data. | installed: |
| | |
| A unit test for a plugin usually needs three things — where the plugins directory is, what the | |
| database says is installed, and a settings object — and all three can be set: | |
| |
| <code php> | <code php> |
| PluginRegistry::setPluginsPath($myFixtureDirectory); | PluginRegistry::setPluginsPath($myFixtureFolder); |
| PluginRegistry::setInstallations(array('my-plugin' => array('comId' => 1, 'version' => '1.0.0'))); | PluginRegistry::setInstallations(array('my-plugin' => array('comId' => 1, 'version' => '1.0.0'))); |
| $GLOBALS['gSettingsManager'] = new PluginSettingsDouble(array('my_plugin_greeting' => 'Moin')); | |
| </code> | </code> |
| |
| Read a plugin with ''Plugin::read($directory)'' and assert on the descriptor. Build a real ZIP with | Read a plugin with ''Plugin::read($folder)'' and assert on the result. Build a real ZIP with |
| ''ZipArchive'' and hand it to ''PluginPackage::install()'' if you want to test the whole route. | ''ZipArchive'' and hand it to ''PluginPackage::install()'' to test the whole route. |
| |
| ==== Where your tests live ==== | Composer autoloads ''Admidio\'' and ''Admidio\Tests\'', but **not your plugin**: your namespace is |
| | mapped by ''plugin.json'' at runtime. Require the file you test, or read the plugin and load it the way |
| | Admidio does. |
| |
| Put them beside your plugin, in the same three suites the core uses: | The example plugin ships ''plugins/hello-world/tests/Unit/ManifestTest.php''. It guards the two |
| | mistakes that produce no error anywhere: a ''label'' or ''description'' that is not a key of the |
| | plugin's ''languages/en.xml'' (it reaches the form as ''#PLG_...#''), and a renamed setting. |
| | |
| | ===== Packaging and publishing ===== |
| | |
| | ==== The archive ==== |
| | |
| | A plugin is distributed as a ZIP archive with **one top-level folder** that holds the plugin, with |
| | ''plugin.json'' directly inside it: |
| |
| <code> | <code> |
| plugins/my-plugin/tests/Unit/ | my-plugin-1.2.0.zip |
| plugins/my-plugin/tests/Integration/ | └── my-plugin/ |
| plugins/my-plugin/tests/Cli/ | ├── plugin.json |
| | ├── plugin.php (optional) |
| | └── ... |
| </code> | </code> |
| |
| ''phpunit.xml'' picks these up: each suite reads ''plugins/*/tests/<suite>'' as well as its own | The folder is named after the plugin ID, unless ''plugin.json'' states the ID in ''id''. Then the |
| directory. So ''composer test:unit'' runs your unit tests together with Admidio's, and a plugin that | folder may be called anything, and the installer renames it to the ID. This makes the source archive |
| is merely present in ''plugins/'' is tested — it does not have to be enabled, and no organization has | GitHub generates for a tag (''admidio-my-plugin-1.2.0/'') installable as it is. With ''id'', an archive |
| to have switched it on. | **without** a folder, with ''plugin.json'' at the top level, is accepted as well. |
| |
| That has a consequence worth knowing: **a broken test in your plugin breaks the run for everybody | Everything an archive contains is checked before a single file reaches the plugins folder: the folder |
| working in that installation**, exactly as a broken core test would. Keep the unit tests free of the | structure, a valid plugin ID, the manifest, no path that escapes the plugin folder, and |
| database and the network so they stay fast and cannot fail for reasons outside your plugin. | limits of 5000 entries, 32 MB compressed and 128 MB extracted. A failure at any point removes the |
| | temporary folder rather than leaving a partial plugin behind. |
| |
| Nothing stops you from shipping your own ''phpunit.xml'' as well, for developing the plugin outside | The installer skips these entries at any depth: ''__MACOSX'', ''.git'', ''.github'', ''.svn'', |
| an Admidio checkout. Point it at your own ''tests/'' and reuse ''tests/bootstrap.php'' for the | ''.hg'', ''tests'', ''phpunit.xml'', ''phpunit.xml.dist'', ''.phpunit.result.cache'', ''.DS_Store'', |
| autoloader. | ''Thumbs.db'', ''.gitignore'' and ''.gitattributes''. ''vendor'' and ''node_modules'' are extracted: |
| | an archive that carries them was made that way on purpose. |
| |
| ==== Reaching your own classes ==== | ==== Building the archive ==== |
| |
| Composer autoloads ''Admidio\'' and ''Admidio\Tests\'', so a test can extend the base classes | <code bash>./admidio plugin:archive my-plugin --output=/path/to/folder</code> |
| straight away. It does **not** autoload your plugin: your namespace is mapped by ''plugin.json'' and | |
| set up by the plugin loader at runtime, which a unit test does not go through. Require the file you | |
| are testing, or let the test read the plugin and load it the way Admidio does. | |
| |
| ==== A worked example ==== | builds ''<id>-<version>.zip'' and checks it with the very gate the installer uses, so an archive that |
| | builds cleanly installs. It leaves out the entries above and also ''vendor'' and ''node_modules''. |
| |
| The example plugin ships its tests, in ''plugins/hello-world/tests/Unit/ManifestTest.php''. It is | <WRAP center round important 80%> |
| short and it guards the two things that are wrong most often, neither of which produces an error | On macOS, do not build the archive with //Compress// in the Finder. Use ''plugin:archive'', the |
| anywhere: | GitHub workflow below, or ''zip -r my-plugin-1.2.0.zip my-plugin -x "*.DS_Store"'' in a terminal. |
| | </WRAP> |
| |
| * every ''label'' and ''description'' is a real key of the plugin's own ''languages/en.xml'' — a misspelled one reaches the settings form as ''#PLG_...#'' and only a person looking at the page would notice; | ==== Releasing from GitHub ==== |
| * the setting names have not changed — renaming one costs every administrator that setting on update, because the stored row is keyed by the name and nothing migrates it. | |
| |
| ''tests/Unit/Plugins/BuiltInPluginsTest.php'' does the same for the plugins that ship with Admidio, | The Admidio repository provides a **reusable workflow** that builds the archive for every tag and |
| across every one of them at once. | attaches it to the GitHub release of that tag. A plugin repository does not copy it; it //calls// it, |
| | so it gets every later fix of the workflow without doing anything. |
| |
| ===== Packaging and publishing ===== | - State the plugin ID in ''plugin.json'' (''"id": "my-plugin"''). The workflow names the folder in the archive after it. |
| | - Add the file ''.github/workflows/release.yml'' to the plugin repository:<code yaml> |
| | name: Release |
| |
| A plugin is distributed as a ZIP archive containing **exactly one top-level directory, named as the | on: |
| plugin**: | push: |
| | tags: [ 'v*' ] |
| |
| <code> | permissions: |
| my-plugin-1.2.0.zip | contents: write |
| └── my-plugin/ | |
| ├── plugin.json | jobs: |
| ├── plugin.php | release: |
| └── ... | uses: Admidio/admidio/.github/workflows/plugin-release.yml@master |
| | </code> |
| | - Raise ''version'' in ''plugin.json'', commit, and push a tag with that version:<code bash> |
| | git tag v1.2.0 |
| | git push origin v1.2.0 |
| </code> | </code> |
| |
| Admidio builds it for you: | The workflow checks that ''plugin.json'' exists, that the ID is valid and that the tag |
| | is the version of the manifest (with or without a leading ''v''). If the plugin has a |
| | ''composer.json'', it installs the production dependencies from ''composer.lock'' and checks the |
| | platform requirements. Then it builds ''<id>-<version>.zip'' with the same exclusions as |
| | ''plugin:archive'' (but with the generated ''vendor/''), creates the GitHub release of the tag if there |
| | is none yet, and attaches the archive. The summary of the run shows the download address, the SHA-256 |
| | and the contents of the archive. |
| |
| <code>admidio plugin:archive my-plugin --output=/path/to/somewhere</code> | ^ Input ^ Default ^ Description ^ |
| | | ''plugin-directory'' | ''.'' | Folder of the plugin inside the repository, if it is not the repository root. | |
| | | ''plugin-id'' | | The plugin ID, for a ''plugin.json'' without ''id''. | |
| | | ''tag'' | the tag of the run | The tag to release, e.g. when the workflow is started by hand. | |
| | | ''composer-php-version'' | ''8.2'' | PHP version used to install the Composer dependencies. | |
| | | ''draft'' | ''false'' | Attach the archive to a draft release, to be published by hand. | |
| |
| That leaves out what belongs to working on a plugin rather than to the plugin — ''.git'', | <code yaml> |
| ''node_modules'', ''.DS_Store'' and the like — and checks the result with the very gate the installer | jobs: |
| uses, so an archive that builds cleanly will install. | release: |
| | uses: Admidio/admidio/.github/workflows/plugin-release.yml@master |
| | with: |
| | plugin-directory: src/my-plugin |
| | draft: true |
| | </code> |
| | |
| | A workflow that should also run when a release is published in the GitHub web interface uses |
| | ''on: release: types: [published]''. |
| | |
| | <WRAP center round tip 80%> |
| | Use the attached archive (''https://github.com/<owner>/<repository>/releases/download/v1.2.0/my-plugin-1.2.0.zip''), |
| | not the //Source code (zip)// link of the release. The source archive also installs if ''plugin.json'' |
| | states the ''id'', but it contains the whole repository, and GitHub does not guarantee that it stays |
| | byte for byte the same: if it changes, its SHA-256 no longer matches the one the plugin directory |
| | recorded, and the plugin store refuses the download. |
| | </WRAP> |
| | |
| | ==== Publishing in the plugin directory ==== |
| | |
| | The plugin page in the [[en:plugins:index|plugin directory]] lists the releases, and the plugin store of |
| | Admidio reads them from there. Below the release list, //Add release// asks for the address of the |
| | archive: the attached GitHub archive, a file on your own web site, or an archive uploaded to the wiki. |
| | The ID, version, requirements, size and SHA-256 are read from the archive itself, with the same rules the |
| | installer applies. |
| | |
| | An archive **without** ''plugin.json'' is a plugin for Admidio before 6.0. The form then asks for the |
| | version and the Admidio versions it runs on, which must exclude 6.0 (e.g. ''>=5.0 <5.1''). Such a |
| | release is listed for manual installation, but it is never offered to the plugin store. |
| | |
| | ==== The plugin store ==== |
| | |
| | The store is one JSON file on a web server, by default ''plugins.json'' on admidio.org. Admidio fetches |
| | it, caches it in ''adm_my_files'' and refreshes it at most once a day or when an administrator clicks |
| | **Refresh**. The remote call never happens while a page is being built, and a catalogue that cannot be |
| | reached makes the store unavailable rather than breaking the page. |
| |
| An administrator installs it under **Preferences → Plugins → Add plugin**. Admidio checks the whole | The store offers the newest release whose requirements this Admidio and PHP meet. A prerelease |
| archive before unpacking anything: the single directory, a valid plugin name, the manifest, the entry | (''-rc'', ''-beta'', ''-alpha'', ''-dev'') is only offered to installations whose channel admits it, |
| file, no path that escapes the plugin directory, and sensible limits on size. | which is ''stable'' unless a developer sets ''$gPluginStoreChannel''. The plugin manager marks a |
| | prerelease and asks again before it installs one. A download whose SHA-256 does not match the catalogue, |
| | or whose ID or version differs from it, is refused. |
| |
| To have your plugin offered in the plugin store, publish it and ask the Admidio team to add it to the | ''plugin:update'' and the //Update// action fetch newer files where the store publishes them and then |
| catalogue. | run the update scripts, which is all that is needed for a plugin whose files somebody replaced by hand. |
| |
| ===== Rules that will save you time ===== | ===== Rules that will save you time ===== |
| |
| * **The directory name is the identity.** Lowercase letters, digits and hyphens only. | * **The folder name is the identity.** Lower case letters, digits and hyphens. |
| * **Never write into the Admidio core.** Everything you need belongs in your own directory. | * **Never write into the Admidio core.** Everything you need belongs in your own folder, and your data in ''adm_my_files''. |
| * **Installing must not change anything.** A freshly installed plugin should do nothing until it is switched on. | * **Keep ''install.sql'' at the newest schema** and change it together with every update script. |
| * **Removing must leave nothing behind.** Your settings and your tables go with it. | * **Clean up what you own on removal**: tables in ''uninstall.sql'', files and remote data in ''uninstall.php''. The settings of the manifest are removed by Admidio. |
| * **Validate every request parameter** with ''admFuncVariableIsValid()'', use ''FormPresenter'' for forms and Admidio's CSRF handling, and use ''$gDb->queryPrepared()''. | * **Validate every request parameter** with ''admFuncVariableIsValid()'', use ''FormPresenter'' for forms and Admidio's CSRF handling, and bind SQL values with ''$gDb->queryPrepared()''. |
| * **Guard files that are not pages.** A file below ''plugins/'' can be requested directly, so put this at the top of your entry file and of anything else that is not a page: | * **Guard files that are not pages.** Put the ''realpath($_SERVER['SCRIPT_FILENAME'])'' guard at the top of ''plugin.php'' (if you have one), ''cli.php'' and the PHP scripts in ''db_scripts/''. |
| <code php> | * **Pass your plugin ID to every hook registration.** |
| if (realpath($_SERVER['SCRIPT_FILENAME'] ?? '') === __FILE__) { | * **Do not rename settings, and do not change the IDs of released update steps.** |
| exit('This page may not be called directly!'); | |
| } | ===== API reference ===== |
| </code> | |
| | All classes live in the namespace ''Admidio\Infrastructure\Plugins''. |
| | |
| | ==== Plugin ==== |
| | |
| | One plugin as it exists on disk. Reading it never executes plugin code and never throws. |
| | |
| | ^ Property ^ Description ^ |
| | | ''id'' | Plugin ID, which is the folder name | |
| | | ''path'' | Absolute path of the plugin folder | |
| | | ''manifest'' | The decoded manifest, including keys the class does not interpret | |
| | | ''name'', ''description'', ''version'', ''icon'', ''author'', ''homepage'' | Metadata (''homepage'' is the ''url'' of the manifest) | |
| | | ''autoload'' | PSR-4 mappings, as prefix => absolute folder | |
| | | ''settings'' | The preferences the plugin owns, as name => definition | |
| | | ''requires'' | ''admidio'', ''php'', ''extensions'', ''plugins'', ''modules'' | |
| | | ''preferences'' | ''section'' and ''sequence'' of the settings panel | |
| | | ''error'', ''errorCode'' | Why the plugin cannot be used (English, for developers), and a stable code; ''null'' if it can | |
| | |
| | ^ Method ^ Description ^ Return ^ |
| | | ''read(string $directory)'' | Read the plugin in a folder | Plugin | |
| | | ''isValidId(string $id)'' | Whether a folder name is a usable plugin ID | bool | |
| | | ''getSettingKey(string $id)'' | The form of the ID that preference names are built from | string | |
| | | ''isValid()'' | Whether the plugin can be used at all | bool | |
| | | ''getEntryFile()'' / ''hasEntryFile()'' | Absolute path of ''plugin.php''; whether the plugin has one | string / bool | |
| | | ''hasIndexPage()'' | Whether the plugin has the start page ''modules/index.php'' | bool | |
| | | ''getDirectory(string $directory)'' | Absolute path of a conventional subfolder, or ''null'' | ?string | |
| | | ''getPages()'' / ''hasPages()'' | The PHP files directly below ''modules/'' | array / bool | |
| | | ''wantsMenuEntry()'' / ''getMenuParent()'' | Whether the plugin gets a menu entry, and below which node | bool / string | |
| | | ''getUrl(string $page = '')'' | URL of a page, in whichever form is currently live; without a page the URL of ''modules/index.php'', or an empty string | string | |
| | | ''getSettingValues()'' | Every declared preference with its value, cast to the declared type | array | |
| | | ''toRoleIds(mixed $value)'' | The role IDs of a ''roles'' setting | array | |
| | | ''renderTemplate(PagePresenter $page, string $template, array $variables)'' | Render a template of the plugin | string | |
| | | ''getAssetUrl(string $file)'' | Versioned URL of a file below ''assets/'' | string | |
| | | ''getEnabledSettingName()'' / ''getAccessSettingName()'' | ''plugin_<id>_enabled'' / ''<id>_plugin_enabled'' | string | |
| | | ''checkRequirements(array $installedPlugins)'' | One English diagnostic per unsatisfied requirement | array | |
| | | ''getDisabledModules()'' | The Admidio modules the plugin needs that are switched off | array | |
| | | ''versionMatches(string $version, string $constraint)'' | Check a version against a constraint | bool | |
| | |
| | ==== PluginRegistry ==== |
| | |
| | The only place that answers "which plugins are there" and "may this one run". It never includes plugin |
| | code. |
| | |
| | ^ Method ^ Description ^ Return ^ |
| | | ''all()'' / ''get(string $id)'' | Every plugin below ''plugins/'', or one of them | array / ?Plugin | |
| | | ''getState(Plugin or string $plugin)'' | One of the ''STATE_*'' constants | string | |
| | | ''isInstalled(string $id)'' / ''isEnabled(string $id)'' / ''isBuiltIn(string $id)'' | Installed here; enabled for the current organization; part of the Admidio distribution | bool | |
| | | ''getInstalledVersion(string $id)'' | The version the database records | string | |
| | | ''isUpdatePending(Plugin $plugin)'' | Whether the files are newer than the database | bool | |
| | | ''getComponentId(string $id)'' / ''getComponentUuid(string $id)'' | Component record of the plugin | int / string | |
| | | ''getEnabledOrganizations(string $id)'' | Which organizations have it enabled | array | |
| | | ''getLoadable()'' | The plugins that may be loaded in this request | array | |
| | | ''getExcluded()'' | The plugins the crash guard keeps out, as pluginId => ID of the plugin that crashed | array | |
| | | ''getEnabledVersions()'' | pluginId => version of every installed and enabled plugin | array | |
| | | ''getOwnerOfSetting(string $name)'' | Which plugin owns a preference | ?Plugin | |
| | | ''requireEnabled(string $id)'' | Refuse the request unless the plugin is enabled | Plugin | |
| | | ''getScriptPluginId()'' | The plugin the running script belongs to | ?string | |
| | |
| | ==== PluginLoader ==== |
| | |
| | ^ Method ^ Description ^ Return ^ |
| | | ''loadEnabled()'' / ''load(Plugin $plugin)'' | Load every enabled plugin, or one | void / bool | |
| | | ''getLoaded()'' / ''isLoaded(string $id)'' | What was loaded in this request | array / bool | |
| | | ''getFailures()'' | pluginId => why it could not be loaded | array | |
| | | ''getTemplateDirectories()'' | The template search path contributed by plugins | array | |
| | | ''prepareForUpdate(Plugin $plugin)'' | Make the classes and languages of a plugin available without including ''plugin.php'' | void | |
| | |
| | ==== PluginInstaller ==== |
| | |
| | ^ Method ^ Description ^ Return ^ |
| | | ''install(Plugin $plugin, bool $addMenuEntry = true, bool $takeOver = false)'' | Install the plugin; ''$takeOver'' runs the update scripts from the first one | void | |
| | | ''update(Plugin $plugin)'' | Run the update scripts up to the version the files declare | void | |
| | | ''updateWithNewerFiles(Plugin $plugin)'' | Fetch newer files where the store publishes them, then update | Plugin | |
| | | ''remove(Plugin or string $plugin, bool $skipUninstallScript = false)'' | Remove the plugin from every organization, with its data and its files | bool | |
| | | ''enable(Plugin $plugin)'' / ''disable(Plugin $plugin)'' | The per-organization decision; fires ''plugin_enabled'' / ''plugin_disabled'' when the state changes | void | |
| | | ''getRemovalWarnings(Plugin or string $plugin)'' | What the plugin says removal leaves behind | array | |
| | | ''getPreferenceNames(Plugin $plugin)'' | Every preference the plugin owns | array | |
| | |
| | ==== PluginWidget, PluginPanel ==== |
| | |
| | ^ Method ^ Description ^ Return ^ |
| | | ''PluginWidget::register(Plugin $plugin, callable $render, array $options)'' | Declare the widget and add the hook that renders it | void | |
| | | ''PluginWidget::render(PagePresenter $page, Plugin $plugin, string $template, array $variables)'' | Render a template as the widget body | string | |
| | | ''PluginWidget::isVisible(string $preference)'' / ''getAccess(string $preference)'' | Who may see the widget | bool / int | |
| | | ''PluginWidget::getSequence(string $preference, int $default)'' | Position of the widget | int | |
| | | ''PluginPanel::collect()'' / ''inSection(string $section)'' / ''get(string $id)'' | The declared preferences panels | array / ?array | |
| | | ''PluginPanel::normalizeId(string $id)'' | The panel ID a plugin ID maps to | string | |
| | |
| | Constants: ''PluginWidget::HOOK'', ''DEFAULT_SEQUENCE'', ''ACCESS_NOBODY'', ''ACCESS_EVERYBODY'', |
| | ''ACCESS_REGISTERED_USERS''; ''PluginPanel::HOOK'', ''DEFAULT_SEQUENCE''. |
| | |
| | ==== PluginPages, PluginStore, PluginPackage ==== |
| | |
| | ^ Method ^ Description ^ Return ^ |
| | | ''PluginPages::isAllowed()'' / ''isWritable()'' | Whether short addresses are switched on, and possible | bool | |
| | | ''PluginPages::getUrl(Plugin $plugin, string $page)'' | The URL that is currently live | string | |
| | | ''PluginPages::publish(Plugin $plugin)'' / ''unpublish(...)'' / ''syncAll()'' | Write or remove the generated files | bool / void / array | |
| | | ''PluginStore::getPlugins()'' / ''getEntry(string $id)'' | What the catalogue publishes for this Admidio | array / ?array | |
| | | ''PluginStore::getNewerRelease(string $id)'' | A published release newer than the installed one | ?array | |
| | | ''PluginStore::install(string $id)'' / ''updateFiles(string $id)'' | Fetch and place the files | string | |
| | | ''PluginStore::refresh()'' / ''getChannel()'' / ''getError()'' | Fetch the catalogue now; the release channel; why it failed | array / string / ?string | |
| | | ''PluginPackage::install(string $archivePath, bool $replace = false)'' | Put the plugin of an archive on disk; nothing is written to the database | string | |
| | | ''PluginPackage::describe(string $archivePath)'' / ''inspect(string $archivePath)'' | The plugin an archive holds; the gate that checks it | Plugin / string | |
| | | ''PluginPackage::create(Plugin $plugin, string $directory)'' | Build the distributable archive | string | |
| | |
| | ==== Command line ==== |
| | |
| | The plugin manager is fully available from the command line: |
| | |
| | ^ Command ^ Purpose ^ |
| | | ''plugin:list [--state=STATE] [--installed] [--updates]'' | List the plugins and their state. | |
| | | ''plugin:show PLUGIN'' | Show the manifest and the state of a plugin. | |
| | | ''plugin:install SOURCE [--replace]'' | Install a plugin from the store or from an archive file. | |
| | | ''plugin:inspect FILE'' | Show what a plugin archive holds, without installing it. | |
| | | ''plugin:enable PLUGIN'' / ''plugin:disable PLUGIN'' | Enable or disable a plugin for the current organization. | |
| | | ''plugin:update PLUGIN'' | Update a plugin, fetching newer files where the store publishes them. | |
| | | ''plugin:remove PLUGIN [--yes]'' | Remove a plugin from every organization, with its data and its files. | |
| | | ''plugin:archive PLUGIN [--output=FILE] [--overwrite]'' | Build the distributable ZIP archive of a plugin. | |
| | | ''plugin:sync-pages'' | Bring the generated plugin pages in ''modules/'' in line with the preference. | |
| | | ''plugin:store-list [--available] [--updates]'' / ''plugin:store-show PLUGIN'' | What the store publishes. | |
| | | ''plugin:store-refresh'' | Fetch the plugin catalogue now. | |
| | |
| | ===== Changes since the plugin manager of Admidio 5.0 ===== |
| | |
| | The plugin manager of Admidio 5.0 was built around a ''PluginAbstract'' base class. The runtime was |
| | replaced, and a plugin written for it has to be converted: |
| | |
| | ^ Admidio 5.0 ^ Admidio 6.0 ^ |
| | | A main class extending ''PluginAbstract'', with ''doRender()'', ''getInstance()'' and lifecycle methods | **No plugin class.** The optional ''plugin.php'' registers what the plugin contributes and returns nothing. | |
| | | The main file was named by ''mainFile'', or guessed as ''index.php'' / ''PluginName.php'' | The entry file, if there is one, is always ''plugin.php''; pages are module files below ''modules/'', and the menu entry leads to ''modules/index.php''. | |
| | | ''"dependencies"'': Admidio class names that had to exist | ''"requires"'': constraints for ''admidio'' and ''php'', plus ''extensions'', ''plugins'' and ''modules''. | |
| | | ''"defaultConfig"'', each entry with ''name'', ''description'', ''type'', ''value'' | ''"settings"'', each entry with ''type'', ''default'', ''label'', ''description'', plus ''values'' and ''min''/''max''/''step''. | |
| | | ''"overviewPlugin": true'' | ''PluginWidget::register()'' | |
| | | A preferences presenter found by scanning for ''*PreferencesPresenter.php''; ''"preferencesFile"'', ''"hasSubcards"'' | A panel generated from the manifest, or declared through the ''PluginPanel'' hook. | |
| | | ''classes/'' with ''Presenter/'', ''Entity/'', ''Service/'' | Any layout the ''autoload'' mapping names; ''src/'' by convention. | |
| | | ''db-install.sql'' / ''db-uninstall.sql'' | ''db_scripts/install.sql'', ''install.php'', ''update_x_y.xml'', ''uninstall.php'', ''uninstall.sql''. | |
| | | Install and uninstall | Install and update for the installation, enable and disable per organization, remove as the only destructive operation. | |
| | | Installed by copying files | Plugin store, ZIP upload and ''admidio plugin:*'' commands. | |
| | |
| | The generated settings form is the largest simplification: a plugin that only needs ordinary preference |
| | fields declares them in the manifest and writes no presenter, no template and no form code at all. |
| | |
| | Plugins from **before** the plugin system (Admidio 4.x and the ''adm_plugins'' folder) are taken over as |
| | described in [[#taking_over_a_plugin_from_before_admidio_60|Taking over a plugin from before Admidio 6.0]]. |
| |
| ===== Where to look next ===== | ===== Where to look next ===== |
| * [[en:entwickler:hooks:catalogue|The hooks catalogue]] and the [[en:entwickler:hooks|hooks developer guide]]. | * [[en:entwickler:hooks:catalogue|The hooks catalogue]] and the [[en:entwickler:hooks|hooks developer guide]]. |
| * [[en:entwickler:cli|Adding CLI commands]], [[en:2.0:cli:usage|command line usage]] and the [[en:2.0:cli:commands|command reference]]. | * [[en:entwickler:cli|Adding CLI commands]], [[en:2.0:cli:usage|command line usage]] and the [[en:2.0:cli:commands|command reference]]. |
| * [[en:entwickler:programmierrichtlinien|The Admidio coding guidelines]] — a plugin is held to the same standard as the core. | * [[en:entwickler:programmierrichtlinien|The Admidio coding guidelines]]: a plugin is held to the same standard as the core. |
| | * [[en:2.0:plugins|Installing and managing plugins]]: the plugin manager from the administrator's side. |
| * [[en:plugins:index|The plugins published for Admidio]]. | * [[en:plugins:index|The plugins published for Admidio]]. |
| * The example plugin ''plugins/hello-world/'' ships with Admidio and shows every convention on this page in one working plugin. Copy the directory, rename it, and start deleting what you do not need. | * The example plugin ''plugins/hello-world/'' ships with Admidio and shows these conventions in one working plugin. |
| |