[DOCUMENTATION][DEVELOPERS][PLUGINS] Some updates to Plugins doc

This commit is contained in:
Diogo Cordeiro 2019-08-12 21:48:29 +01:00 committed by Diogo Peralta Cordeiro
parent a43c10582f
commit 5524cf331c
210 changed files with 70 additions and 101 deletions

View File

@ -1,8 +1,8 @@
Plugin Development Plugin Development
======================= ==================
SamplePlugin.php SamplePlugin.php
----------------------- ----------------
Each plugin requires a main class to interact with the GNU social system. Each plugin requires a main class to interact with the GNU social system.
@ -15,7 +15,7 @@ have pre-defined arguments, based on which event they're handling. A typical
event handler: event handler:
```php ```php
function onSomeEvent($paramA, &$paramB) public function onSomeEvent($paramA, &$paramB): bool
{ {
if ($paramA == 'jed') { if ($paramA == 'jed') {
throw new Exception(sprintf(_m("Invalid parameter %s"), $paramA)); throw new Exception(sprintf(_m("Invalid parameter %s"), $paramA));
@ -26,7 +26,7 @@ function onSomeEvent($paramA, &$paramB)
``` ```
Event Handlers Event Handlers
----------------------- --------------
Event handlers must return a Boolean value. Event handlers must return a Boolean value.
@ -41,50 +41,43 @@ If the handler throws an exception, processing will stop, and the exception's
error will be shown to the user. error will be shown to the user.
Installation Installation
------------------ ------------
To install a plugin (like this one), site admins add the following code to their To enable a plugin (like the SamplePlugin), site admins add the following code to their
config.php file: config.php file:
```php ```php
addPlugin('Sample'); addPlugin('Sample');
``` ```
Plugins must be installed in one of the following directories: Third Party Plugins must be installed in `local/plugins/{$name}/{$pluginclass}.php`
* local/plugins/{$pluginclass}.php
* local/plugins/{$name}/{$pluginclass}.php
* local/{$pluginclass}.php
* local/{$name}/{$pluginclass}.php
* plugins/{$pluginclass}.php
* plugins/{$name}/{$pluginclass}.php
Here, `{$name}` is the name of the plugin, like 'Sample', and `{$pluginclass}` Here, `{$name}` is the name of the plugin, like 'Sample', and `{$pluginclass}`
is the name of the main class, like 'SamplePlugin'. Plugins that are part of is the name of the main class, like 'SamplePlugin'. Plugins that are part of
the main GNU social distribution go in 'plugins' and third-party or local ones the main GNU social distribution go in 'plugins' and third-party or local ones
go in 'local'. go in 'local'.
Simple plugins can be implemented as a single module. Others are more complex Simple plugins can be implemented as a single plugin. Others are more complex
and require additional modules; these should use their own directory, like and require additional plugins; these should use their own directory, like
'local/plugins/{$name}/'. All files related to the plugin, including images, 'local/plugins/{$name}/'. All files related to the plugin, including images,
JavaScript, CSS, external libraries or PHP modules should go in the plugin JavaScript, CSS, external libraries or PHP plugins should go in the plugin
directory. directory.
Plugin Configuration Plugin Configuration
------------------ --------------------
Plugins are configured using public instance attributes. To set their values, Plugins are configured using public instance attributes. To set their values,
site administrators use this syntax: site administrators use this syntax:
```php ```php
addPlugin('Sample', ('attr1' => 'foo', 'attr2' => 'bar')); addPlugin('Sample', ['attr1' => 'foo', 'attr2' => 'bar']);
``` ```
The same plugin class can be initialized multiple times with different arguments: The same plugin class can be initialized multiple times with different arguments:
```php ```php
addPlugin('EmailNotify', array('sendTo' => 'evan@status.net')); addPlugin('EmailNotify', ['sendTo' => 'evan@status.net']);
addPlugin('EmailNotify', array('sendTo' => 'brionv@status.net')); addPlugin('EmailNotify', ['sendTo' => 'brionv@status.net']);
``` ```
```php ```php
@ -96,34 +89,34 @@ class SamplePlugin extends Plugin
``` ```
Initialization Initialization
------------------ --------------
Plugins overload this method to do any initialization they need, like connecting Plugins overload this method to do any initialization they need, like connecting
to remote servers or creating paths or so on. @return boolean hook value; true to remote servers or creating paths or so on. @return bool hook value; true
means continue processing, false means stop. means continue processing, false means stop.
```php ```php
function initialize() public function initialize(): bool
{ {
return true; return true;
} }
``` ```
Clean Up Clean Up
------------------ --------
Plugins overload this method to do any cleanup they need, like disconnecting from Plugins overload this method to do any cleanup they need, like disconnecting from
remote servers or deleting temp files or so on. remote servers or deleting temp files or so on.
```php ```php
function cleanup() public function cleanup(): bool
{ {
return true; return true;
} }
``` ```
Database schema setup Database schema setup
------------------ ---------------------
Plugins can add their own tables to the GNU social database. Plugins should use Plugins can add their own tables to the GNU social database. Plugins should use
GNU social's schema interface to add or delete tables. The ensureTable() method GNU social's schema interface to add or delete tables. The ensureTable() method
@ -135,25 +128,26 @@ the checkschema.php script is run, greatly improving performance. However, they
need to remember to run that script after installing or upgrading a plugin! need to remember to run that script after installing or upgrading a plugin!
```php ```php
function onCheckSchema() public function onCheckSchema(): bool
{ {
$schema = Schema::get(); $schema = Schema::get();
// '''For storing user-submitted flags on profiles''' // '''For storing user-submitted flags on profiles'''
$schema->ensureTable('user_greeting_count', $schema->ensureTable('user_greeting_count',[
array(new ColumnDef('user_id', 'integer', null, new ColumnDef('user_id', 'integer', null, true, 'PRI'),
true, 'PRI'), new ColumnDef('greeting_count', 'integer')
new ColumnDef('greeting_count', 'integer'))); ]
);
return true; return true;
} }
``` ```
Load related modules when needed Load related plugins when needed
------------------ --------------------------------
Most non-trivial plugins will require extra modules to do their work. Typically Most non-trivial plugins will require extra plugins to do their work. Typically
these include data classes, action classes, widget classes, or external libraries. these include data classes, action classes, widget classes, or external libraries.
This method receives a class name and loads the PHP file related to that class. This method receives a class name and loads the PHP file related to that class.
@ -166,26 +160,26 @@ in this plugin! So, make sure to return true by default to let other plugins,
and the core code, get a chance. and the core code, get a chance.
```php ```php
function onAutoload($cls) public function onAutoload($cls): bool
{ {
$dir = dirname(__FILE__); $dir = __DIR__;
switch ($cls) switch ($cls)
{ {
case 'HelloAction': case 'HelloAction':
include_once $dir . '/' . strtolower(mb_substr($cls, 0, -6)) . '.php'; include_once $dir . '/' . strtolower(mb_substr($cls, 0, -6)) . '.php';
return false; return false;
case 'User_greeting_count': case 'User_greeting_count':
include_once $dir . '/'.$cls.'.php'; include_once $dir . '/'.$cls.'.php';
return false; return false;
default: default:
return true; return true;
} }
} }
``` ```
Map URLs to actions Map URLs to actions
------------------ -------------------
This event handler lets the plugin map URLs on the site to actions (and thus an This event handler lets the plugin map URLs on the site to actions (and thus an
action handler class). Note that the action handler class for an action will be action handler class). Note that the action handler class for an action will be
@ -193,28 +187,28 @@ named 'FoobarAction', where action = 'foobar'. The class must be loaded in the
onAutoload() method. onAutoload() method.
```php ```php
function onRouterInitialized($m) public function onRouterInitialized($m): bool
{ {
$m->connect('main/hello', $m->connect('main/hello',
array('action' => 'hello')); ['action' => 'hello']);
return true; return true;
} }
``` ```
Modify the default menu to link to our custom action Modify the default menu to link to our custom action
------------------ -----------------------------------------------------
Using event handlers, it's possible to modify the default UI for pages almost Using event handlers, it's possible to modify the default UI for pages almost
without limit. In this method, we add a menu item to the default primary menu without limit. In this method, we add a menu item to the default primary menu
for the interface to link to our action. for the interface to link to our action.
Action Class Action Class
------------------ ------------
The Action class provides a rich set of events to hook, as well as output methods. The Action class provides a rich set of events to hook, as well as output methods.
```php ```php
function onEndPrimaryNav($action) public function onEndPrimaryNav($action): bool
{ {
// '''common_local_url()''' gets the correct URL for the action name we provide // '''common_local_url()''' gets the correct URL for the action name we provide
@ -225,18 +219,20 @@ function onEndPrimaryNav($action)
public function onPluginVersion(&$versions): bool public function onPluginVersion(&$versions): bool
{ {
$versions[] = array('name' => 'Sample', $versions[] = [
'version' => GNUSOCIAL_VERSION, 'name' => 'Sample',
'author' => 'Brion Vibber, Evan Prodromou', 'version' => GNUSOCIAL_VERSION,
'homepage' => 'http://example.org/plugin', 'author' => 'Brion Vibber, Evan Prodromou',
'rawdescription' => 'homepage' => 'http://example.org/plugin',
_m('A sample plugin to show basics of development for new hackers.')); 'rawdescription' =>
_m('A sample plugin to show basics of development for new hackers.')
];
return true; return true;
} }
``` ```
hello.php hello.php
------------------ ---------
This section is taken directly from the 'hello.php'. ( plugins/Sample/hello.php ) This section is taken directly from the 'hello.php'. ( plugins/Sample/hello.php )
@ -255,7 +251,7 @@ class HelloAction extends Action
``` ```
Take arguments for running Take arguments for running
------------------ --------------------------
This method is called first, and it lets the action class get all its arguments This method is called first, and it lets the action class get all its arguments
and validate them. It's also the time to fetch any relevant data from the database. and validate them. It's also the time to fetch any relevant data from the database.
@ -264,7 +260,7 @@ Action classes should run parent::prepare(array $args = []) as the first line
of this method to make sure the default argument-processing happens. of this method to make sure the default argument-processing happens.
```php ```php
function prepare(array $args = []) public function prepare(array $args = []): bool
{ {
parent::prepare($args); parent::prepare($args);
@ -279,14 +275,14 @@ function prepare(array $args = [])
``` ```
Handle request Handle request
------------------ --------------
This is the main method for handling a request. Note that most preparation This is the main method for handling a request. Note that most preparation
should be done in the prepare() method; by the time handle() is called the should be done in the prepare() method; by the time handle() is called the
action should be more or less ready to go. action should be more or less ready to go.
```php ```php
function handle() public function handle(): void
{ {
parent::handle(); parent::handle();
@ -300,7 +296,7 @@ Title of this page
Override this method to show a custom title. Override this method to show a custom title.
```php ```php
function title() public function title(): string
{ {
if (empty($this->user)) { if (empty($this->user)) {
return _m('Hello'); return _m('Hello');
@ -311,7 +307,7 @@ function title()
``` ```
Show content in the content area Show content in the content area
------------------ --------------------------------
The default GNU social page has a lot of decorations: menus, logos, tabs, all The default GNU social page has a lot of decorations: menus, logos, tabs, all
that jazz. This method is used to show content in the content area of the that jazz. This method is used to show content in the content area of the
@ -319,15 +315,15 @@ page; it's the main thing you want to overload. This method also demonstrates
use of a plural localized string. use of a plural localized string.
```php ```php
function showContent() public function showContent(): void
{ {
if (empty($this->user)) { if (empty($this->user)) {
$this->element('p', array('class' => 'greeting'), $this->element('p', ['class' => 'greeting'],
_m('Hello, stranger!')); _m('Hello, stranger!'));
} else { } else {
$this->element('p', array('class' => 'greeting'), $this->element('p', ['class' => 'greeting'],
sprintf(_m('Hello, %s'), $this->user->nickname)); sprintf(_m('Hello, %s'), $this->user->nickname));
$this->element('p', array('class' => 'greeting_count'), $this->element('p', ['class' => 'greeting_count'],
sprintf(_m('I have greeted you %d time.', sprintf(_m('I have greeted you %d time.',
'I have greeted you %d times.', 'I have greeted you %d times.',
$this->gc->greeting_count), $this->gc->greeting_count),
@ -337,7 +333,7 @@ function showContent()
``` ```
Return true if read only. Return true if read only.
------------------ -------------------------
Some actions only read from the database; others read and write. The simple Some actions only read from the database; others read and write. The simple
database load-balancer built into GNU social will direct read-only actions to database load-balancer built into GNU social will direct read-only actions to
@ -347,9 +343,8 @@ This defaults to false to avoid data integrity issues, but you should make sure
to overload it for performance gains. to overload it for performance gains.
```php ```php
function isReadOnly($args) public function isReadOnly($args): bool
{ {
return false; return false;
} }
``` ```

View File

@ -13,39 +13,13 @@
// //
// You should have received a copy of the GNU Affero General Public License // You should have received a copy of the GNU Affero General Public License
// along with GNU social. If not, see <http://www.gnu.org/licenses/>. // along with GNU social. If not, see <http://www.gnu.org/licenses/>.
/**
* StatusNet, the distributed open-source microblogging tool
*
* Module to add additional awesomenss to StatusNet
*
* PHP version 5
*
* LICENCE: This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* @category Module
* @package StatusNet
* @author Jeroen De Dauw <jeroendedauw@gmail.com>
* @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
* @link http://status.net/
*/
defined('GNUSOCIAL') || die(); defined('GNUSOCIAL') || die();
/** /**
* Fun sample plugin: tweaks input data and adds a 'Cornify' widget to sidebar. * Fun sample plugin: tweaks input data and adds a 'Cornify' widget to sidebar.
* *
* @category Module * @category Plugin
* @package GNUsocial * @package GNUsocial
* @author Jeroen De Dauw <jeroendedauw@gmail.com> * @author Jeroen De Dauw <jeroendedauw@gmail.com>
* @copyright 2019 Free Software Foundation, Inc http://www.fsf.org * @copyright 2019 Free Software Foundation, Inc http://www.fsf.org
@ -63,7 +37,7 @@ class AwesomenessPlugin extends Plugin
'version' => self::PLUGIN_VERSION, 'version' => self::PLUGIN_VERSION,
'author' => 'Jeroen De Dauw', 'author' => 'Jeroen De Dauw',
'homepage' => 'https://git.gnu.io/gnu/gnu-social/tree/master/plugins/Awesomeness', 'homepage' => 'https://git.gnu.io/gnu/gnu-social/tree/master/plugins/Awesomeness',
// TRANS: Module description for a sample plugin. // TRANS: Plugin description for a sample plugin.
'rawdescription' => _m('The Awesomeness plugin adds additional awesomeness ' . 'rawdescription' => _m('The Awesomeness plugin adds additional awesomeness ' .
'to a GNU social installation.') 'to a GNU social installation.')
]; ];
@ -80,7 +54,7 @@ class AwesomenessPlugin extends Plugin
public function onEndShowSections(Action $action) public function onEndShowSections(Action $action)
{ {
$action->elementStart('div', ['id' => 'cornify_section', $action->elementStart('div', ['id' => 'cornify_section',
'class' => 'section']); 'class' => 'section']);
$action->raw( $action->raw(
<<<EOT <<<EOT

Some files were not shown because too many files have changed in this diff Show More