[SamplePlugin] Review and update with the latest GNU social best practices

This commit is contained in:
Diogo Cordeiro 2019-08-11 03:16:50 +01:00 committed by Diogo Peralta Cordeiro
parent 68db757269
commit 0c6d94fca8
4 changed files with 203 additions and 188 deletions

View File

@ -65,15 +65,16 @@ class URLMapper
* Route creation. * Route creation.
* $acceptHeaders should be set to true when, for whatever reason, * $acceptHeaders should be set to true when, for whatever reason,
* a path is being re-connected. The $headers list is still optional, * a path is being re-connected. The $headers list is still optional,
* in this case, given that being empty means "accept everything". * in this case, given that being empty means "accept everything".
* *
* @author Evan Prodromou <evan@status.net> * @author Evan Prodromou <evan@status.net>
* @author Bruno Casteleiro <brunoccast@fc.up.pt> * @author Bruno Casteleiro <brunoccast@fc.up.pt>
* @param string $path route path * @param string $path route path
* @param array $args route action and, if needed, action settings * @param array $args route action and, if needed, action settings
* @param array $paramPatterns regex patterns for path's parameters * @param array $paramPatterns regex patterns for path's parameters
* @param bool $acceptHeaders whether a path is being re-connected * @param bool $acceptHeaders whether a path is being re-connected
* @param array $headers headers that should be set for route creation * @param array $headers headers that should be set for route creation
* @throws Exception If can't connect
* @return void * @return void
*/ */
public function connect(string $path, array $args, array $paramPatterns = [], bool $acceptHeaders = false, array $headers = []) public function connect(string $path, array $args, array $paramPatterns = [], bool $acceptHeaders = false, array $headers = [])

View File

@ -1,39 +1,32 @@
<?php <?php
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social 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.
//
// GNU social 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 GNU social. If not, see <http://www.gnu.org/licenses/>.
/** /**
* StatusNet - the distributed open-source microblogging tool * A sample plugin to show best practices for GNU social plugins
* Copyright (C) 2009, StatusNet, Inc.
* *
* A sample Plugin to show best practices for StatusNet plugins * @package GNU social
*
* PHP version 5
*
* 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 Sample
* @package StatusNet
* @author Brion Vibber <brionv@status.net> * @author Brion Vibber <brionv@status.net>
* @author Evan Prodromou <evan@status.net> * @author Evan Prodromou <evan@status.net>
* @copyright 2009 StatusNet, Inc. * @copyright 2019 Free Software Foundation, Inc http://www.fsf.org
* @license http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0 * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
* @link http://status.net/
*/ */
if (!defined('STATUSNET')) { // This check helps protect against security problems;
// This check helps protect against security problems; // your code file can't be executed directly from the web.
// your code file can't be executed directly from the web. defined('GNUSOCIAL') || die();
exit(1);
}
/** /**
* Sample plugin main class * Sample plugin main class
@ -87,38 +80,37 @@ if (!defined('STATUSNET')) {
* main StatusNet distribution go in 'plugins' and third-party or local ones go * main StatusNet distribution go in 'plugins' and third-party or local ones go
* in 'local'. * in 'local'.
* *
* Simple plugins can be implemented as a single Plugin. Others are more complex * Simple plugins can be implemented as a single plugin. Others are more complex
* and require additional Plugins; 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 Plugins should go in the plugin * JavaScript, CSS, external libraries or PHP plugins should go in the plugin
* directory. * directory.
* *
* @category Sample * @category Sample
* @package StatusNet * @package GNU social
* @author Brion Vibber <brionv@status.net> * @author Brion Vibber <brionv@status.net>
* @author Evan Prodromou <evan@status.net> * @author Evan Prodromou <evan@status.net>
* @copyright 2009 StatusNet, Inc. * @copyright 2019 Free Software Foundation, Inc http://www.fsf.org
* @license http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0 * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
* @link http://status.net/
*/ */
class SamplePlugin extends Plugin class SamplePlugin extends Plugin
{ {
const PLUGIN_VERSION = '2.0.0'; // Versions start at 0.1.0 in Semver
const PLUGIN_VERSION = '0.1.0';
/** /**
* Plugins are configured using public instance attributes. To set * Plugins are configured using public instance attributes. To set
* their values, site administrators use this syntax: * their values, site administrators use this syntax:
* *
* addPlugin('Sample', array('attr1' => 'foo', 'attr2' => 'bar')); * addPlugin('Sample', ['attr1' => 'foo', 'attr2' => 'bar']);
* *
* The same plugin class can be initialized multiple times with different * The same plugin class can be initialized multiple times with different
* arguments: * arguments:
* *
* 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']);
* *
*/ */
public $attr1 = null; public $attr1 = null;
public $attr2 = null; public $attr2 = null;
@ -128,9 +120,9 @@ class SamplePlugin extends Plugin
* Plugins overload this method to do any initialization they need, * Plugins overload this method to do any initialization they need,
* like connecting to remote servers or creating paths or so on. * like connecting to remote servers or creating paths or so on.
* *
* @return boolean hook value; true means continue processing, false means stop. * @return bool hook value; true means continue processing, false means stop.
*/ */
function initialize() public function initialize(): bool
{ {
return true; return true;
} }
@ -141,9 +133,9 @@ class SamplePlugin extends Plugin
* Plugins overload this method to do any cleanup they need, * Plugins overload this method to do any cleanup they need,
* like disconnecting from remote servers or deleting temp files or so on. * like disconnecting from remote servers or deleting temp files or so on.
* *
* @return boolean hook value; true means continue processing, false means stop. * @return bool hook value; true means continue processing, false means stop.
*/ */
function cleanup() public function cleanup(): bool
{ {
return true; return true;
} }
@ -162,12 +154,11 @@ class SamplePlugin extends Plugin
* However, they need to remember to run that script after installing or * However, they need to remember to run that script after installing or
* upgrading a plugin! * upgrading a plugin!
* *
* @return bool hook value; true means continue processing, false means stop.
* @see Schema * @see Schema
* @see ColumnDef * @see ColumnDef
*
* @return boolean hook value; true means continue processing, false means stop.
*/ */
function onCheckSchema() public function onCheckSchema(): bool
{ {
$schema = Schema::get(); $schema = Schema::get();
@ -186,12 +177,15 @@ class SamplePlugin extends Plugin
* *
* @param URLMapper $m path-to-action mapper * @param URLMapper $m path-to-action mapper
* *
* @return boolean hook value; true means continue processing, false means stop. * @return bool hook value; true means continue processing, false means stop.
* @throws Exception If it can't connect our required routes
*/ */
public function onRouterInitialized(URLMapper $m) public function onRouterInitialized(URLMapper $m): bool
{ {
$m->connect('main/hello', $m->connect(
['action' => 'hello']); 'main/hello',
['action' => 'hello']
);
return true; return true;
} }
@ -208,31 +202,45 @@ class SamplePlugin extends Plugin
* @param Action $action The current action handler. Use this to * @param Action $action The current action handler. Use this to
* do any output. * do any output.
* *
* @return boolean hook value; true means continue processing, false means stop. * @return bool hook value; true means continue processing, false means stop.
* *
* @throws Exception
* @see Action * @see Action
*/ */
function onEndPrimaryNav($action) public function onEndPrimaryNav(Action $action): bool
{ {
// common_local_url() gets the correct URL for the action name // common_local_url() gets the correct URL for the action name
// we provide // we provide
$action->menuItem(common_local_url('hello'), $action->menuItem(
// TRANS: Menu item in sample plugin. common_local_url('hello'),
_m('Hello'), // TRANS: Menu item in sample plugin.
// TRANS: Menu item title in sample plugin. _m('Hello'),
_m('A warm greeting'), false, 'nav_hello'); // TRANS: Menu item title in sample plugin.
_m('A warm greeting'),
false,
'nav_hello'
);
return true; return true;
} }
/**
* Plugin version information/meta-data
*
* @param array $versions
* @return bool hook true
* @throws Exception
*/
public function onPluginVersion(array &$versions): bool public function onPluginVersion(array &$versions): bool
{ {
$versions[] = array('name' => 'Sample', $versions[] = [
'version' => self::PLUGIN_VERSION, 'name' => 'Sample',
'author' => 'Brion Vibber, Evan Prodromou', 'version' => self::PLUGIN_VERSION,
'homepage' => 'https://git.gnu.io/gnu/gnu-social/tree/master/plugins/Sample', 'author' => 'Brion Vibber, Evan Prodromou',
'rawdescription' => 'homepage' => 'https://git.gnu.io/gnu/gnu-social/tree/master/plugins/Sample',
// TRANS: Plugin description. 'rawdescription' =>
_m('A sample plugin to show basics of development for new hackers.')); // TRANS: Plugin description.
_m('A sample plugin to show basics of development for new hackers.')
];
return true; return true;
} }
} }

View File

@ -1,55 +1,48 @@
<?php <?php
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social 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.
//
// GNU social 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 GNU social. If not, see <http://www.gnu.org/licenses/>.
/** /**
* Give a warm greeting to our friendly user * Give a warm greeting to our friendly user
* *
* PHP version 5 * @package GNU social
* * @author Brion Vibber <brionv@status.net>
* @category Sample * @author Evan Prodromou <evan@status.net>
* @package StatusNet * @copyright 2019 Free Software Foundation, Inc http://www.fsf.org
* @author Evan Prodromou <evan@status.net> * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
* @license http://www.fsf.org/licensing/licenses/agpl.html AGPLv3
* @link http://status.net/
*
* StatusNet - the distributed open-source microblogging tool
* Copyright (C) 2009, StatusNet, Inc.
*
* 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/>.
*/ */
if (!defined('STATUSNET')) { defined('GNUSOCIAL') || die();
exit(1);
}
/** /**
* Give a warm greeting to our friendly user
*
* This sample action shows some basic ways of doing output in an action * This sample action shows some basic ways of doing output in an action
* class. * class.
* *
* Action classes have several output methods that they override from * Action classes have several output methods that they override from
* the parent class. * the parent class.
* *
* @category Sample * @category Sample
* @package StatusNet * @package GNU social
* @author Evan Prodromou <evan@status.net> * @author Evan Prodromou <evan@status.net>
* @license http://www.fsf.org/licensing/licenses/agpl.html AGPLv3 * @copyright 2019 Free Software Foundation, Inc http://www.fsf.org
* @link http://status.net/ * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/ */
class HelloAction extends Action class HelloAction extends Action
{ {
var $user = null; public $user = null;
var $gc = null; public $gc = null;
/** /**
* Take arguments for running * Take arguments for running
@ -64,16 +57,17 @@ class HelloAction extends Action
* *
* @param array $args $_REQUEST args * @param array $args $_REQUEST args
* *
* @return boolean success flag * @return bool success flag
* @throws ClientException
*/ */
function prepare(array $args = array()) public function prepare(array $args = [])
{ {
parent::prepare($args); parent::prepare($args);
$this->user = common_current_user(); $this->user = common_current_user();
if (!empty($this->user)) { if (!empty($this->user)) {
$this->gc = User_greeting_count::inc($this->user->id); $this->gc = User_greeting_count::inc($this->user->getID());
} }
return true; return true;
@ -87,11 +81,12 @@ class HelloAction extends Action
* by the time handle() is called the action should be * by the time handle() is called the action should be
* more or less ready to go. * more or less ready to go.
* *
* @param array $args $_REQUEST args; handled in prepare()
*
* @return void * @return void
* @throws ClientException
* @throws ReflectionException
* @throws ServerException
*/ */
function handle() public function handle()
{ {
parent::handle(); parent::handle();
@ -104,15 +99,16 @@ class HelloAction extends Action
* Override this method to show a custom title. * Override this method to show a custom title.
* *
* @return string Title of the page * @return string Title of the page
* @throws Exception
*/ */
function title() public function title()
{ {
if (empty($this->user)) { if (empty($this->user)) {
// TRANS: Page title for sample plugin. // TRANS: Page title for sample plugin.
return _m('Hello'); return _m('Hello');
} else { } else {
// TRANS: Page title for sample plugin. %s is a user nickname. // TRANS: Page title for sample plugin. %s is a user nickname.
return sprintf(_m('Hello, %s!'), $this->user->nickname); return sprintf(_m('Hello, %s!'), $this->user->getNickname());
} }
} }
@ -127,24 +123,38 @@ class HelloAction extends Action
* This method also demonstrates use of a plural localized string. * This method also demonstrates use of a plural localized string.
* *
* @return void * @return void
* @throws Exception
*/ */
function showContent() public function showContent()
{ {
if (empty($this->user)) { if (empty($this->user)) {
$this->element('p', array('class' => 'greeting'), $this->element(
// TRANS: Message in sample plugin. 'p',
_m('Hello, stranger!')); ['class' => 'greeting'],
// TRANS: Message in sample plugin.
_m('Hello, stranger!')
);
} else { } else {
$this->element('p', array('class' => 'greeting'), $this->element(
// TRANS: Message in sample plugin. %s is a user nickname. 'p',
sprintf(_m('Hello, %s'), $this->user->nickname)); ['class' => 'greeting'],
$this->element('p', array('class' => 'greeting_count'), // TRANS: Message in sample plugin. %s is a user nickname.
// TRANS: Message in sample plugin. sprintf(_m('Hello, %s'), $this->user->getNickname())
// TRANS: %d is the number of times a user is greeted. );
sprintf(_m('I have greeted you %d time.', $this->element(
'I have greeted you %d times.', 'p',
$this->gc->greeting_count), ['class' => 'greeting_count'],
$this->gc->greeting_count)); // TRANS: Message in sample plugin.
// TRANS: %d is the number of times a user is greeted.
sprintf(
_m(
'I have greeted you %d time.',
'I have greeted you %d times.',
$this->gc->greeting_count
),
$this->gc->greeting_count
)
);
} }
} }
@ -161,9 +171,9 @@ class HelloAction extends Action
* *
* @param array $args other arguments, if RO/RW status depends on them. * @param array $args other arguments, if RO/RW status depends on them.
* *
* @return boolean is read only action? * @return bool is read only action?
*/ */
function isReadOnly($args) public function isReadOnly($args)
{ {
return false; return false;
} }

View File

@ -1,42 +1,33 @@
<?php <?php
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social 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.
//
// GNU social 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 GNU social. If not, see <http://www.gnu.org/licenses/>.
/** /**
* Data class for counting greetings * Data class for counting greetings
* *
* PHP version 5 * @package GNU social
* * @author Brion Vibber <brionv@status.net>
* @category Data * @author Evan Prodromou <evan@status.net>
* @package StatusNet * @copyright 2019 Free Software Foundation, Inc http://www.fsf.org
* @author Evan Prodromou <evan@status.net> * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
* @license http://www.fsf.org/licensing/licenses/agpl.html AGPLv3
* @link http://status.net/
*
* StatusNet - the distributed open-source microblogging tool
* Copyright (C) 2009, StatusNet, Inc.
*
* 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/>.
*/ */
if (!defined('STATUSNET')) { defined('GNUSOCIAL') || die();
exit(1);
}
require_once INSTALLDIR . '/classes/Memcached_DataObject.php';
/** /**
* Data class for counting greetings * We use the DB_DataObject framework for data classes in GNU social. Each
*
* We use the DB_DataObject framework for data classes in StatusNet. Each
* table maps to a particular data class, making it easier to manipulate * table maps to a particular data class, making it easier to manipulate
* data. * data.
* *
@ -44,11 +35,11 @@ require_once INSTALLDIR . '/classes/Memcached_DataObject.php';
* extension of DB_DataObject that provides caching, internationalization, * extension of DB_DataObject that provides caching, internationalization,
* and other bits of good functionality to StatusNet-specific data classes. * and other bits of good functionality to StatusNet-specific data classes.
* *
* @category Action * @category Action
* @package StatusNet * @package GNU social
* @author Evan Prodromou <evan@status.net> * @author Evan Prodromou <evan@status.net>
* @license http://www.fsf.org/licensing/licenses/agpl.html AGPLv3 * @copyright 2019 Free Software Foundation, Inc http://www.fsf.org
* @link http://status.net/ * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
* *
* @see DB_DataObject * @see DB_DataObject
*/ */
@ -57,23 +48,23 @@ class User_greeting_count extends Managed_DataObject
public $__table = 'user_greeting_count'; // table name public $__table = 'user_greeting_count'; // table name
public $user_id; // int(4) primary_key not_null public $user_id; // int(4) primary_key not_null
public $greeting_count; // int(4) public $greeting_count; // int(4)
public $created; // datetime() not_null public $created; // datetime() not_null default_0000-00-00%2000%3A00%3A00
public $modified; // datetime not_null default_0000-00-00%2000%3A00%3A00 public $modified; // datetime() not_null default_CURRENT_TIMESTAMP
public static function schemaDef() public static function schemaDef()
{ {
return array( return [
'fields' => array( 'fields' => [
'user_id' => array('type' => 'int', 'not null' => true, 'description' => 'user id'), 'user_id' => ['type' => 'int', 'not null' => true, 'description' => 'user id'],
'greeting_count' => array('type' => 'int', 'not null' => true, 'description' => 'the greeting count'), 'greeting_count' => ['type' => 'int', 'not null' => true, 'description' => 'the greeting count'],
'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'), 'created' => ['type' => 'datetime', 'not null' => true, 'default' => '0000-00-00 00:00:00', 'description' => 'date this record was created'],
'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'), 'modified' => ['type' => 'datetime', 'not null' => true, 'default' => 'CURRENT_TIMESTAMP', 'description' => 'date this record was modified'],
), ],
'primary key' => array('user_id'), 'primary key' => ['user_id'],
'foreign keys' => array( 'foreign keys' => [
'user_greeting_count_user_id_fkey' => array('user', array('user_id' => 'id')), 'user_greeting_count_user_id_fkey' => ['user', ['user_id' => 'id']],
), ],
); ];
} }
/** /**
@ -85,15 +76,16 @@ class User_greeting_count extends Managed_DataObject
* @param integer $user_id ID of the user to get a count for * @param integer $user_id ID of the user to get a count for
* *
* @return User_greeting_count instance for this user, with count already incremented. * @return User_greeting_count instance for this user, with count already incremented.
* @throws Exception
*/ */
static function inc($user_id) public static function inc($user_id)
{ {
$gc = User_greeting_count::getKV('user_id', $user_id); $gc = User_greeting_count::getKV('user_id', $user_id);
if (empty($gc)) { if (empty($gc)) {
$gc = new User_greeting_count(); $gc = new User_greeting_count();
$gc->user_id = $user_id; $gc->user_id = $user_id;
$gc->greeting_count = 1; $gc->greeting_count = 1;
$result = $gc->insert(); $result = $gc->insert();
@ -101,21 +93,25 @@ class User_greeting_count extends Managed_DataObject
if (!$result) { if (!$result) {
// TRANS: Exception thrown when the user greeting count could not be saved in the database. // TRANS: Exception thrown when the user greeting count could not be saved in the database.
// TRANS: %d is a user ID (number). // TRANS: %d is a user ID (number).
throw new Exception(sprintf(_m('Could not save new greeting count for %d.'), throw new Exception(sprintf(
$user_id)); _m('Could not save new greeting count for %d.'),
$user_id
));
} }
} else { } else {
$orig = clone($gc); $orig = clone($gc);
$gc->greeting_count++; ++$gc->greeting_count;
$result = $gc->update($orig); $result = $gc->update($orig);
if (!$result) { if (!$result) {
// TRANS: Exception thrown when the user greeting count could not be saved in the database. // TRANS: Exception thrown when the user greeting count could not be saved in the database.
// TRANS: %d is a user ID (number). // TRANS: %d is a user ID (number).
throw new Exception(sprintf(_m('Could not increment greeting count for %d.'), throw new Exception(sprintf(
$user_id)); _m('Could not increment greeting count for %d.'),
$user_id
));
} }
} }