[CORE] Plugin API now extends a new Module API

This commit is contained in:
Diogo Cordeiro 2019-08-12 15:03:30 +01:00
parent b6e7b18c7b
commit 0c2c3ec862
397 changed files with 3093 additions and 1450 deletions

View File

@ -223,10 +223,10 @@ function onEndPrimaryNav($action)
return true;
}
function onPluginVersion(&$versions)
public function onPluginVersion(&$versions): bool
{
$versions[] = array('name' => 'Sample',
'version' => STATUSNET_VERSION,
'version' => GNUSOCIAL_VERSION,
'author' => 'Brion Vibber, Evan Prodromou',
'homepage' => 'http://example.org/plugin',
'rawdescription' =>

View File

@ -72,7 +72,7 @@ class VersionAction extends Action
{
parent::prepare($args);
Event::handle('PluginVersion', array(&$this->pluginVersions));
Event::handle('PluginVersion', [&$this->pluginVersions]);
return true;
}

View File

@ -106,6 +106,7 @@ require_once INSTALLDIR . '/lib/language.php';
// can use it
require_once INSTALLDIR . '/lib/event.php';
require_once INSTALLDIR . '/lib/modules/Module.php';
require_once INSTALLDIR . '/lib/modules/Plugin.php';
function addPlugin($name, array $attrs = [])

View File

@ -27,10 +27,66 @@ class GNUsocial
protected static $have_config;
protected static $is_api;
protected static $is_ajax;
protected static $plugins = [];
protected static $modules = [];
/**
* Configure and instantiate a plugin (or a core module) into the current configuration.
* Configure and instantiate a core module into the current configuration.
* Class definitions will be loaded from standard paths if necessary.
* Note that initialization events won't be fired until later.
*
* @param string $name class name & module file/subdir name
* @param array $attrs key/value pairs of public attributes to set on module instance
*
* @return bool
* @throws ServerException if module can't be found
*/
public static function addModule(string $name, array $attrs = [])
{
$name = ucfirst($name);
if (isset(self::$modules[$name])) {
// We have already loaded this module. Don't try to
// do it again with (possibly) different values.
// Försten till kvarn får mala.
return true;
}
$moduleclass = "{$name}Module";
if (!class_exists($moduleclass)) {
$files = [
"modules/{$moduleclass}.php",
"modules/{$name}/{$moduleclass}.php"
];
foreach ($files as $file) {
$fullpath = INSTALLDIR . '/' . $file;
if (@file_exists($fullpath)) {
include_once $fullpath;
break;
}
}
if (!class_exists($moduleclass)) {
throw new ServerException("Module $name not found.", 500);
}
}
// Doesn't this $inst risk being garbage collected or something?
// TODO: put into a static array that makes sure $inst isn't lost.
$inst = new $moduleclass();
foreach ($attrs as $aname => $avalue) {
$inst->$aname = $avalue;
}
// Record activated modules for later display/config dump
self::$modules[$name] = $attrs;
return true;
}
/**
* Configure and instantiate a plugin into the current configuration.
* Class definitions will be loaded from standard paths if necessary.
* Note that initialization events won't be fired until later.
*
@ -44,7 +100,7 @@ class GNUsocial
{
$name = ucfirst($name);
if (isset(self::$plugins[$name])) {
if (isset(self::$modules[$name])) {
// We have already loaded this module. Don't try to
// do it again with (possibly) different values.
// Försten till kvarn får mala.
@ -58,8 +114,6 @@ class GNUsocial
$files = [
"local/plugins/{$moduleclass}.php",
"local/plugins/{$name}/{$moduleclass}.php",
"modules/{$moduleclass}.php",
"modules/{$name}/{$moduleclass}.php",
"plugins/{$moduleclass}.php",
"plugins/{$name}/{$moduleclass}.php"
];
@ -67,7 +121,7 @@ class GNUsocial
foreach ($files as $file) {
$fullpath = INSTALLDIR . '/' . $file;
if (@file_exists($fullpath)) {
include_once($fullpath);
include_once $fullpath;
break;
}
}
@ -84,7 +138,7 @@ class GNUsocial
}
// Record activated modules for later display/config dump
self::$plugins[$name] = $attrs;
self::$modules[$name] = $attrs;
return true;
}
@ -93,8 +147,8 @@ class GNUsocial
{
// Remove our module if it was previously loaded
$name = ucfirst($name);
if (isset(self::$plugins[$name])) {
unset(self::$plugins[$name]);
if (isset(self::$modules[$name])) {
unset(self::$modules[$name]);
}
// make sure initPlugins will avoid this
@ -107,9 +161,9 @@ class GNUsocial
* Get a list of activated modules in this process.
* @return array of (string $name, array $args) pairs
*/
public static function getActivePlugins()
public static function getActiveModules()
{
return self::$plugins;
return self::$modules;
}
/**
@ -145,7 +199,7 @@ class GNUsocial
self::fillConfigVoids();
self::verifyLoadedConfig();
self::initPlugins();
self::initModules();
}
/**
@ -206,9 +260,9 @@ class GNUsocial
}
/**
* Fire initialization events for all instantiated plugins.
* Fire initialization events for all instantiated modules.
*/
protected static function initPlugins()
protected static function initModules()
{
// User config may have already added some of these modules, with
// maybe configured parameters. The self::addModule function will
@ -216,7 +270,7 @@ class GNUsocial
// Load core modules
foreach (common_config('plugins', 'core') as $name => $params) {
call_user_func('self::addPlugin', $name, $params);
call_user_func('self::addModule', $name, $params);
}
// Load default plugins
@ -245,7 +299,8 @@ class GNUsocial
Event::handle('CheckSchema');
}
// Give modules a chance to initialize in a fully-prepared environment
// Give modules and plugins a chance to initialize in a fully-prepared environment
Event::handle('InitializeModule');
Event::handle('InitializePlugin');
}
@ -310,7 +365,7 @@ class GNUsocial
global $_server, $_path, $config, $_PEAR;
Event::clearHandlers();
self::$plugins = [];
self::$modules = [];
// try to figure out where we are. $server and $path
// can be set by including module, else we guess based

View File

@ -0,0 +1,640 @@
<?php
/*
* GNU Social - a federating social network
* Copyright (C) 2014, Free Software Foundation, 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('GNUSOCIAL')) { exit(1); }
/**
* Superclass for plugins which add Activity types and such
*
* @category Activity
* @package GNUsocial
* @author Mikael Nordfeldth <mmn@hethane.se>
* @copyright 2014 Free Software Foundation, Inc.
* @license http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
* @link http://gnu.io/social
*/
abstract class ActivityHandlerModule extends Module
{
/**
* Returns a key string which represents this activity in HTML classes,
* ids etc, as when offering selection of what type of post to make.
* In MicroAppPlugin, this is paired with the user-visible localizable appTitle().
*
* @return string (compatible with HTML classes)
*/
abstract function tag();
/**
* Return a list of ActivityStreams object type IRIs
* which this micro-app handles. Default implementations
* of the base class will use this list to check if a
* given ActivityStreams object belongs to us, via
* $this->isMyNotice() or $this->isMyActivity.
*
* An empty list means any type is ok. (Favorite verb etc.)
*
* @return array of strings
*/
abstract function types();
/**
* Return a list of ActivityStreams verb IRIs which
* this micro-app handles. Default implementations
* of the base class will use this list to check if a
* given ActivityStreams verb belongs to us, via
* $this->isMyNotice() or $this->isMyActivity.
*
* All micro-app classes must override this method.
*
* @return array of strings
*/
public function verbs() {
return array(ActivityVerb::POST);
}
/**
* Check if a given ActivityStreams activity should be handled by this
* micro-app plugin.
*
* The default implementation checks against the activity type list
* returned by $this->types(), and requires that exactly one matching
* object be present. You can override this method to expand
* your checks or to compare the activity's verb, etc.
*
* @param Activity $activity
* @return boolean
*/
function isMyActivity(Activity $act) {
return (count($act->objects) == 1
&& ($act->objects[0] instanceof ActivityObject)
&& $this->isMyVerb($act->verb)
&& $this->isMyType($act->objects[0]->type));
}
/**
* Check if a given notice object should be handled by this micro-app
* plugin.
*
* The default implementation checks against the activity type list
* returned by $this->types(). You can override this method to expand
* your checks, but follow the execution chain to get it right.
*
* @param Notice $notice
* @return boolean
*/
function isMyNotice(Notice $notice) {
return $this->isMyVerb($notice->verb) && $this->isMyType($notice->object_type);
}
function isMyVerb($verb) {
$verb = $verb ?: ActivityVerb::POST; // post is the default verb
return ActivityUtils::compareVerbs($verb, $this->verbs());
}
function isMyType($type) {
// Third argument to compareTypes is true, to allow for notices with empty object_type for example (verb-only)
return count($this->types())===0 || ActivityUtils::compareTypes($type, $this->types());
}
/**
* Given a parsed ActivityStreams activity, your plugin
* gets to figure out how to actually save it into a notice
* and any additional data structures you require.
*
* This function is deprecated and in the future, Notice::saveActivity
* should be called from onStartHandleFeedEntryWithProfile in this class
* (which instead turns to saveObjectFromActivity).
*
* @param Activity $activity
* @param Profile $actor
* @param array $options=array()
*
* @return Notice the resulting notice
*/
public function saveNoticeFromActivity(Activity $activity, Profile $actor, array $options=array())
{
// Any plugin which has not implemented saveObjectFromActivity _must_
// override this function until they are migrated (this function will
// be deleted when all plugins are migrated to saveObjectFromActivity).
if (isset($this->oldSaveNew)) {
throw new ServerException('A function has been called for new saveActivity functionality, but is still set with an oldSaveNew configuration');
}
return Notice::saveActivity($activity, $actor, $options);
}
/**
* Given a parsed ActivityStreams activity, your plugin gets
* to figure out itself how to store the additional data into
* the database, besides the base data stored by the core.
*
* This will handle just about all events where an activity
* object gets saved, whether it is via AtomPub, OStatus
* (WebSub and Salmon transports), or ActivityStreams-based
* backup/restore of account data.
*
* You should be able to accept as input the output from an
* asActivity() call on the stored object. Where applicable,
* try to use existing ActivityStreams structures and object
* types, and be liberal in accepting input from what might
* be other compatible apps.
*
* All micro-app classes must override this method.
*
* @fixme are there any standard options?
*
* @param Activity $activity
* @param Notice $stored The notice in our database for this certain object
* @param array $options=array()
*
* @return object If the verb handling plugin creates an object, it can be returned here (otherwise true)
* @throws exception On any error.
*/
protected function saveObjectFromActivity(Activity $activity, Notice $stored, array $options=array())
{
throw new ServerException('This function should be abstract when all plugins have migrated to saveObjectFromActivity');
}
/*
* This usually gets called from Notice::saveActivity after a Notice object has been created,
* so it contains a proper id and a uri for the object to be saved.
*/
public function onStoreActivityObject(Activity $act, Notice $stored, array $options, &$object) {
// $this->oldSaveNew is there during a migration period of plugins, to start using
// Notice::saveActivity instead of Notice::saveNew
if (!$this->isMyActivity($act) || isset($this->oldSaveNew)) {
return true;
}
$object = $this->saveObjectFromActivity($act, $stored, $options);
return false;
}
/**
* Given an existing Notice object, your plugin gets to
* figure out how to arrange it into an ActivityStreams
* object.
*
* This will be how your specialized notice gets output in
* Atom feeds and JSON-based ActivityStreams output, including
* account backup/restore and OStatus (WebSub and Salmon transports).
*
* You should be able to round-trip data from this format back
* through $this->saveNoticeFromActivity(). Where applicable, try
* to use existing ActivityStreams structures and object types,
* and consider interop with other compatible apps.
*
* All micro-app classes must override this method.
*
* @fixme this outputs an ActivityObject, not an Activity. Any compat issues?
*
* @param Notice $notice
*
* @return ActivityObject
*/
abstract function activityObjectFromNotice(Notice $notice);
/**
* When a notice is deleted, you'll be called here for a chance
* to clean up any related resources.
*
* All micro-app classes must override this method.
*
* @param Notice $notice
*/
abstract function deleteRelated(Notice $notice);
protected function notifyMentioned(Notice $stored, array &$mentioned_ids)
{
// pass through silently by default
// If we want to stop any other plugin from notifying based on this activity, return false instead.
return true;
}
/**
* Called when generating Atom XML ActivityStreams output from an
* ActivityObject belonging to this plugin. Gives the plugin
* a chance to add custom output.
*
* Note that you can only add output of additional XML elements,
* not change existing stuff here.
*
* If output is already handled by the base Activity classes,
* you can leave this base implementation as a no-op.
*
* @param ActivityObject $obj
* @param XMLOutputter $out to add elements at end of object
*/
function activityObjectOutputAtom(ActivityObject $obj, XMLOutputter $out)
{
// default is a no-op
}
/**
* Called when generating JSON ActivityStreams output from an
* ActivityObject belonging to this plugin. Gives the plugin
* a chance to add custom output.
*
* Modify the array contents to your heart's content, and it'll
* all get serialized out as JSON.
*
* If output is already handled by the base Activity classes,
* you can leave this base implementation as a no-op.
*
* @param ActivityObject $obj
* @param array &$out JSON-targeted array which can be modified
*/
public function activityObjectOutputJson(ActivityObject $obj, array &$out)
{
// default is a no-op
}
/**
* When a notice is deleted, delete the related objects
* by calling the overridable $this->deleteRelated().
*
* @param Notice $notice Notice being deleted
*
* @return boolean hook value
*/
public function onNoticeDeleteRelated(Notice $notice)
{
if ($this->isMyNotice($notice)) {
try {
$this->deleteRelated($notice);
} catch (NoProfileException $e) {
// we failed because of database lookup failure, Notice has no recognized profile as creator
// so we skip this. If we want to remove missing notices we should do a SQL constraints check
// in the affected plugin.
} catch (AlreadyFulfilledException $e) {
// Nothing to see here, it's obviously already gone...
}
}
// Always continue this event in our activity handling plugins.
return true;
}
/**
* @param Notice $stored The notice being distributed
* @param array &$mentioned_ids List of profiles (from $stored->getReplies())
*/
public function onStartNotifyMentioned(Notice $stored, array &$mentioned_ids)
{
if (!$this->isMyNotice($stored)) {
return true;
}
return $this->notifyMentioned($stored, $mentioned_ids);
}
/**
* Render a notice as one of our objects
*
* @param Notice $notice Notice to render
* @param ActivityObject &$object Empty object to fill
*
* @return boolean hook value
*/
function onStartActivityObjectFromNotice(Notice $notice, &$object)
{
if (!$this->isMyNotice($notice)) {
return true;
}
$object = $this->activityObjectFromNotice($notice);
return false;
}
/**
* Handle a posted object from WebSub
*
* @param Activity $activity activity to handle
* @param Profile $actor Profile for the feed
*
* @return boolean hook value
*/
function onStartHandleFeedEntryWithProfile(Activity $activity, Profile $profile, &$notice)
{
if (!$this->isMyActivity($activity)) {
return true;
}
// We are guaranteed to get a Profile back from checkAuthorship (or it throws an exception)
$profile = ActivityUtils::checkAuthorship($activity, $profile);
$object = $activity->objects[0];
$options = array('uri' => $object->id,
'url' => $object->link,
'self' => $object->selfLink,
'is_local' => Notice::REMOTE,
'source' => 'ostatus');
if (!isset($this->oldSaveNew)) {
$notice = Notice::saveActivity($activity, $profile, $options);
} else {
$notice = $this->saveNoticeFromActivity($activity, $profile, $options);
}
return false;
}
/**
* Handle a posted object from Salmon
*
* @param Activity $activity activity to handle
* @param mixed $target user or group targeted
*
* @return boolean hook value
*/
function onStartHandleSalmonTarget(Activity $activity, $target)
{
if (!$this->isMyActivity($activity)) {
return true;
}
if (!isset($this->oldSaveNew)) {
// Handle saveActivity in OStatus class for incoming salmon, remove this event
// handler when all plugins have gotten rid of "oldSaveNew".
return true;
}
$this->log(LOG_INFO, get_called_class()." checking {$activity->id} as a valid Salmon slap.");
if ($target instanceof User_group || $target->isGroup()) {
$uri = $target->getUri();
if (!array_key_exists($uri, $activity->context->attention)) {
// @todo FIXME: please document (i18n).
// TRANS: Client exception thrown when ...
throw new ClientException(_('Object not posted to this group.'));
}
} elseif ($target instanceof Profile && $target->isLocal()) {
$original = null;
// FIXME: Shouldn't favorites show up with a 'target' activityobject?
if (!ActivityUtils::compareVerbs($activity->verb, array(ActivityVerb::POST)) && isset($activity->objects[0])) {
// If this is not a post, it's a verb targeted at something (such as a Favorite attached to a note)
if (!empty($activity->objects[0]->id)) {
$activity->context->replyToID = $activity->objects[0]->id;
}
}
if (!empty($activity->context->replyToID)) {
$original = Notice::getKV('uri', $activity->context->replyToID);
}
if ((!$original instanceof Notice || $original->profile_id != $target->id)
&& !array_key_exists($target->getUri(), $activity->context->attention)) {
// @todo FIXME: Please document (i18n).
// TRANS: Client exception when ...
throw new ClientException(_('Object not posted to this user.'));
}
} else {
// TRANS: Server exception thrown when a micro app plugin uses a target that cannot be handled.
throw new ServerException(_('Do not know how to handle this kind of target.'));
}
$oactor = Ostatus_profile::ensureActivityObjectProfile($activity->actor);
$actor = $oactor->localProfile();
// FIXME: will this work in all cases? I made it work for Favorite...
if (ActivityUtils::compareVerbs($activity->verb, array(ActivityVerb::POST))) {
$object = $activity->objects[0];
} else {
$object = $activity;
}
$options = array('uri' => $object->id,
'url' => $object->link,
'self' => $object->selfLink,
'is_local' => Notice::REMOTE,
'source' => 'ostatus');
$notice = $this->saveNoticeFromActivity($activity, $actor, $options);
return false;
}
/**
* Handle object posted via AtomPub
*
* @param Activity $activity Activity that was posted
* @param Profile $scoped Profile of user posting
* @param Notice &$notice Resulting notice
*
* @return boolean hook value
*/
public function onStartAtomPubNewActivity(Activity $activity, Profile $scoped, Notice &$notice=null)
{
if (!$this->isMyActivity($activity)) {
return true;
}
$options = array('source' => 'atompub');
$notice = $this->saveNoticeFromActivity($activity, $scoped, $options);
return false;
}
/**
* Handle object imported from a backup file
*
* @param User $user User to import for
* @param ActivityObject $author Original author per import file
* @param Activity $activity Activity to import
* @param boolean $trusted Is this a trusted user?
* @param boolean &$done Is this done (success or unrecoverable error)
*
* @return boolean hook value
*/
function onStartImportActivity($user, $author, Activity $activity, $trusted, &$done)
{
if (!$this->isMyActivity($activity)) {
return true;
}
$obj = $activity->objects[0];
$options = array('uri' => $object->id,
'url' => $object->link,
'self' => $object->selfLink,
'source' => 'restore');
// $user->getProfile() is a Profile
$saved = $this->saveNoticeFromActivity($activity,
$user->getProfile(),
$options);
if (!empty($saved)) {
$done = true;
}
return false;
}
/**
* Event handler gives the plugin a chance to add custom
* Atom XML ActivityStreams output from a previously filled-out
* ActivityObject.
*
* The atomOutput method is called if it's one of
* our matching types.
*
* @param ActivityObject $obj
* @param XMLOutputter $out to add elements at end of object
* @return boolean hook return value
*/
function onEndActivityObjectOutputAtom(ActivityObject $obj, XMLOutputter $out)
{
if (in_array($obj->type, $this->types())) {
$this->activityObjectOutputAtom($obj, $out);
}
return true;
}
/**
* Event handler gives the plugin a chance to add custom
* JSON ActivityStreams output from a previously filled-out
* ActivityObject.
*
* The activityObjectOutputJson method is called if it's one of
* our matching types.
*
* @param ActivityObject $obj
* @param array &$out JSON-targeted array which can be modified
* @return boolean hook return value
*/
function onEndActivityObjectOutputJson(ActivityObject $obj, array &$out)
{
if (in_array($obj->type, $this->types())) {
$this->activityObjectOutputJson($obj, $out);
}
return true;
}
public function onStartOpenNoticeListItemElement(NoticeListItem $nli)
{
if (!$this->isMyNotice($nli->notice)) {
return true;
}
$this->openNoticeListItemElement($nli);
Event::handle('EndOpenNoticeListItemElement', array($nli));
return false;
}
public function onStartCloseNoticeListItemElement(NoticeListItem $nli)
{
if (!$this->isMyNotice($nli->notice)) {
return true;
}
$this->closeNoticeListItemElement($nli);
Event::handle('EndCloseNoticeListItemElement', array($nli));
return false;
}
protected function openNoticeListItemElement(NoticeListItem $nli)
{
$id = (empty($nli->repeat)) ? $nli->notice->id : $nli->repeat->id;
$class = 'h-entry notice ' . $this->tag();
if ($nli->notice->scope != 0 && $nli->notice->scope != 1) {
$class .= ' limited-scope';
}
try {
$class .= ' notice-source-'.common_to_alphanumeric($nli->notice->source);
} catch (Exception $e) {
// either source or what we filtered out was a zero-length string
}
$nli->out->elementStart('li', array('class' => $class,
'id' => 'notice-' . $id));
}
protected function closeNoticeListItemElement(NoticeListItem $nli)
{
$nli->out->elementEnd('li');
}
// FIXME: This is overriden in MicroAppPlugin but shouldn't have to be
public function onStartShowNoticeItem(NoticeListItem $nli)
{
if (!$this->isMyNotice($nli->notice)) {
return true;
}
try {
$this->showNoticeListItem($nli);
} catch (Exception $e) {
common_log(LOG_ERR, 'Error showing notice '.$nli->getNotice()->getID().': ' . $e->getMessage());
$nli->out->element('p', 'error', sprintf(_('Error showing notice: %s'), $e->getMessage()));
}
Event::handle('EndShowNoticeItem', array($nli));
return false;
}
protected function showNoticeListItem(NoticeListItem $nli)
{
$nli->showNoticeHeaders();
$nli->showContent();
$nli->showNoticeFooter();
}
public function onStartShowNoticeItemNotice(NoticeListItem $nli)
{
if (!$this->isMyNotice($nli->notice)) {
return true;
}
$this->showNoticeItemNotice($nli);
Event::handle('EndShowNoticeItemNotice', array($nli));
return false;
}
protected function showNoticeItemNotice(NoticeListItem $nli)
{
$nli->showNoticeTitle();
$nli->showAuthor();
$nli->showAddressees();
$nli->showContent();
}
public function onStartShowNoticeContent(Notice $stored, HTMLOutputter $out, Profile $scoped=null)
{
if (!$this->isMyNotice($stored)) {
return true;
}
try {
$this->showNoticeContent($stored, $out, $scoped);
} catch (Exception $e) {
$out->element('div', 'error', $e->getMessage());
}
return false;
}
protected function showNoticeContent(Notice $stored, HTMLOutputter $out, Profile $scoped=null)
{
$out->text($stored->getContent());
}
}

View File

@ -23,7 +23,7 @@ if (!defined('GNUSOCIAL')) { exit(1); }
* @package Activity
* @maintainer Mikael Nordfeldth <mmn@hethane.se>
*/
abstract class ActivityVerbHandlerModule extends ActivityHandlerPlugin
abstract class ActivityVerbHandlerModule extends ActivityHandlerModule
{
public function onActivityVerbTitle(ManagedAction $action, $verb, Notice $target, Profile $scoped, &$title)
{

View File

@ -0,0 +1,82 @@
<?php
/*
* GNU Social - a federating social network
* Copyright (C) 2014, Free Software Foundation, 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('GNUSOCIAL')) { exit(1); }
/**
* @package Activity
* @maintainer Mikael Nordfeldth <mmn@hethane.se>
*/
abstract class ActivityVerbHandlerPlugin extends ActivityHandlerPlugin
{
public function onActivityVerbTitle(ManagedAction $action, $verb, Notice $target, Profile $scoped, &$title)
{
if (!$this->isMyVerb($verb)) {
return true;
}
$title = $this->getActionTitle($action, $verb, $target, $scoped);
return false;
}
abstract protected function getActionTitle(ManagedAction $action, $verb, Notice $target, Profile $scoped);
public function onActivityVerbShowContent(ManagedAction $action, $verb, Notice $target, Profile $scoped)
{
if (!$this->isMyVerb($verb)) {
return true;
}
return $this->showActionContent($action, $verb, $target, $scoped);
}
protected function showActionContent(ManagedAction $action, $verb, Notice $target, Profile $scoped)
{
if (!GNUsocial::isAjax()) {
$nl = new NoticeListItem($target, $action, array('options'=>false, 'attachments'=>false,
'item_tag'=>'div', 'id_prefix'=>'fave'));
$nl->show();
}
$form = $this->getActivityForm($action, $verb, $target, $scoped);
$form->show();
return false;
}
public function onActivityVerbDoPreparation(ManagedAction $action, $verb, Notice $target, Profile $scoped)
{
if (!$this->isMyVerb($verb)) {
return true;
}
return $this->doActionPreparation($action, $verb, $target, $scoped);
}
abstract protected function doActionPreparation(ManagedAction $action, $verb, Notice $target, Profile $scoped);
public function onActivityVerbDoPost(ManagedAction $action, $verb, Notice $target, Profile $scoped)
{
if (!$this->isMyVerb($verb)) {
return true;
}
return $this->doActionPost($action, $verb, $target, $scoped);
}
abstract protected function doActionPost(ManagedAction $action, $verb, Notice $target, Profile $scoped);
abstract protected function getActivityForm(ManagedAction $action, $verb, Notice $target, Profile $scoped);
}

View File

@ -0,0 +1,260 @@
<?php
/**
* StatusNet, the distributed open-source microblogging tool
*
* Superclass for plugins that do authentication and/or authorization
*
* 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 Plugin
* @package StatusNet
* @author Craig Andrews <candrews@integralblue.com>
* @copyright 2009 Free Software Foundation, Inc http://www.fsf.org
* @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
* @link http://status.net/
*/
if (!defined('GNUSOCIAL')) { exit(1); }
/**
* Superclass for plugins that do authentication
*
* @category Module
* @package GNUsocial
* @author Craig Andrews <candrews@integralblue.com>
* @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
* @link http://status.net/
*/
abstract class AuthenticationModule extends Module
{
//is this plugin authoritative for authentication?
public $authoritative = false;
//should accounts be automatically created after a successful login attempt?
public $autoregistration = false;
//can the user change their email address
public $password_changeable=true;
//unique name for this authentication provider
public $provider_name;
//------------Auth plugin should implement some (or all) of these methods------------\\
/**
* Check if a nickname/password combination is valid
* @param username
* @param password
* @return boolean true if the credentials are valid, false if they are invalid.
*/
function checkPassword($username, $password)
{
return false;
}
/**
* Automatically register a user when they attempt to login with valid credentials.
* User::register($data) is a very useful method for this implementation
* @param username username (that is used to login and find the user in the authentication provider) of the user to be registered
* @param nickname nickname of the user in the SN system. If nickname is null, then set nickname = username
* @return mixed instance of User, or false (if user couldn't be created)
*/
function autoRegister($username, $nickname = null)
{
if(is_null($nickname)){
$nickname = $username;
}
$registration_data = array();
$registration_data['nickname'] = $nickname;
return User::register($registration_data);
}
/**
* Change a user's password
* The old password has been verified to be valid by this plugin before this call is made
* @param username
* @param oldpassword
* @param newpassword
* @return boolean true if the password was changed, false if password changing failed for some reason
*/
function changePassword($username,$oldpassword,$newpassword)
{
return false;
}
/**
* Given a username, suggest what the nickname should be
* Used during autoregistration
* Useful if your usernames are ugly, and you want to suggest
* nice looking nicknames when users initially sign on
* All nicknames returned by this function should be valid
* implementations may want to use common_nicknamize() to ensure validity
* @param username
* @return string nickname
*/
function suggestNicknameForUsername($username)
{
return common_nicknamize($username);
}
//------------Below are the methods that connect StatusNet to the implementing Auth plugin------------\\
function onInitializePlugin(){
if(!isset($this->provider_name)){
throw new Exception("must specify a provider_name for this authentication provider");
}
}
/**
* Internal AutoRegister event handler
* @param nickname
* @param provider_name
* @param user - the newly registered user
*/
function onAutoRegister($nickname, $provider_name, &$user)
{
if($provider_name == $this->provider_name && $this->autoregistration){
$suggested_nickname = $this->suggestNicknameForUsername($nickname);
$test_user = User::getKV('nickname', $suggested_nickname);
if($test_user) {
//someone already exists with the suggested nickname, so used the passed nickname
$suggested_nickname = common_nicknamize($nickname);
}
$test_user = User::getKV('nickname', $suggested_nickname);
if($test_user) {
//someone already exists with the suggested nickname
//not much else we can do
}else{
$user = $this->autoRegister($nickname, $suggested_nickname);
if ($user instanceof User) {
User_username::register($user,$nickname,$this->provider_name);
return false;
}
}
}
}
function onStartCheckPassword($nickname, $password, &$authenticatedUser){
//map the nickname to a username
$user_username = new User_username();
$user_username->username=$nickname;
$user_username->provider_name=$this->provider_name;
if($user_username->find() && $user_username->fetch()){
$authenticated = $this->checkPassword($user_username->username, $password);
if($authenticated){
$authenticatedUser = User::getKV('id', $user_username->user_id);
return false;
}
}else{
//$nickname is the username used to login
//$suggested_nickname is the nickname the auth provider suggests for that username
$suggested_nickname = $this->suggestNicknameForUsername($nickname);
$user = User::getKV('nickname', $suggested_nickname);
if($user){
//make sure this user isn't claimed
$user_username = new User_username();
$user_username->user_id=$user->id;
$we_can_handle = false;
if($user_username->find()){
//either this provider, or another one, has already claimed this user
//so we cannot. Let another plugin try.
return;
}else{
//no other provider claims this user, so it's safe for us to handle it
$authenticated = $this->checkPassword($nickname, $password);
if($authenticated){
$authenticatedUser = $user;
User_username::register($authenticatedUser,$nickname,$this->provider_name);
return false;
}
}
}else{
$authenticated = $this->checkPassword($nickname, $password);
if($authenticated){
if(! Event::handle('AutoRegister', array($nickname, $this->provider_name, &$authenticatedUser))){
//unlike most Event::handle lines of code, this one has a ! (not)
//we want to do this if the event *was* handled - this isn't a "default" implementation
//like most code of this form.
if($authenticatedUser){
return false;
}
}
}
}
}
if($this->authoritative){
return false;
}else{
//we're not authoritative, so let other handlers try
return;
}
}
function onStartChangePassword(Profile $target ,$oldpassword, $newpassword)
{
if($this->password_changeable){
$user_username = new User_username();
$user_username->user_id = $target->getID();
$user_username->provider_name=$this->provider_name;
if ($user_username->find(true)) {
$authenticated = $this->checkPassword($user_username->username, $oldpassword);
if($authenticated){
$result = $this->changePassword($user_username->username,$oldpassword,$newpassword);
if($result){
//stop handling of other handlers, because what was requested was done
return false;
}else{
// TRANS: Exception thrown when a password change fails.
throw new Exception(_('Password changing failed.'));
}
}else{
if($this->authoritative){
//since we're authoritative, no other plugin could do this
// TRANS: Exception thrown when a password change fails.
throw new Exception(_('Password changing failed.'));
}else{
//let another handler try
return null;
}
}
}
}else{
if($this->authoritative){
//since we're authoritative, no other plugin could do this
// TRANS: Exception thrown when a password change attempt fails because it is not allowed.
throw new Exception(_('Password changing is not allowed.'));
}
}
}
function onStartAccountSettingsPasswordMenuItem($widget)
{
if($this->authoritative && !$this->password_changeable){
//since we're authoritative, no other plugin could change passwords, so do not render the menu item
return false;
}
}
function onCheckSchema() {
$schema = Schema::get();
$schema->ensureTable('user_username', User_username::schemaDef());
return true;
}
function onUserDeleteRelated($user, &$tables)
{
$tables[] = 'User_username';
return true;
}
}

View File

@ -48,7 +48,7 @@ if (!defined('STATUSNET')) {
* @license http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
* @link http://status.net/
*/
abstract class MicroAppModule extends ActivityHandlerPlugin
abstract class MicroAppPlugin extends ActivityHandlerPlugin
{
/**
* Returns a localized string which represents this micro-app,

221
lib/modules/Module.php Normal file
View File

@ -0,0 +1,221 @@
<?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/>.
defined('GNUSOCIAL') || die();
/**
* Base class for modules
*
* A base class for GNU social modules. Mostly a light wrapper around
* the Event framework.
*
* Subclasses of Module will automatically handle an event if they define
* a method called "onEventName". (Well, OK -- only if they call parent::__construct()
* in their constructors.)
*
* They will also automatically handle the InitializeModule and CleanupModule with the
* initialize() and cleanup() methods, respectively.
*
* @category Module
* @package GNUsocial
* @author Evan Prodromou <evan@status.net>
* @copyright 2010-2019 Free Software Foundation, Inc http://www.fsf.org
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*
* @see Event
*/
class Module
{
public function __construct()
{
Event::addHandler('InitializeModule', [$this, 'initialize']);
Event::addHandler('CleanupModule', [$this, 'cleanup']);
foreach (get_class_methods($this) as $method) {
if (mb_substr($method, 0, 2) == 'on') {
Event::addHandler(mb_substr($method, 2), [$this, $method]);
}
}
$this->setupGettext();
}
public function initialize()
{
return true;
}
public function cleanup()
{
return true;
}
/**
* Load related components when needed
*
* Most non-trivial plugins will require extra components to do their work. Typically
* 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. By
* tradition, action classes typically have files named for the action, all lower-case.
* Data classes are in files with the data class name, initial letter capitalized.
*
* Note that this method will be called for *all* overloaded classes, not just ones
* in this plugin! So, make sure to return true by default to let other plugins, and
* the core code, get a chance.
*
* @param string $cls Name of the class to be loaded
*
* @return bool hook value; true means continue processing, false means stop.
*/
public function onAutoload($cls)
{
$cls = basename($cls);
$basedir = INSTALLDIR . '/modules/' . mb_substr(get_called_class(), 0, -6);
$file = null;
if (preg_match('/^(\w+)(Action|Form)$/', $cls, $type)) {
$type = array_map('strtolower', $type);
$file = "{$basedir}/{$type[2]}s/{$type[1]}.php";
}
if (!file_exists($file)) {
$file = "{$basedir}/classes/{$cls}.php";
// library files can be put into subdirs ('_'->'/' conversion)
// such as LRDDMethod_WebFinger -> lib/lrddmethod/webfinger.php
if (!file_exists($file)) {
$type = strtolower($cls);
$type = str_replace('_', '/', $type);
$file = "{$basedir}/lib/{$type}.php";
}
}
if (!is_null($file) && file_exists($file)) {
require_once $file;
return false;
}
return true;
}
/**
* Checks if this plugin has localization that needs to be set up.
* Gettext localizations can be called via the _m() helper function.
*/
protected function setupGettext()
{
$class = get_class($this);
if (substr($class, -6) == 'Module') {
$name = substr($class, 0, -6);
$path = common_config('plugins', 'locale_path');
if (!$path) {
// @fixme this will fail for things installed in local/plugins
// ... but then so will web links so far.
$path = INSTALLDIR . "/modules/{$name}/locale";
}
if (file_exists($path) && is_dir($path)) {
bindtextdomain($name, $path);
bind_textdomain_codeset($name, 'UTF-8');
}
}
}
protected function log($level, $msg)
{
common_log($level, get_class($this) . ': ' . $msg);
}
protected function debug($msg)
{
$this->log(LOG_DEBUG, $msg);
}
public function name()
{
$cls = get_class($this);
return mb_substr($cls, 0, -6);
}
public function version()
{
return GNUSOCIAL_VERSION;
}
protected function userAgent()
{
return HTTPClient::userAgent()
. ' (' . get_class($this) . ' v' . $this->version() . ')';
}
public function onModuleVersion(array &$versions): bool
{
$name = $this->name();
$versions[] = [
'name' => $name,
// TRANS: Displayed as version information for a plugin if no version information was found.
'version' => _m('Unknown')
];
return true;
}
public static function staticPath($module, $relative)
{
if (GNUsocial::useHTTPS()) {
$server = common_config('plugins', 'sslserver');
} else {
$server = common_config('plugins', 'server');
}
if (empty($server)) {
if (GNUsocial::useHTTPS()) {
$server = common_config('site', 'sslserver');
}
if (empty($server)) {
$server = common_config('site', 'server');
}
}
if (GNUsocial::useHTTPS()) {
$path = common_config('plugins', 'sslpath');
} else {
$path = common_config('plugins', 'path');
}
if (empty($path)) {
$path = common_config('site', 'path') . '/modules/';
}
if ($path[strlen($path) - 1] != '/') {
$path .= '/';
}
if ($path[0] != '/') {
$path = '/' . $path;
}
$protocol = GNUsocial::useHTTPS() ? 'https' : 'http';
return $protocol . '://' . $server . $path . $module . '/' . $relative;
}
public function path($relative)