Compare commits

..
Author SHA1 Message Date
Valentin Popov a81530d0d7 refactor: remove cross-component runtime dependencies
Moodle Plugin CI / test (push) Successful in 3m20s
2026-08-12 17:53:02 +00:00
Valentin Popov 0d4bf6a208 style: apply Moodle coding standards
Moodle Plugin CI / test (push) Successful in 1m27s
2026-08-12 17:13:30 +00:00
Valentin Popov 91111b66d3 fix(ci): copy plugin into test image
Moodle Plugin CI / test (push) Failing after 1m44s
2026-08-12 17:07:32 +00:00
Valentin Popov d35ce9b445 ci: add Moodle 5.2 Docker checks 2026-08-12 16:57:33 +00:00
Valentin Popov 482d15db8f Bump version
Signed-off-by: Valentin Popov <info@valentineus.link>
2020-05-16 01:59:03 +04:00
Valentin PopovandGitHub 9d70f553bb Merge pull request #19 from catalyst/requires-v3.0.0-stable
Set minimum required version to Moodle 3.7.0
2020-05-16 00:57:28 +04:00
Valentin PopovandGitHub b77e2a2cdb Merge pull request #18 from catalyst/issue15-v3.0.0-stable
Add null privacy provider to fix #15
2020-05-16 00:56:45 +04:00
Dmitrii Metelkin f89cdba127 Set minimum required version to Moodle 3.7.0 2020-04-22 09:21:33 +10:00
Dmitrii Metelkin 1acd3ef21d Add null privacy provider to fix #15 2020-04-22 09:16:57 +10:00
Valentin Popov 3f74278add Bump 3.0.4 version
Signed-off-by: Valentin Popov <info@valentineus.link>
2020-04-14 13:32:14 +04:00
Valentin Popov 4e64c0bcd2 Version fix
Signed-off-by: Valentin Popov <info@valentineus.link>
2019-02-17 03:38:45 +04:00
Valentin Popov 835f5516e8 Correction problem tag display
Signed-off-by: Valentin Popov <info@valentineus.link>
2019-02-17 03:36:52 +04:00
Valentin Popov 833434c5ba Formatting code
Signed-off-by: Valentin Popov <info@valentineus.link>
2019-02-17 03:34:52 +04:00
Valentin Popov 8eda3bc6bb Version update
Signed-off-by: Valentin Popov <info@valentineus.link>
2018-11-02 02:51:29 +04:00
Valentin Popov 9cb5bd0760 Bug fixes
Signed-off-by: Valentin Popov <info@valentineus.link>
2018-11-02 02:38:31 +04:00
Valentin Popov 2f04aeab6d Correction of possible problems
Signed-off-by: Valentin Popov <info@valentineus.link>
2018-11-02 02:06:47 +04:00
Valentin Popov 849d7126d8 Correction of work with event names
Signed-off-by: Valentin Popov <info@valentineus.link>
2018-11-02 02:03:17 +04:00
Valentin Popov d8f3a9f3ed Formatting code and eliminating possible errors
Signed-off-by: Valentin Popov <info@valentineus.link>
2018-11-02 01:07:14 +04:00
Valentin Popov f9772b1fb9 Fix check MOODLE_INTERNAL
Signed-off-by: Valentin Popov <info@valentineus.link>
2018-06-19 22:22:45 +04:00
Valentin Popov 3fa97bad31 Fix error install.xml
Signed-off-by: Valentin Popov <info@valentineus.link>
2018-06-19 19:49:00 +04:00
40 changed files with 1686 additions and 2503 deletions
+38
View File
@@ -0,0 +1,38 @@
FROM composer:2.10.2@sha256:4d71c3c2109c61d5415544264b59ad4087e4c5b7244481723664138fd36d5040 AS composer
FROM node:22.23.2-bookworm-slim@sha256:d649c27dae7ba0137b3cef5dd75baa422c08dc3d9e3fc0c23dfb172dc3cc6436 AS node
FROM moodlehq/moodle-php-apache:8.4@sha256:07cac70e0ed3f96f334ffeece92075b98adfbe4110312a3a9308b95eab8e2080
ARG MOODLE_PLUGIN_CI_COMMIT=9276f968746960275b12190b4ef8e47b1e6af674
ARG MOODLE_PLUGIN_CI_LOCK_SHA256=e5c8ce77b90f43a057ee717c52e856bf81d43387834dab36083a1c1b17a24be4
COPY --from=composer /usr/bin/composer /usr/local/bin/composer
COPY --from=node /usr/local/bin/node /usr/local/bin/node
COPY --from=node /usr/local/lib/node_modules /usr/local/lib/node_modules
RUN ln -s /usr/local/lib/node_modules/npm/bin/npm-cli.js /usr/local/bin/npm \
&& ln -s /usr/local/lib/node_modules/npm/bin/npx-cli.js /usr/local/bin/npx \
&& apt-get update \
&& DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends postgresql-client \
&& rm -rf /var/lib/apt/lists/* \
&& locale-gen en_AU.UTF-8 \
&& git init /opt/moodle-plugin-ci \
&& git -C /opt/moodle-plugin-ci remote add origin https://github.com/moodlehq/moodle-plugin-ci.git \
&& git -C /opt/moodle-plugin-ci fetch --depth 1 origin "${MOODLE_PLUGIN_CI_COMMIT}" \
&& git -C /opt/moodle-plugin-ci checkout --detach FETCH_HEAD \
&& test "$(git -C /opt/moodle-plugin-ci rev-parse HEAD)" = "${MOODLE_PLUGIN_CI_COMMIT}" \
&& echo "${MOODLE_PLUGIN_CI_LOCK_SHA256} /opt/moodle-plugin-ci/composer.lock" | sha256sum --check \
&& COMPOSER_ALLOW_SUPERUSER=1 composer install \
--working-dir=/opt/moodle-plugin-ci \
--no-dev \
--no-interaction \
--prefer-dist \
--classmap-authoritative \
&& ln -s /opt/moodle-plugin-ci/bin/moodle-plugin-ci /usr/local/bin/moodle-plugin-ci
COPY . /plugin
ENV LANG=en_AU.UTF-8
WORKDIR /workspace
+11
View File
@@ -0,0 +1,11 @@
.git
.github
.gitea
.docker
.dockerignore
.env
.env.*
compose.yaml
node_modules
vendor
*.log
+31
View File
@@ -0,0 +1,31 @@
name: Moodle Plugin CI
on:
push:
branches:
- develop
- main
pull_request:
workflow_dispatch:
permissions:
contents: read
jobs:
test:
runs-on: ubuntu-latest
env:
COMPOSE_PROJECT_NAME: local_webhooks_${{ gitea.run_id }}_${{ gitea.run_attempt }}
steps:
- name: Check out repository
uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
- name: Build test image
run: docker compose build --pull ci
- name: Test plugin
run: docker compose up --abort-on-container-exit --exit-code-from ci
- name: Clean up
if: always()
run: docker compose down --volumes --remove-orphans
-54
View File
@@ -1,54 +0,0 @@
language: php
sudo: true
addons:
firefox: "latest-esr"
postgresql: "9.6"
apt:
packages:
- "mysql-client-5.6"
- "mysql-client-core-5.6"
- "mysql-server-5.6"
- "openjdk-8-jre-headless"
cache:
directories:
- "$HOME/.composer/cache"
- "$HOME/.npm"
php:
- "7.0"
- "7.1"
- "7.2"
env:
matrix:
- MOODLE_BRANCH=MOODLE_35_STABLE DB=mysqli
- MOODLE_BRANCH=MOODLE_35_STABLE DB=pgsql
- MOODLE_BRANCH=MOODLE_36_STABLE DB=mysqli
- MOODLE_BRANCH=MOODLE_36_STABLE DB=pgsql
before_install:
- phpenv config-rm xdebug.ini
- nvm install 8.9
- nvm use 8.9
- cd ../..
- composer selfupdate
- composer create-project -n --no-dev --prefer-dist moodlerooms/moodle-plugin-ci ci ^2
- export PATH="$(cd ci/bin; pwd):$(cd ci/vendor/bin; pwd):$PATH"
install:
- moodle-plugin-ci install
script:
- moodle-plugin-ci phplint
- moodle-plugin-ci phpcpd
- moodle-plugin-ci phpmd
- moodle-plugin-ci codechecker
- moodle-plugin-ci validate
- moodle-plugin-ci savepoints
- moodle-plugin-ci mustache
- moodle-plugin-ci grunt
- moodle-plugin-ci phpunit
- moodle-plugin-ci behat
+20 -4
View File
@@ -20,11 +20,27 @@ Features:
* Use a secret phrase to authenticate requests;
* [JSON](https://en.wikipedia.org/wiki/JSON) - Format of outgoing data;
## Documentation
## Installation
* [Install the plugin](docs/getting-started.md#installation).
* [User guide](docs/getting-started.md#user-guide).
* [Request format](docs/getting-started.md#request-format).
Get the installation package in any of the available methods:
* [GitHub Releases](https://github.com/valentineus/moodle-webhooks/releases).
* [Compilation from the source code](#build).
## Build
Self-assembly package is as follows:
* Clone the repository:
```bash
git clone https://github.com/valentineus/moodle-webhooks.git moodle-webhooks
```
* Run the build script:
```bash
cd ./moodle-webhooks
/bin/sh build.sh
```
## License
+20 -9
View File
@@ -1,21 +1,32 @@
#!/bin/sh
# Author: Valentin Popov
# Email: info@valentineus.link
# Date: 2017-10-19
# Usage: /bin/sh build.sh
# Date: 2018-06-19
# Usage: /bin/sh ./build.sh
# Description: Build the final package for installation in Moodle.
# Updating the Environment
PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
export PATH="$PATH:/usr/local/scripts"
# Build the package
cd ..
mv "./moodle-webhooks" "./local_webhooks"
zip -9 -r "local_webhooks.zip" "local_webhooks" \
-x "local_webhooks/.git*" \
-x "local_webhooks/.travis.yml" \
-x "local_webhooks/build.sh"
# Current project
PROJECT="local_webhooks"
# Defining directories
DIRECTORY="$(pwd)"
NAMEDIR="$(basename $DIRECTORY)"
TMPDIR="$(mktemp --directory)"
# Creating a Temporary Directory
cp --recursive --verbose "../$NAMEDIR" "$TMPDIR/$PROJECT"
mkdir --parents --verbose "$DIRECTORY/build"
cd "$TMPDIR"
# Creating an archive
zip -9 -r "$DIRECTORY/build/$PROJECT.zip" "$PROJECT" \
-x "$PROJECT/.git*" \
-x "$PROJECT/.travis.yml" \
-x "$PROJECT/build*"
# End of work
exit 0
+72
View File
@@ -0,0 +1,72 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Registration of the system of events.
*
* @package local_webhooks
* @copyright 2017 "Valentin Popov" <info@valentineus.link>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace local_webhooks\event;
use core\event\base;
use moodle_url;
/**
* Defines how to work with events.
*
* @copyright 2017 "Valentin Popov" <info@valentineus.link>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class backup_performed extends base {
/**
* Return localised event name.
*
* @throws \coding_exception
*/
public static function get_name() {
return get_string('create', 'local_webhooks');
}
/**
* Returns description of what happened.
*
* @throws \coding_exception
*/
public function get_description() {
return get_string('backup', 'local_webhooks');
}
/**
* Get URL related to the action.
*
* @throws \moodle_exception
*/
public function get_url() {
return new moodle_url('/local/webhooks/index.php');
}
/**
* Init method.
*/
protected function init() {
$this->data['crud'] = 'c';
$this->data['edulevel'] = self::LEVEL_OTHER;
$this->data['objecttable'] = 'local_webhooks_service';
}
}
+72
View File
@@ -0,0 +1,72 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Registration of the system of events.
*
* @package local_webhooks
* @copyright 2017 "Valentin Popov" <info@valentineus.link>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace local_webhooks\event;
use core\event\base;
use moodle_url;
/**
* Defines how to work with events.
*
* @copyright 2017 "Valentin Popov" <info@valentineus.link>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class backup_restored extends base {
/**
* Return localised event name.
*
* @throws \coding_exception
*/
public static function get_name() {
return get_string('update', 'local_webhooks');
}
/**
* Returns description of what happened.
*
* @throws \coding_exception
*/
public function get_description() {
return get_string('backupfinished', 'local_webhooks');
}
/**
* Get URL related to the action.
*
* @throws \moodle_exception
*/
public function get_url() {
return new moodle_url('/local/webhooks/index.php');
}
/**
* Init method.
*/
protected function init() {
$this->data['crud'] = 'u';
$this->data['edulevel'] = self::LEVEL_OTHER;
$this->data['objecttable'] = 'local_webhooks_service';
}
}
+70
View File
@@ -0,0 +1,70 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Registration of the system of events.
*
* @package local_webhooks
* @copyright 2017 "Valentin Popov" <info@valentineus.link>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace local_webhooks\event;
use core\event\base;
use moodle_url;
/**
* Defines how to work with events.
*
* @copyright 2017 "Valentin Popov" <info@valentineus.link>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class response_answer extends base {
/**
* Return localised event name.
*
* @throws \coding_exception
*/
public static function get_name() {
return get_string('answer', 'local_webhooks');
}
/**
* Returns description of what happened.
*/
public function get_description() {
return $this->other['status'];
}
/**
* Get URL related to the action.
*
* @throws \moodle_exception
*/
public function get_url() {
return new moodle_url('/local/webhooks/editservice.php', ['serviceid' => $this->objectid]);
}
/**
* Init method.
*/
protected function init() {
$this->data['crud'] = 'r';
$this->data['edulevel'] = self::LEVEL_OTHER;
$this->data['objecttable'] = 'local_webhooks_service';
}
}
+72
View File
@@ -0,0 +1,72 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Registration of the system of events.
*
* @package local_webhooks
* @copyright 2017 "Valentin Popov" <info@valentineus.link>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace local_webhooks\event;
use core\event\base;
use moodle_url;
/**
* Defines how to work with events.
*
* @copyright 2017 "Valentin Popov" <info@valentineus.link>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class service_added extends base {
/**
* Return localised event name.
*
* @throws \coding_exception
*/
public static function get_name() {
return get_string('create', 'local_webhooks');
}
/**
* Returns description of what happened.
*
* @throws \coding_exception
*/
public function get_description() {
return get_string('eventwebserviceservicecreated', 'local_webhooks');
}
/**
* Get URL related to the action.
*
* @throws \moodle_exception
*/
public function get_url() {
return new moodle_url('/local/webhooks/editservice.php', ['serviceid' => $this->objectid]);
}
/**
* Init method.
*/
protected function init() {
$this->data['crud'] = 'c';
$this->data['edulevel'] = self::LEVEL_OTHER;
$this->data['objecttable'] = 'local_webhooks_service';
}
}
+72
View File
@@ -0,0 +1,72 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Registration of the system of events.
*
* @package local_webhooks
* @copyright 2017 "Valentin Popov" <info@valentineus.link>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace local_webhooks\event;
use core\event\base;
use moodle_url;
/**
* Defines how to work with events.
*
* @copyright 2017 "Valentin Popov" <info@valentineus.link>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class service_deleted extends base {
/**
* Return localised event name.
*
* @throws \coding_exception
*/
public static function get_name() {
return get_string('deleted', 'local_webhooks');
}
/**
* Returns description of what happened.
*
* @throws \coding_exception
*/
public function get_description() {
return get_string('eventwebserviceservicedeleted', 'local_webhooks');
}
/**
* Get URL related to the action.
*
* @throws \moodle_exception
*/
public function get_url() {
return new moodle_url('/local/webhooks/index.php');
}
/**
* Init method.
*/
protected function init() {
$this->data['crud'] = 'd';
$this->data['edulevel'] = self::LEVEL_OTHER;
$this->data['objecttable'] = 'local_webhooks_service';
}
}
+72
View File
@@ -0,0 +1,72 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Registration of the system of events.
*
* @package local_webhooks
* @copyright 2017 "Valentin Popov" <info@valentineus.link>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace local_webhooks\event;
use core\event\base;
use moodle_url;
/**
* Defines how to work with events.
*
* @copyright 2017 "Valentin Popov" <info@valentineus.link>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class service_updated extends base {
/**
* Return localised event name.
*
* @throws \coding_exception
*/
public static function get_name() {
return get_string('update', 'local_webhooks');
}
/**
* Returns description of what happened.
*
* @throws \coding_exception
*/
public function get_description() {
return get_string('eventwebserviceserviceupdated', 'local_webhooks');
}
/**
* Get URL related to the action.
*
* @throws \moodle_exception
*/
public function get_url() {
return new moodle_url('/local/webhooks/editservice.php', ['serviceid' => $this->objectid]);
}
/**
* Init method.
*/
protected function init() {
$this->data['crud'] = 'u';
$this->data['edulevel'] = self::LEVEL_OTHER;
$this->data['objecttable'] = 'local_webhooks_service';
}
}
+107
View File
@@ -0,0 +1,107 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* The event handler.
*
* @package local_webhooks
* @copyright 2017 "Valentin Popov" <info@valentineus.link>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace local_webhooks;
defined('MOODLE_INTERNAL') || die();
global $CFG;
require_once(__DIR__ . '/../lib.php');
require_once(__DIR__ . '/../locallib.php');
require_once($CFG->libdir . '/filelib.php');
use curl;
use local_webhooks_events;
/**
* Defines how to work with events.
*
* @copyright 2017 "Valentin Popov" <info@valentineus.link>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class handler {
/**
* External handler.
*
* @param object $event
*
* @throws \dml_exception
* @throws \coding_exception
*/
public static function events($event) {
$data = $event->get_data();
if (!empty($callbacks = local_webhooks_get_list_records())) {
foreach ($callbacks as $callback) {
self::handler_callback($data, $callback);
}
}
}
/**
* Processes each callback.
*
* @param array $data
* @param object $callback
*
* @throws \coding_exception
* @throws \dml_exception
*/
private static function handler_callback($data, $callback) {
global $CFG;
if ((bool) $callback->enable && !empty($callback->events[$data['eventname']])) {
$urlparse = parse_url($CFG->wwwroot);
$data['host'] = $urlparse['host'];
$data['token'] = $callback->token;
$data['extra'] = $callback->other;
self::send($data, $callback);
}
}
/**
* Sending data to the node.
*
* @param array $data
* @param object $callback
*
* @return array
* @throws \coding_exception
* @throws \dml_exception
*/
private static function send($data, $callback) {
$curl = new curl();
$curl->setHeader(['Content-Type: application/' . $callback->type]);
$curl->post($callback->url, json_encode($data));
$response = $curl->getResponse();
local_webhooks_events::response_answer($callback->id, $response);
return $response;
}
}
-361
View File
@@ -1,361 +0,0 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
namespace local_webhooks\local;
defined('MOODLE_INTERNAL') || die();
define('LW_TABLE_EVENTS', 'local_webhooks_events');
define('LW_TABLE_SERVICES', 'local_webhooks_service');
global $CFG;
require_once($CFG->dirroot . '/local/webhooks/classes/local/record.php');
use coding_exception;
use core_component;
use ReflectionClass;
use function define;
use function defined;
use function is_array;
use function is_int;
use function is_object;
use function is_string;
use function strlen;
/**
* The main class for the plugin.
*
* @copyright 2019 'Valentin Popov' <info@valentineus.link>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @package local_webhooks\local
*/
final class api {
/**
* Create a new record in the database.
*
* @param \local_webhooks\local\record $record
*
* @return int
*
* @throws \coding_exception
* @throws \dml_exception
*/
public static function add_service(record $record): int {
global $DB;
$id = $DB->insert_record(LW_TABLE_SERVICES, $record);
if (is_int($id) && is_array($record->events)) {
$DB->insert_records(LW_TABLE_EVENTS, array_map(static function (string $name) use ($id) {
return ['name' => $name, 'serviceid' => $id];
}, $record->events));
}
if (!is_int($id)) {
throw new coding_exception('Variable \'id\' must be type \'Integer\'');
}
return $id;
}
/**
* Delete an existing record in the database.
*
* @param int $id
*
* @return bool
*
* @throws \dml_exception
*/
public static function del_service(int $id): bool {
global $DB;
$DB->delete_records(LW_TABLE_EVENTS, ['serviceid' => $id]);
return $DB->delete_records(LW_TABLE_SERVICES, ['id' => $id]);
}
/**
* Get an event's list.
*
* @return array
*
* @throws \ReflectionException
*/
public static function get_events(): array {
return array_merge(self::get_core_events_list(), self::get_non_core_event_list());
}
/**
* Get an existing record from the database.
*
* @param int $id
*
* @return \local_webhooks\local\record
*
* @throws \dml_exception
*/
public static function get_service(int $id): record {
global $DB;
$record = $DB->get_record(LW_TABLE_SERVICES, ['id' => $id], '*', MUST_EXIST);
$events = $DB->get_records(LW_TABLE_EVENTS, ['serviceid' => $id]);
$service = new record();
$service->events = array_column($events, 'name');
$service->header = $record->header;
$service->id = $record->id;
$service->name = $record->name;
$service->point = $record->point;
$service->status = $record->status;
$service->token = $record->token;
return $service;
}
/**
* Get list records from the database.
*
* @param array|null $conditions
* @param string|null $sort
* @param int|null $from
* @param int|null $limit
*
* @return array
*
* @throws \dml_exception
*/
public static function get_services(array $conditions = null, string $sort = null, int $from = null, int $limit = null): array {
global $DB;
$records = $DB->get_records(LW_TABLE_SERVICES, $conditions ?? [], $sort ?? '', '*', $from ?? 0, $limit ?? 0);
$services = [];
foreach ($records as $record) {
if (!is_object($record)) {
continue;
}
$events = $DB->get_records(LW_TABLE_EVENTS, ['serviceid' => $record->id]);
$service = new record();
$service->events = array_column($events, 'name');
$service->header = $record->header;
$service->id = $record->id;
$service->name = $record->name;
$service->point = $record->point;
$service->status = $record->status;
$service->token = $record->token;
$services[] = $service;
}
return $services;
}
/**
* Get list records from the database by the event's name.
*
* @param string $name
*
* @return \local_webhooks\local\record[]
*
* @throws \dml_exception
*/
public static function get_services_by_event(string $name): array {
global $DB;
$events = $DB->get_records(LW_TABLE_EVENTS, ['name' => $name]);
$services = [];
foreach ($events as $event) {
if (!is_object($event)) {
continue;
}
$services[] = self::get_service($event->serviceid);
}
return $services;
}
/**
* Get a total count of existing records.
*
* @return int
*
* @throws \dml_exception
*/
public static function get_total_count(): int {
global $DB;
return $DB->count_records(LW_TABLE_SERVICES);
}
/**
* Update an existing record in the database.
*
* @param \local_webhooks\local\record $service
*
* @return bool
*
* @throws \coding_exception
* @throws \dml_exception
*/
public static function set_service(record $service): bool {
global $DB;
$result = $DB->update_record(LW_TABLE_SERVICES, $service);
$DB->delete_records(LW_TABLE_EVENTS, ['serviceid' => $service->id]);
if ($result && is_array($service->events)) {
$DB->insert_records(LW_TABLE_EVENTS, array_map(static function (string $name) use ($service) {
return ['name' => $name, 'serviceid' => $service->id];
}, $service->events));
}
return $result;
}
/**
* Get a system's events list.
*
* @return array
*
* @throws \ReflectionException
*/
private static function get_core_events_list(): array {
global $CFG;
$debugdeveloper = $CFG->debugdeveloper;
$debugdisplay = $CFG->debugdisplay;
$debuglevel = $CFG->debug;
$CFG->debug = 0;
$CFG->debugdeveloper = false;
$CFG->debugdisplay = false;
$directory = $CFG->libdir . '/classes/event';
$events = [];
$files = self::get_file_list($directory);
if (isset($files['unknown_logged'])) {
unset($files['unknown_logged']);
}
foreach (array_keys($files) as $file) {
$name = '\\core\\event\\' . $file;
if (method_exists($name, 'get_static_info')) {
$class = new ReflectionClass($name);
if ($file !== 'manager' && !$class->isAbstract()) {
$events[$name] = $name::get_static_info();
}
}
}
$CFG->debug = $debuglevel;
$CFG->debugdeveloper = $debugdeveloper;
$CFG->debugdisplay = $debugdisplay;
return $events;
}
/**
* Get a file's list in the directory.
*
* @param string $directory
*
* @return array
*/
private static function get_file_list(string $directory): array {
global $CFG;
$files = [];
$root = $CFG->dirroot;
if (is_dir($directory) && is_readable($directory)) {
$handle = opendir($directory);
if ($handle) {
foreach (scandir($directory, SCANDIR_SORT_NONE) as $file) {
if ($file !== '.' && $file !== '..' && strrpos($directory, $root) !== false) {
$location = substr($directory, strlen($root));
$eventname = substr($file, 0, -4);
if (is_string($eventname)) {
$files[$eventname] = $location . '/' . $file;
}
}
}
}
}
return $files;
}
/**
* Get a plugins' events list.
*
* @return array
*
* @throws \ReflectionException
*/
private static function get_non_core_event_list(): array {
global $CFG;
$debugdeveloper = $CFG->debugdeveloper;
$debugdisplay = $CFG->debugdisplay;
$debuglevel = $CFG->debug;
$CFG->debug = 0;
$CFG->debugdeveloper = false;
$CFG->debugdisplay = false;
$events = [];
foreach (array_keys(core_component::get_plugin_types()) as $type) {
foreach (core_component::get_plugin_list($type) as $plugin => $directory) {
$directory .= '/classes/event';
$files = self::get_file_list($directory);
if (isset($files['unknown_logged'])) {
unset($files['unknown_logged']);
}
foreach (array_keys($files) as $file) {
$name = '\\' . $type . '_' . $plugin . '\\event\\' . $file;
if (method_exists($name, 'get_static_info')) {
$class = new ReflectionClass($name);
if ($type . '_' . $plugin !== 'logstore_legacy' && !$class->isAbstract()) {
$events[$name] = $name::get_static_info();
}
}
}
}
}
$CFG->debug = $debuglevel;
$CFG->debugdeveloper = $debugdeveloper;
$CFG->debugdisplay = $debugdisplay;
return $events;
}
}
-95
View File
@@ -1,95 +0,0 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
namespace local_webhooks\local;
defined('MOODLE_INTERNAL') || die();
use stdClass;
use function defined;
/**
* It's a class description record.
*
* @copyright 2019 'Valentin Popov' <info@valentineus.link>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @package local_webhooks\local
*/
final class record extends stdClass {
/**
* List of some events.
*
* @var array|null
*/
public $events;
/**
* Type of the package.
*
* @var string
*/
public $header;
/**
* A unique identifier of the service.
*
* @var int|null
*/
public $id;
/**
* Name of the service.
*
* @var string
*/
public $name;
/**
* Url's an endpoint to send notifications.
*
* @var string
*/
public $point;
/**
* Status activity of the service.
*
* @var bool
*/
public $status;
/**
* Secret key of the service.
*
* @var string
*/
public $token;
/**
* Classes constructor.
*
* @param array|null $conditions
*/
public function __construct(array $conditions = null) {
$this->events = $conditions['events'] ?? null;
$this->header = $conditions['header'] ?? null;
$this->id = $conditions['id'] ?? null;
$this->name = $conditions['name'] ?? null;
$this->point = $conditions['point'] ?? null;
$this->status = $conditions['status'] ?? null;
$this->token = $conditions['token'] ?? null;
}
}
-184
View File
@@ -1,184 +0,0 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
namespace local_webhooks\output;
defined('MOODLE_INTERNAL') || die();
global $CFG;
require_once($CFG->dirroot . '/local/webhooks/classes/local/api.php');
require_once($CFG->libdir . '/tablelib.php');
use html_writer;
use lang_string;
use local_webhooks\local\api;
use moodle_url;
use pix_icon;
use stdClass;
use table_sql;
use function defined;
use function is_int;
/**
* Class table for list services.
*
* @copyright 2019 'Valentin Popov' <info@valentineus.link>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @package local_webhooks\output
*/
final class services_table extends table_sql {
/**
* URL editor page.
*
* @var string
*/
private static $editorpage = '/local/webhooks/service.php';
/**
* URL main page.
*
* @var string
*/
private static $mainpage = '/local/webhooks/index.php';
/**
* Class constructor.
*
* @param string $uniqueid
*
* @throws \coding_exception
*/
public function __construct(string $uniqueid) {
parent::__construct($uniqueid);
$this->define_table_columns();
$this->define_table_configs();
}
/**
* Define the action column.
*
* @param \stdClass $row
*
* @return string
*
* @throws \coding_exception
* @throws \moodle_exception
*/
public function col_actions(stdClass $row): string {
global $OUTPUT;
$deletelink = new moodle_url(self::$mainpage, ['deleteid' => $row->id, 'sesskey' => sesskey()]);
$deleteitem = $OUTPUT->action_icon($deletelink, new pix_icon('t/delete', new lang_string('delete', 'moodle')));
$editlink = new moodle_url(self::$editorpage, ['serviceid' => $row->id, 'sesskey' => sesskey()]);
$edititem = $OUTPUT->action_icon($editlink, new pix_icon('t/edit', new lang_string('edit', 'moodle')));
$hideshowlink = new moodle_url(self::$mainpage, ['hideshowid' => $row->id, 'sesskey' => sesskey()]);
$hideshowitem = $OUTPUT->action_icon($hideshowlink, new pix_icon($row->status ? 't/hide' : 't/show', $row->status
? new lang_string('disable', 'moodle')
: new lang_string('enable', 'moodle')
));
return $hideshowitem . $edititem . $deleteitem;
}
/**
* Define the events column.
*
* @param \stdClass $row
*
* @return int
*/
public function col_events(stdClass $row): int {
$total = count($row->events);
return is_int($total) ? $total : 0;
}
/**
* Define the name column.
*
* @param \stdClass $row
*
* @return string
*
* @throws \moodle_exception
*/
public function col_name(stdClass $row): string {
$link = new moodle_url(self::$editorpage, [
'serviceid' => $row->id,
'sesskey' => sesskey(),
]);
return html_writer::link($link, $row->name);
}
/**
* Config table's columns.
*
* @throws \coding_exception
*/
public function define_table_columns() {
$this->define_columns([
'name',
'point',
'events',
'actions',
]);
$this->define_headers([
new lang_string('name', 'moodle'),
new lang_string('url', 'moodle'),
new lang_string('edulevel', 'moodle'),
new lang_string('actions', 'moodle'),
]);
}
/**
* Config table.
*/
public function define_table_configs() {
$this->collapsible(false);
$this->is_downloadable(false);
$this->no_sorting('actions');
$this->no_sorting('events');
$this->pageable(true);
}
/**
* The query for the database.
*
* @param int $pagesize
* @param bool $useinitialsbar
*
* @throws \dml_exception
*/
public function query_db($pagesize, $useinitialsbar = true) {
$this->pagesize($pagesize, $pagesize + 1);
$sort = (string) $this->get_sql_sort();
$this->rawdata = api::get_services(null, $sort, $this->get_page_start(), $this->get_page_size());
$total = api::get_total_count();
$this->pagesize($pagesize, $total);
if ($useinitialsbar) {
$this->initialbars($total > $pagesize);
}
}
}
@@ -14,31 +14,29 @@
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
namespace local_webhooks\event;
/**
* Privacy Subsystem implementation for local_webhooks.
*
* @package local_webhooks
* @copyright 2020 Dmitrii Metelkin <dmitriim@catalyst-net.au>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
use core\event\base as event;
use core\task\manager;
use local_webhooks\task\notify;
use function defined;
namespace local_webhooks\privacy;
/**
* Class observer.
*
* @copyright 2019 'Valentin Popov' <info@valentineus.link>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @package local_webhooks\event
* Declares that the plugin does not store personal data.
*/
final class observer {
class provider implements
// This plugin does not store any personal user data.
\core_privacy\local\metadata\null_provider {
/**
* Main handler for events.
* Get the language string identifier with the component's language
* file to explain why this plugin stores no data.
*
* @param \core\event\base $event
* @return string
*/
public static function handler(event $event) {
$task = new notify();
$task->set_custom_data($event->get_data());
manager::queue_adhoc_task($task);
public static function get_reason(): string {
return 'privacy:metadata';
}
}
+103
View File
@@ -0,0 +1,103 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Defines the service editing form.
*
* @package local_webhooks
* @copyright 2017 "Valentin Popov" <info@valentineus.link>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
require_once($CFG->libdir . '/formslib.php');
/**
* Description editing form definition.
*
* @copyright 2017 "Valentin Popov" <info@valentineus.link>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class service_edit_form extends moodleform {
/**
* Defines the standard structure of the form.
*
* @throws \coding_exception
*/
protected function definition() {
$mform =& $this->_form;
$size = ['size' => 60];
/* Form heading */
$mform->addElement('header', 'editserviceheader', new lang_string('service', 'local_webhooks'));
/* Name of the service */
$mform->addElement('text', 'title', new lang_string('name', 'local_webhooks'), $size);
$mform->addRule('title', null, 'required');
$mform->setType('title', PARAM_NOTAGS);
/* Callback address */
$mform->addElement('text', 'url', new lang_string('url', 'local_webhooks'), $size);
$mform->addRule('url', null, 'required');
$mform->setType('url', PARAM_URL);
/* Enabling the service */
$mform->addElement('advcheckbox', 'enable', new lang_string('enable', 'local_webhooks'));
$mform->setType('enable', PARAM_BOOL);
$mform->setDefault('enable', 1);
$mform->setAdvanced('enable');
/* Token */
$mform->addElement('text', 'token', new lang_string('token', 'local_webhooks'), $size);
$mform->setType('token', PARAM_NOTAGS);
/* Additional information */
$mform->addElement('text', 'other', new lang_string('sourceext', 'local_webhooks'), $size);
$mform->setType('other', PARAM_NOTAGS);
$mform->setAdvanced('other');
/* Content type */
$contenttype = [
'json' => 'application/json',
'x-www-form-urlencoded' => 'application/x-www-form-urlencoded',
];
$mform->addElement('select', 'type', new lang_string('contenttype', 'local_webhooks'), $contenttype);
$mform->setAdvanced('type');
/* Form heading */
$mform->addElement('header', 'editserviceheaderevent', new lang_string('edulevel', 'local_webhooks'));
/* List of events */
$events = [];
/* Formation of the list of elements */
foreach (local_webhooks_get_event_choices() as $component => $choices) {
foreach ($choices as $key => $eventname) {
$events[$component][] =& $mform->createElement('checkbox', $key, $eventname);
}
}
/* Displays groups of items */
foreach ($events as $key => $event) {
$mform->addGroup($event, 'events', $key, '<br />');
}
/* Control Panel */
$this->add_action_buttons();
}
}
+54
View File
@@ -0,0 +1,54 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Defines forms.
*
* @package local_webhooks
* @copyright 2017 "Valentin Popov" <info@valentineus.link>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
require_once($CFG->libdir . '/formslib.php');
/**
* Description of the form of restoration.
*
* @copyright 2017 "Valentin Popov" <info@valentineus.link>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class service_backup_form extends moodleform {
/**
* Defines the standard structure of the form.
*
* @throws \coding_exception
*/
protected function definition() {
$mform =& $this->_form;
/* Form heading */
$mform->addElement('header', 'editserviceheader', new lang_string('restore', 'local_webhooks'));
/* Download the file */
$mform->addElement('filepicker', 'backupfile', new lang_string('file', 'local_webhooks'));
$mform->addRule('backupfile', null, 'required');
/* Control Panel */
$this->add_action_buttons(true, new lang_string('restore', 'local_webhooks'));
}
}
-90
View File
@@ -1,90 +0,0 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
namespace local_webhooks\task;
defined('MOODLE_INTERNAL') || die();
global $CFG;
require_once($CFG->dirroot . '/local/webhooks/classes/local/api.php');
use core\task\adhoc_task;
use curl;
use local_webhooks\local\api;
use local_webhooks\local\record;
use function defined;
use function is_object;
use function is_string;
/**
* Class for processing events.
*
* @package local_webhooks\task
*/
final class notify extends adhoc_task {
/**
* Debug information.
*
* @var array
*/
public $debug;
/**
* Process an event.
*
* @throws \dml_exception
*/
public function execute() {
$event = $this->get_custom_data();
if (!is_object($event) || !isset($event->eventname) || !is_string($event->eventname)) {
return;
}
foreach (api::get_services_by_event($event->eventname) as $service) {
if (!is_object($service)) {
continue;
}
if (!$service->status) {
continue;
}
$this->post($service, array_merge((array) $event, [
'token' => $service->token,
]));
}
}
/**
* Send a request for the service.
*
* @param \local_webhooks\local\record $service
* @param array $data
*/
public function post(record $service, array $data) {
$curl = new curl();
$curl->setHeader(['Content-Type: ' . $service->header]);
$curl->post($service->point, json_encode($data));
if (defined('PHPUNIT_TEST') && PHPUNIT_TEST) {
$this->debug = array_merge($this->debug ?? [], [
compact('data', 'service'),
]);
}
}
}
-105
View File
@@ -1,105 +0,0 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Defines forms.
*
* @copyright 2018 'Valentin Popov' <info@valentineus.link>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @package local_webhooks
*/
defined('MOODLE_INTERNAL') || die();
require_once($CFG->dirroot . '/local/webhooks/lib.php');
require_once($CFG->libdir . '/formslib.php');
/**
* Description editing form definition.
*
* @copyright 2018 'Valentin Popov' <info@valentineus.link>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @package local_webhooks
*/
class local_webhooks_service_edit_form extends moodleform {
/**
* @param string $baseurl
*/
public function __construct($baseurl) {
parent::__construct($baseurl);
}
/**
* Defines the standard structure of the form.
*
* @throws \coding_exception
*/
protected function definition() {
$mform =& $this->_form;
$size = array('size' => 60);
/* Form heading */
$mform->addElement('header', 'edit-service-header-main', new lang_string('service', 'webservice'));
/* Name of the service */
$mform->addElement('text', 'name', new lang_string('name', 'moodle'), $size);
$mform->addRule('name', null, 'required');
$mform->setType('name', PARAM_RAW);
/* Callback address */
$mform->addElement('text', 'point', new lang_string('url', 'moodle'), $size);
$mform->addRule('point', null, 'required');
$mform->setType('point', PARAM_URL);
/* Enabling the service */
$mform->addElement('advcheckbox', 'status', new lang_string('enable', 'moodle'));
$mform->setType('status', PARAM_BOOL);
$mform->setDefault('status', 1);
$mform->setAdvanced('status');
/* Token */
$mform->addElement('text', 'token', new lang_string('token', 'webservice'), $size);
$mform->addRule('token', null, 'required');
$mform->setType('token', PARAM_RAW);
/* Content type */
$contenttype = array(
'application/json' => 'application/json',
'application/x-www-form-urlencoded' => 'application/x-www-form-urlencoded',
);
$mform->addElement('select', 'header', 'Content-Type', $contenttype);
$mform->setAdvanced('header');
/* Form heading */
$mform->addElement('header', 'edit-service-header-event', new lang_string('edulevel', 'moodle'));
/* List of events */
$eventlist = report_eventlist_list_generator::get_all_events_list(true);
$events = array();
foreach ($eventlist as $event) {
$events[$event['component']][] =& $mform->createElement('checkbox', $event['eventname'], $event['eventname']);
}
foreach ($events as $key => $event) {
$mform->addGroup($event, 'events', $key, '<br />', true);
}
/* Control Panel */
$this->add_action_buttons(true);
}
}
+44
View File
@@ -0,0 +1,44 @@
services:
postgres:
image: postgres:16.13-alpine3.22@sha256:caf536ebd910e85473a9f5e2fd1aea360c965c4a911c8555ac1f61b2102006cb
environment:
POSTGRES_HOST_AUTH_METHOD: trust
POSTGRES_USER: postgres
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres"]
interval: 2s
timeout: 5s
retries: 15
tmpfs:
- /var/lib/postgresql/data
ci:
build:
context: .
dockerfile: .docker/ci/Dockerfile
depends_on:
postgres:
condition: service_healthy
environment:
DB: pgsql
DB_HOST: postgres
DB_USER: postgres
MOODLE_BRANCH: v5.2.2
NPM_CONFIG_FETCH_RETRIES: 5
command:
- /bin/bash
- -lc
- |
set -euo pipefail
php --version
composer --version
node --version
moodle-plugin-ci --version
moodle-plugin-ci install --plugin /plugin --branch v5.2.2 --db-host postgres
test "$$(git -C /workspace/moodle rev-parse HEAD)" = "acfa383c13dd46c83ca82894a8e95fac273fda33"
moodle-plugin-ci phplint
moodle-plugin-ci phpcs --max-warnings 0
moodle-plugin-ci phpdoc --max-warnings 0
moodle-plugin-ci validate
moodle-plugin-ci savepoints
moodle-plugin-ci phpunit --fail-on-warning
+7 -3
View File
@@ -15,9 +15,10 @@
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Registration of observers for events.
* Interception of all events in the system.
*
* @copyright 2019 'Valentin Popov' <info@valentineus.link>
* @package local_webhooks
* @copyright 2017 "Valentin Popov" <info@valentineus.link>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
@@ -25,7 +26,10 @@ defined('MOODLE_INTERNAL') || die();
$observers = [
[
'callback' => '\local_webhooks\event\observer::handler',
'callback' => '\local_webhooks\handler::events',
'eventname' => '*',
'includefile' => null,
'internal' => true,
'priority' => 200,
],
];
+9 -20
View File
@@ -1,33 +1,22 @@
<?xml version="1.0" encoding="UTF-8" ?>
<XMLDB PATH="local/webhooks/db" VERSION="2018090700" COMMENT="XMLDB file for Moodle local/webhooks"
<XMLDB PATH="local/webhooks/db" VERSION="2018061900" COMMENT="XMLDB file for Moodle"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="../../../lib/xmldb/xmldb.xsd">
<TABLES>
<TABLE NAME="local_webhooks_service" COMMENT="Storing created services.">
<TABLE NAME="local_webhooks_service" COMMENT="A table for storing callback services.">
<FIELDS>
<FIELD NAME="id" TYPE="int" LENGTH="10" NOTNULL="true" SEQUENCE="true" />
<FIELD NAME="header" TYPE="char" LENGTH="255" NOTNULL="true" SEQUENCE="false" DEFAULT="application/json" COMMENT="Type of outgoing header." />
<FIELD NAME="name" TYPE="char" LENGTH="255" NOTNULL="true" SEQUENCE="false" COMMENT="Name of the service." />
<FIELD NAME="point" TYPE="char" LENGTH="255" NOTNULL="true" SEQUENCE="false" COMMENT="Point of delivery of notifications." />
<FIELD NAME="status" TYPE="int" LENGTH="1" NOTNULL="true" SEQUENCE="false" DEFAULT="0" COMMENT="Current status of the service." />
<FIELD NAME="token" TYPE="char" LENGTH="255" NOTNULL="true" SEQUENCE="false" COMMENT="Token for verification of requests." />
<FIELD NAME="enable" TYPE="int" LENGTH="2" NOTNULL="true" DEFAULT="0" SEQUENCE="false" />
<FIELD NAME="title" TYPE="text" NOTNULL="true" SEQUENCE="false" />
<FIELD NAME="url" TYPE="char" LENGTH="255" NOTNULL="true" SEQUENCE="false" />
<FIELD NAME="type" TYPE="char" LENGTH="255" NOTNULL="true" SEQUENCE="false" />
<FIELD NAME="token" TYPE="char" LENGTH="255" NOTNULL="true" SEQUENCE="false" />
<FIELD NAME="events" TYPE="text" NOTNULL="false" SEQUENCE="false" />
<FIELD NAME="other" TYPE="text" NOTNULL="false" SEQUENCE="false" />
</FIELDS>
<KEYS>
<KEY NAME="primary" TYPE="primary" FIELDS="id" />
</KEYS>
</TABLE>
<TABLE NAME="local_webhooks_events" COMMENT="Storing of viewed events.">
<FIELDS>
<FIELD NAME="id" TYPE="int" LENGTH="10" NOTNULL="true" SEQUENCE="true" />
<FIELD NAME="name" TYPE="char" LENGTH="255" NOTNULL="true" SEQUENCE="false" COMMENT="Name of the service." />
<FIELD NAME="serviceid" TYPE="int" LENGTH="10" NOTNULL="true" SEQUENCE="false" COMMENT="Service ID." />
</FIELDS>
<KEYS>
<KEY NAME="primary" TYPE="primary" FIELDS="id" />
</KEYS>
</TABLE>
</TABLES>
</XMLDB>
-74
View File
@@ -1,74 +0,0 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* This file registers the plugin's external functions.
*
* @copyright 2019 'Valentin Popov' <info@valentineus.link>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$functions = [
'local_webhooks_add_service' => [
'classname' => 'local_webhooks_external',
'classpath' => 'local/webhooks/externallib.php',
'description' => 'Add a new service.',
'methodname' => 'add_service',
'type' => 'write',
],
'local_webhooks_del_service' => [
'classname' => 'local_webhooks_external',
'classpath' => 'local/webhooks/externallib.php',
'description' => 'Delete the existing service.',
'methodname' => 'del_service',
'type' => 'write',
],
'local_webhooks_get_events' => [
'classname' => 'local_webhooks_external',
'classpath' => 'local/webhooks/externallib.php',
'description' => 'Get the event\'s list.',
'methodname' => 'get_events',
'type' => 'read',
],
'local_webhooks_get_service' => [
'classname' => 'local_webhooks_external',
'classpath' => 'local/webhooks/externallib.php',
'description' => 'Get data by service.',
'methodname' => 'get_service',
'type' => 'read',
],
'local_webhooks_get_services' => [
'classname' => 'local_webhooks_external',
'classpath' => 'local/webhooks/externallib.php',
'description' => 'Get the service\'s list.',
'methodname' => 'get_services',
'type' => 'read',
],
'local_webhooks_set_service' => [
'classname' => 'local_webhooks_external',
'classpath' => 'local/webhooks/externallib.php',
'description' => 'Update the existing service.',
'methodname' => 'set_service',
'type' => 'write',
],
];
-28
View File
@@ -1,28 +0,0 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
defined('MOODLE_INTERNAL') || die();
/**
* Function to upgrade 'local_webhooks'.
*
* @param int $oldversion
*
* @return bool
*/
function xmldb_local_webhooks_upgrade(int $oldversion) {
return true;
}
+105
View File
@@ -0,0 +1,105 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Page for editing the service.
*
* @package local_webhooks
* @copyright 2017 "Valentin Popov" <info@valentineus.link>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
require_once(__DIR__ . '/../../config.php');
require_once(__DIR__ . '/classes/service_edit_form.php');
require_once(__DIR__ . '/lib.php');
require_once($CFG->libdir . '/adminlib.php');
/* Optional parameters */
$serviceid = optional_param('serviceid', 0, PARAM_INT);
/* Link generation */
$urlparameters = ['serviceid' => $serviceid];
$baseurl = new moodle_url('/local/webhooks/editservice.php', $urlparameters);
$managerservice = new moodle_url('/local/webhooks/index.php');
/* Configure the context of the page */
admin_externalpage_setup('local_webhooks', '', null, $baseurl);
$context = context_system::instance();
/* Create an editing form */
$mform = new service_edit_form($PAGE->url);
/* Cancel processing */
if ($mform->is_cancelled()) {
redirect($managerservice);
}
/* Getting the data */
$servicerecord = new stdClass();
if (($editing = (bool) $serviceid) === true) {
$servicerecord = local_webhooks_get_record($serviceid);
if (is_array($servicerecord->events)) {
$events = [];
/* Escaping event names */
foreach ($servicerecord->events as $eventname => $eventstatus) {
$eventname = base64_encode($eventname);
$events[$eventname] = $eventstatus;
}
$servicerecord->events = $events;
}
$mform->set_data($servicerecord);
}
/* Processing of received data */
if (!empty($data = $mform->get_data())) {
if (is_array($data->events)) {
$events = [];
/* Deciphering event names */
foreach ($data->events as $eventname => $eventstatus) {
$eventname = (string) base64_decode($eventname);
$events[$eventname] = $eventstatus;
}
$data->events = $events;
}
if ($editing) {
$data->id = $serviceid;
local_webhooks_update_record($data, false);
redirect($managerservice, new lang_string('eventwebserviceserviceupdated', 'local_webhooks'));
} else {
local_webhooks_update_record($data);
redirect($managerservice, new lang_string('eventwebserviceservicecreated', 'local_webhooks'));
}
}
/* The page title */
$titlepage = new lang_string('externalservice', 'local_webhooks');
$PAGE->navbar->add($titlepage);
$PAGE->set_heading($titlepage);
$PAGE->set_title($titlepage);
echo $OUTPUT->header();
/* Displays the form */
$mform->display();
echo $OUTPUT->footer();
-366
View File
@@ -1,366 +0,0 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
defined('MOODLE_INTERNAL') || die();
global $CFG;
require_once($CFG->dirroot . '/local/webhooks/classes/local/api.php');
require_once($CFG->libdir . '/externallib.php');
use local_webhooks\local\api;
use local_webhooks\local\record;
/**
* WebHooks external functions.
*
* @copyright 2019 'Valentin Popov' <info@valentineus.link>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
final class local_webhooks_external extends external_api {
/**
* Add a new service.
*
* @param array $conditions
*
* @return int
*
* @throws \coding_exception
* @throws \dml_exception
* @throws \invalid_parameter_exception
* @throws \restricted_context_exception
*/
public static function add_service(array $conditions): int {
$parameters = self::validate_parameters(self::add_service_parameters(), [
'record' => array_filter($conditions),
]);
$context = context_system::instance();
self::validate_context($context);
$parameters = array_filter($parameters['record']);
$record = new record($parameters);
return api::add_service($record);
}
/**
* Returns description of the method parameters.
*
* @return \external_function_parameters
*/
public static function add_service_parameters(): external_function_parameters {
return new external_function_parameters([
'record' => new external_single_structure([
'events' => new external_multiple_structure(
new external_value(PARAM_RAW, 'The event\'s name.'), 'The service\'s list events.', false
),
'header' => new external_value(PARAM_RAW, 'The request\'s header or type', false, 'application/json'),
'name' => new external_value(PARAM_RAW, 'The service\'s name.'),
'point' => new external_value(PARAM_URL, 'The service\'s endpoint.'),
'status' => new external_value(PARAM_BOOL, 'The service\'s status.', false, true),
'token' => new external_value(PARAM_RAW, 'The service\'s secret key.'),
], 'The new service\'s data.'),
]);
}
/**
* Returns description of the method result value.
*
* @return \external_value
*/
public static function add_service_returns(): external_value {
return new external_value(PARAM_INT, 'The service\'s ID.');
}
/**
* Delete the existing service.
*
* @param int $serviceid
*
* @return bool
*
* @throws \dml_exception
* @throws \invalid_parameter_exception
* @throws \restricted_context_exception
*/
public static function del_service(int $serviceid): bool {
$parameters = self::validate_parameters(self::del_service_parameters(), [
'serviceid' => $serviceid,
]);
$context = context_system::instance();
self::validate_context($context);
return api::del_service($parameters['serviceid']);
}
/**
* Returns description of the method parameters.
*
* @return \external_function_parameters
*/
public static function del_service_parameters(): external_function_parameters {
return new external_function_parameters([
'serviceid' => new external_value(PARAM_INT, 'The service\'s ID.'),
]);
}
/**
* Returns description of the method result value.
*
* @return \external_value
*/
public static function del_service_returns(): external_value {
return new external_value(PARAM_BOOL, 'The result operation.');
}
/**
* Get the event's list.
*
* @return array
*
* @throws \ReflectionException
* @throws \dml_exception
* @throws \invalid_parameter_exception
* @throws \restricted_context_exception
*/
public static function get_events(): array {
$context = context_system::instance();
self::validate_context($context);
return api::get_events();
}
/**
* Returns description of the method parameters.
*
* @return \external_function_parameters
*/
public static function get_events_parameters(): external_function_parameters {
return new external_function_parameters([]);
}
/**
* Returns description of the method result value.
*
* @return \external_multiple_structure
*/
public static function get_events_returns(): external_multiple_structure {
return new external_multiple_structure(
new external_single_structure([
'action' => new external_value(PARAM_ALPHANUMEXT, 'The action name.'),
'component' => new external_value(PARAM_COMPONENT, 'The component name.'),
'crud' => new external_value(PARAM_ALPHA, 'The transaction type.'),
'edulevel' => new external_value(PARAM_INT, 'The level of educational value.'),
'eventname' => new external_value(PARAM_RAW, 'The event name.'),
'objecttable' => new external_value(PARAM_RAW, 'The database table name.'),
'target' => new external_value(PARAM_RAW, 'The target on which the action.'),
], 'The event\'s data.'), 'The event\'s list.'
);
}
/**
* Get data by service.
*
* @param int $serviceid
*
* @return \local_webhooks\local\record
*
* @throws \dml_exception
* @throws \invalid_parameter_exception
* @throws \restricted_context_exception
*/
public static function get_service(int $serviceid): record {
$parameters = self::validate_parameters(self::get_service_parameters(), [
'serviceid' => $serviceid,
]);
$context = context_system::instance();
self::validate_context($context);
return api::get_service($parameters['serviceid']);
}
/**
* Returns description of the method parameters.
*
* @return \external_function_parameters
*/
public static function get_service_parameters(): external_function_parameters {
return new external_function_parameters([
'serviceid' => new external_value(PARAM_INT, 'The service\'s ID.'),
]);
}
/**
* Returns description of the method result value.
*
* @return \external_single_structure
*/
public static function get_service_returns(): external_single_structure {
return new external_single_structure([
'events' => new external_multiple_structure(
new external_value(PARAM_RAW, 'The event\'s name.'), 'The service\'s list events.'
),
'header' => new external_value(PARAM_RAW, 'The request\'s header or type'),
'id' => new external_value(PARAM_INT, 'The service\'s ID.'),
'name' => new external_value(PARAM_RAW, 'The service\'s name.'),
'point' => new external_value(PARAM_URL, 'The service\'s endpoint.'),
'status' => new external_value(PARAM_BOOL, 'The service\'s status.'),
'token' => new external_value(PARAM_RAW, 'The service\'s secret key.'),
], 'The service\'s data.');
}
/**
* Get the service's list.
*
* @param array|null $conditions
* @param string|null $sort
* @param int|null $from
* @param int|null $limit
*
* @return array
*
* @throws \dml_exception
* @throws \invalid_parameter_exception
* @throws \restricted_context_exception
*/
public static function get_services(array $conditions = null, string $sort = null, int $from = null, int $limit = null): array {
$parameters = self::validate_parameters(self::get_services_parameters(), [
'conditions' => $conditions ?? [],
'from' => $from,
'limit' => $limit,
'sort' => $sort,
]);
$context = context_system::instance();
self::validate_context($context);
return api::get_services(
array_filter($parameters['conditions']),
$parameters['sort'],
$parameters['from'],
$parameters['limit']
);
}
/**
* Returns description of the method parameters.
*
* @return \external_function_parameters
*/
public static function get_services_parameters(): external_function_parameters {
return new external_function_parameters([
'conditions' => new external_single_structure([
'header' => new external_value(PARAM_RAW, 'The request\'s header or type', false),
'name' => new external_value(PARAM_RAW, 'The service\'s name.', false),
'point' => new external_value(PARAM_URL, 'The service\'s endpoint.', false),
'status' => new external_value(PARAM_BOOL, 'The service\'s status.', false),
'token' => new external_value(PARAM_RAW, 'The service\'s secret key.', false),
], 'SQL conditions.', false),
'sort' => new external_value(PARAM_RAW, 'SQL sort parameters.', false),
'from' => new external_value(PARAM_INT, 'The start index.', false),
'limit' => new external_value(PARAM_INT, 'The count elements.', false),
]);
}
/**
* Returns description of the method result value.
*
* @return \external_multiple_structure
*/
public static function get_services_returns(): external_multiple_structure {
return new external_multiple_structure(
new external_single_structure([
'events' => new external_multiple_structure(
new external_value(PARAM_RAW, 'The event\'s name.'), 'The service\'s list events.'
),
'header' => new external_value(PARAM_RAW, 'The request\'s header or type'),
'id' => new external_value(PARAM_INT, 'The service\'s ID.'),
'name' => new external_value(PARAM_RAW, 'The service\'s name.'),
'point' => new external_value(PARAM_URL, 'The service\'s endpoint.'),
'status' => new external_value(PARAM_BOOL, 'The service\'s status.'),
'token' => new external_value(PARAM_RAW, 'The service\'s secret key.'),
], 'The service\'s data.'), 'The service\'s list.'
);
}
/**
* Update the existing service.
*
* @param array $conditions
*
* @return bool
*
* @throws \coding_exception
* @throws \dml_exception
* @throws \invalid_parameter_exception
* @throws \restricted_context_exception
*/
public static function set_service(array $conditions): bool {
$conditions = array_filter($conditions);
$conditions['events'] = $conditions['events'] ?? [];
$parameters = self::validate_parameters(self::set_service_parameters(), [
'record' => $conditions,
]);
$context = context_system::instance();
self::validate_context($context);
$parameters = array_filter($parameters['record']);
$record = api::get_service($parameters['id']);
foreach ($parameters as $index => $value) {
if (property_exists($record, $index)) {
$record->$index = $value;
}
}
return api::set_service($record);
}
/**
* Returns description of the method parameters.
*
* @return \external_function_parameters
*/
public static function set_service_parameters(): external_function_parameters {
return new external_function_parameters([
'record' => new external_single_structure([
'events' => new external_multiple_structure(
new external_value(PARAM_RAW, 'The event\'s name.'), 'The service\'s list events.', false
),
'header' => new external_value(PARAM_RAW, 'The request\'s header or type', false),
'id' => new external_value(PARAM_INT, 'The service\'s ID.'),
'name' => new external_value(PARAM_RAW, 'The service\'s name.', false),
'point' => new external_value(PARAM_URL, 'The service\'s endpoint.', false),
'status' => new external_value(PARAM_BOOL, 'The service\'s status.', false),
'token' => new external_value(PARAM_RAW, 'The service\'s secret key.', false),
], 'The new service\'s data.'),
]);
}
/**
* Returns description of the method result value.
*
* @return \external_value
*/
public static function set_service_returns(): external_value {
return new external_value(PARAM_BOOL, 'The result operation.');
}
}
+105 -35
View File
@@ -14,63 +14,133 @@
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
require_once(dirname(__DIR__, 2) . '/config.php');
/**
* Service Management Manager.
*
* @package local_webhooks
* @copyright 2017 "Valentin Popov" <info@valentineus.link>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
global $CFG;
require_once(__DIR__ . '/../../config.php');
require_once(__DIR__ . '/lib.php');
defined('MOODLE_INTERNAL') || die();
require_once($CFG->dirroot . '/local/webhooks/classes/local/api.php');
require_once($CFG->dirroot . '/local/webhooks/classes/output/services_table.php');
require_once($CFG->libdir . '/adminlib.php');
require_once($CFG->libdir . '/tablelib.php');
use local_webhooks\local\api;
use local_webhooks\output\services_table;
/* Optional parameters */
$backupservices = optional_param('getbackup', 0, PARAM_BOOL);
$deleteid = optional_param('deleteid', 0, PARAM_INT);
$hideshowid = optional_param('hideshowid', 0, PARAM_INT);
$editpage = '/local/webhooks/service.php';
$mainpage = '/local/webhooks/index.php';
/* Link generation */
$editservice = '/local/webhooks/editservice.php';
$managerservice = '/local/webhooks/index.php';
$restorebackup = '/local/webhooks/restorebackup.php';
$baseurl = new moodle_url($managerservice);
$baseurl = new moodle_url($mainpage);
/* Configure the context of the page */
admin_externalpage_setup('local_webhooks', '', null, $baseurl);
$context = context_system::instance();
admin_externalpage_setup('local_webhooks', '', ['contextid' => $context->contextlevel], $baseurl, []);
// Deleting the existing service.
if ($deleteid !== 0 && confirm_sesskey()) {
api::del_service($deleteid);
redirect($PAGE->url, new lang_string('deleted', 'moodle'));
/* Delete the service */
if ((bool) $deleteid) {
local_webhooks_remove_record($deleteid);
redirect($PAGE->url, new lang_string('eventwebserviceservicedeleted', 'local_webhooks'));
}
// Setting status to existing service.
if ($hideshowid !== 0 && confirm_sesskey()) {
$service = api::get_service($hideshowid);
$service->status = !filter_var($service->status, FILTER_VALIDATE_BOOLEAN);
api::set_service($service);
/* Retrieving a list of services */
$callbacks = local_webhooks_get_list_records();
redirect($PAGE->url, new lang_string('changessaved', 'moodle'));
/* Upload settings as a file */
if ((bool) $backupservices) {
$filecontent = local_webhooks_create_backup();
$filename = 'webhooks_' . date('U') . '.backup';
send_file($filecontent, $filename, 0, 0, true, true);
}
// Page header.
/* Switching the status of the service */
if ((bool) $hideshowid) {
$callback = $callbacks[$hideshowid];
if (!empty($callback)) {
$callback->enable = !(bool) $callback->enable;
local_webhooks_update_record($callback, false);
redirect($PAGE->url, new lang_string('eventwebserviceserviceupdated', 'local_webhooks'));
}
}
/* The page title */
$titlepage = new lang_string('pluginname', 'local_webhooks');
$PAGE->set_heading($titlepage);
$PAGE->set_title($titlepage);
echo $OUTPUT->header();
// Adds the add button.
$addserviceurl = new moodle_url($editpage, ['sesskey' => sesskey()]);
echo $OUTPUT->single_button($addserviceurl, new lang_string('add', 'moodle'));
/* Table declaration */
$table = new flexible_table('webhooks-service-table');
// Separation.
echo html_writer::empty_tag('br');
/* Customize the table */
$table->define_columns(
[
'title',
'url',
'actions',
]
);
$table->define_headers(
[
new lang_string('name', 'local_webhooks'),
new lang_string('url', 'local_webhooks'),
new lang_string('actions', 'local_webhooks'),
]
);
// Displays the table.
$table = new services_table('local-webhooks-services');
$table->define_baseurl($baseurl);
$table->out(25, true);
$table->setup();
foreach ($callbacks as $callback) {
/* Filling of information columns */
$titlecallback = html_writer::div($callback->title, 'title');
$urlcallback = html_writer::div($callback->url, 'url');
/* Defining service status */
$hideshowicon = 't/show';
$hideshowstring = new lang_string('enable', 'local_webhooks');
if ((bool) $callback->enable) {
$hideshowicon = 't/hide';
$hideshowstring = new lang_string('disable', 'local_webhooks');
}
/* Link to enable / disable the service */
$hideshowlink = new moodle_url($managerservice, ['hideshowid' => $callback->id]);
$hideshowitem = $OUTPUT->action_icon($hideshowlink, new pix_icon($hideshowicon, $hideshowstring));
/* Link for editing */
$editlink = new moodle_url($editservice, ['serviceid' => $callback->id]);
$edititem = $OUTPUT->action_icon($editlink, new pix_icon('t/edit', new lang_string('edit', 'local_webhooks')));
/* Link to remove */
$deletelink = new moodle_url($managerservice, ['deleteid' => $callback->id]);
$deleteitem = $OUTPUT->action_icon($deletelink, new pix_icon('t/delete', new lang_string('delete', 'local_webhooks')));
/* Adding data to the table */
$table->add_data([$titlecallback, $urlcallback, $hideshowitem . $edititem . $deleteitem]);
}
/* Display the table */
$table->print_html();
/* Add service button */
$addserviceurl = new moodle_url($editservice);
echo $OUTPUT->single_button($addserviceurl, new lang_string('addaservice', 'local_webhooks'), 'get');
/* Button to get a backup */
$backupurl = new moodle_url($managerservice, ['getbackup' => true]);
echo $OUTPUT->single_button($backupurl, new lang_string('backup', 'local_webhooks'), 'get');
/* Button for restoring settings */
$restorebackupurl = new moodle_url($restorebackup);
echo $OUTPUT->single_button($restorebackupurl, new lang_string('restore', 'local_webhooks'), 'get');
// Footer.
echo $OUTPUT->footer();
+31 -3
View File
@@ -15,11 +15,39 @@
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Strings for component 'local_webhooks', language 'en'.
* Strings for component "local_webhooks", language "en".
*
* @copyright 2018 'Valentin Popov' <info@valentineus.link>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @package local_webhooks
* @copyright 2017 "Valentin Popov" <info@valentineus.link>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
$string['actions'] = 'Actions';
$string['addaservice'] = 'Add service';
$string['answer'] = 'Answer';
$string['backup'] = 'Backup';
$string['backupfinished'] = 'Backup completed successfully';
$string['contenttype'] = 'Content type';
$string['create'] = 'Create';
$string['delete'] = 'Delete';
$string['deleted'] = 'Deleted';
$string['disable'] = 'Disable';
$string['edit'] = 'Edit';
$string['edulevel'] = 'All events';
$string['enable'] = 'Enable';
$string['errorsendingrequest'] = 'Error sending request';
$string['eventwebserviceservicecreated'] = 'Web service created';
$string['eventwebserviceservicedeleted'] = 'Web service deleted';
$string['eventwebserviceserviceupdated'] = 'Web service updated';
$string['externalservice'] = 'External service';
$string['file'] = 'File';
$string['name'] = 'Name';
$string['pluginname'] = 'WebHooks';
$string['privacy:metadata'] = 'WebHooks does not store any personal data.';
$string['restore'] = 'Restore';
$string['restorefinished'] = 'Restore completed successfully';
$string['service'] = 'Service';
$string['sourceext'] = 'Additional';
$string['token'] = 'Token';
$string['update'] = 'Update';
$string['url'] = 'URL';
+225
View File
@@ -0,0 +1,225 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Library code used by the service control interfaces.
*
* @package local_webhooks
* @copyright 2017 "Valentin Popov" <info@valentineus.link>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
require_once(__DIR__ . '/locallib.php');
/**
* Returns available event classes grouped by component.
*
* @return array
*/
function local_webhooks_get_event_choices() {
global $CFG;
$choices = [];
$debug = $CFG->debug;
// Deprecated core events emit debugging while loading; mirror the core tool_monitor workaround.
try {
$CFG->debug = DEBUG_NONE;
$classes = core_component::get_component_classes_in_namespace(null, 'event');
} finally {
$CFG->debug = $debug;
}
ksort($classes);
foreach (array_keys($classes) as $classname) {
if (
$classname === \core\event\unknown_logged::class
|| !is_subclass_of($classname, \core\event\base::class)
|| $classname::is_deprecated()
) {
continue;
}
$reflection = new ReflectionClass($classname);
if ($reflection->isAbstract()) {
continue;
}
$eventname = '\\' . ltrim($classname, '\\');
$component = core_component::get_component_from_classname($classname);
$choices[$component][base64_encode($eventname)] = $eventname;
}
return $choices;
}
/**
* Getting a list of all services.
*
* @param int $limitfrom
* @param int $limitnum
*
* @return array
* @throws \dml_exception
*/
function local_webhooks_get_list_records($limitfrom = 0, $limitnum = 0) {
global $DB;
$listservices = $DB->get_records('local_webhooks_service', null, 'id', '*', $limitfrom, $limitnum);
foreach ($listservices as $servicerecord) {
if (!empty($servicerecord->events)) {
$servicerecord->events = local_webhooks_unarchive_data($servicerecord->events);
}
}
return $listservices;
}
/**
* Getting information about the service.
*
* @param int $serviceid
*
* @return object
* @throws \dml_exception
*/
function local_webhooks_get_record($serviceid = 0) {
global $DB;
$servicerecord = $DB->get_record('local_webhooks_service', ['id' => $serviceid], '*', MUST_EXIST);
if (!empty($servicerecord->events)) {
$servicerecord->events = local_webhooks_unarchive_data($servicerecord->events);
}
return $servicerecord;
}
/**
* Clear the database table.
*
* @throws \dml_exception
*/
function local_webhooks_remove_list_records() {
global $DB;
$DB->delete_records('local_webhooks_service');
}
/**
* Delete the record.
*
* @param int $serviceid
*
* @throws \dml_exception
* @throws \coding_exception
*/
function local_webhooks_remove_record($serviceid = 0) {
global $DB;
$DB->delete_records('local_webhooks_service', ['id' => $serviceid]);
local_webhooks_events::service_deleted($serviceid);
}
/**
* Update the record in the database.
*
* @param object $data
* @param boolean $insert
*
* @return boolean
* @throws \dml_exception
* @throws \coding_exception
*/
function local_webhooks_update_record($data, $insert = true) {
global $DB;
if (empty($data->events)) {
$data->events = [];
}
$data->events = local_webhooks_archiving_data($data->events);
if ((bool) $insert) {
$result = $DB->insert_record('local_webhooks_service', $data);
local_webhooks_events::service_added($result);
} else {
$result = $DB->update_record('local_webhooks_service', $data);
local_webhooks_events::service_updated($data->id);
}
return (bool) $result;
}
/**
* Make a backup copy of all the services.
*
* @return string
* @throws \dml_exception
* @throws \coding_exception
*/
function local_webhooks_create_backup() {
$listservices = local_webhooks_get_list_records();
$listservices = local_webhooks_archiving_data($listservices);
local_webhooks_events::backup_performed();
return $listservices;
}
/**
* Restore the data from the backup.
*
* @param string $listservices
*
* @throws \dml_exception
* @throws \coding_exception
*/
function local_webhooks_restore_backup($listservices = '') {
$listservices = local_webhooks_unarchive_data($listservices);
local_webhooks_remove_list_records();
foreach ($listservices as $servicerecord) {
local_webhooks_update_record($servicerecord);
}
local_webhooks_events::backup_restored();
}
/**
* Compress an array into a string.
*
* @param array $data
*
* @return string
*/
function local_webhooks_archiving_data(array $data = []) {
return base64_encode(gzcompress(serialize($data), 3));
}
/**
* Gets an array from a compressed string.
*
* @param string $data
*
* @return array
*/
function local_webhooks_unarchive_data($data = '') {
return unserialize(gzuncompress(base64_decode($data)));
}
+151
View File
@@ -0,0 +1,151 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Classes of modules.
*
* @package local_webhooks
* @copyright 2017 "Valentin Popov" <info@valentineus.link>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
/**
* Description of functions of the call of events
*
* @copyright 2017 "Valentin Popov" <info@valentineus.link>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class local_webhooks_events {
/**
* Call the event when creating a backup.
*
* @throws \coding_exception
* @throws \dml_exception
*/
public static function backup_performed() {
$context = context_system::instance();
$event = local_webhooks\event\backup_performed::create(
[
'context' => $context,
'objectid' => 0,
]
);
$event->trigger();
}
/**
* Call the event when restoring from a backup.
*
* @throws \coding_exception
* @throws \dml_exception
*/
public static function backup_restored() {
$context = context_system::instance();
$event = local_webhooks\event\backup_restored::create(
[
'context' => $context,
'objectid' => 0,
]
);
$event->trigger();
}
/**
* Call event when the response is received from the service
*
* @param int $objectid Service ID
* @param array $response Server response
*
* @throws \coding_exception
* @throws \dml_exception
*/
public static function response_answer($objectid = 0, array $response = []) {
$context = context_system::instance();
$status = get_string('errorsendingrequest', 'local_webhooks');
if (!empty($response['HTTP/1.1'])) {
$status = $response['HTTP/1.1'];
}
$event = local_webhooks\event\response_answer::create(
[
'context' => $context,
'objectid' => $objectid,
'other' => ['status' => $status],
]
);
$event->trigger();
}
/**
* Call the event when the service is added.
*
* @param int $objectid Service ID
*
* @throws \coding_exception
* @throws \dml_exception
*/
public static function service_added($objectid = 0) {
$context = context_system::instance();
$event = local_webhooks\event\service_added::create(
compact('context', 'objectid')
);
$event->trigger();
}
/**
* Call the event when the service is deleted.
*
* @param int $objectid Service ID
*
* @throws \coding_exception
* @throws \dml_exception
*/
public static function service_deleted($objectid = 0) {
$context = context_system::instance();
$event = local_webhooks\event\service_deleted::create(
compact('context', 'objectid')
);
$event->trigger();
}
/**
* Call event when the service is updated.
*
* @param int $objectid Service ID
*
* @throws \coding_exception
* @throws \dml_exception
*/
public static function service_updated($objectid = 0) {
$context = context_system::instance();
$event = local_webhooks\event\service_updated::create(
compact('context', 'objectid')
);
$event->trigger();
}
}
+64
View File
@@ -0,0 +1,64 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Restore the settings page.
*
* @package local_webhooks
* @copyright 2017 "Valentin Popov" <info@valentineus.link>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
require_once(__DIR__ . '/../../config.php');
require_once(__DIR__ . '/classes/service_form.php');
require_once(__DIR__ . '/lib.php');
require_once($CFG->libdir . '/adminlib.php');
/* Link generation */
$baseurl = new moodle_url('/local/webhooks/restorebackup.php');
$managerservice = new moodle_url('/local/webhooks/index.php');
/* Configure the context of the page */
admin_externalpage_setup('local_webhooks', '', null, $baseurl);
$context = context_system::instance();
/* Create an editing form */
$mform = new service_backup_form($PAGE->url);
/* Cancel processing */
if ($mform->is_cancelled()) {
redirect($managerservice);
}
/* Processing the received file */
if (!empty($data = $mform->get_data())) {
$content = $mform->get_file_content('backupfile');
local_webhooks_restore_backup($content);
redirect($managerservice, new lang_string('restorefinished', 'local_webhooks'));
}
/* The page title */
$titlepage = new lang_string('backup', 'local_webhooks');
$PAGE->navbar->add($titlepage);
$PAGE->set_heading($titlepage);
$PAGE->set_title($titlepage);
echo $OUTPUT->header();
/* Displays the form */
$mform->display();
echo $OUTPUT->footer();
-82
View File
@@ -1,82 +0,0 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Page of the service editor.
*
* @copyright 2018 'Valentin Popov' <info@valentineus.link>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @package local_webhooks
*/
require_once(__DIR__ . '/../../config.php');
require_once($CFG->dirroot . '/local/webhooks/classes/ui_forms_plugin.php');
require_once($CFG->dirroot . '/local/webhooks/lib.php');
require_once($CFG->libdir . '/adminlib.php');
$serviceid = optional_param('serviceid', 0, PARAM_INT);
$urlparameters = array('serviceid' => $serviceid);
$baseurl = new moodle_url('/local/webhooks/service.php', $urlparameters);
$mainpage = new moodle_url('/local/webhooks/index.php');
admin_externalpage_setup('local_webhooks', '', null, $baseurl, array());
$context = context_system::instance();
$mform = new local_webhooks_service_edit_form($PAGE->url);
$formdata = (array) $mform->get_data();
/* Cancel */
if ($mform->is_cancelled()) {
redirect($mainpage);
}
/* Updating the data */
if (!empty($formdata) && confirm_sesskey()) {
if (isset($formdata['events'])) {
$formdata['events'] = array_keys($formdata['events']);
}
if (!empty($serviceid)) {
$formdata['id'] = $serviceid;
local_webhooks_api::update_service($formdata);
} else {
local_webhooks_api::create_service($formdata);
}
redirect($mainpage, new lang_string('changessaved', 'moodle'));
}
/* Loading service data */
if (!empty($serviceid)) {
$service = local_webhooks_api::get_service($serviceid);
$service->events = array_fill_keys($service->events, 1);
$mform->set_data($service);
}
/* The page title */
$titlepage = new lang_string('externalservice', 'webservice');
$PAGE->navbar->add($titlepage);
$PAGE->set_heading($titlepage);
$PAGE->set_title($titlepage);
echo $OUTPUT->header();
/* Displays the form */
$mform->display();
/* Footer */
echo $OUTPUT->footer();
+4 -5
View File
@@ -17,18 +17,17 @@
/**
* Settings of the plugin.
*
* @copyright 2018 'Valentin Popov' <info@valentineus.link>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @package local_webhooks
* @copyright 2017 "Valentin Popov" <info@valentineus.link>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
/* @var \admin_root $ADMIN */
if ($hassiteconfig) {
$ADMIN->add(
'server', new admin_externalpage(
'server',
new admin_externalpage(
'local_webhooks',
new lang_string('pluginname', 'local_webhooks'),
new moodle_url('/local/webhooks/index.php')
-364
View File
@@ -1,364 +0,0 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
defined('MOODLE_INTERNAL') || die();
global $CFG;
require_once($CFG->dirroot . '/local/webhooks/classes/local/api.php');
use local_webhooks\local\api;
use local_webhooks\local\record;
/**
* Testing the API plugin class.
*
* @copyright 2019 'Valentin Popov' <info@valentineus.link>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
final class local_webhooks_api_testcase extends advanced_testcase {
/**
* Generate random an event's list.
*
* @return array
*
* @throws \ReflectionException
*/
private static function get_random_events(): array {
$result = array_rand(api::get_events(), random_int(2, 10));
return is_array($result) ? $result : [];
}
/**
* Generate a random record.
*
* @return \local_webhooks\local\record
*
* @throws \ReflectionException
*/
private static function get_random_record(): record {
$record = new record();
$record->events = self::get_random_events();
$record->header = 'application/json';
$record->name = uniqid('', false);
$record->point = 'http://example.org/' . urlencode($record->name);
$record->status = true;
$record->token = generate_uuid();
return $record;
}
/**
* Testing creation of the service.
*
* @group local_webhooks
*
* @throws \dml_exception
* @throws \moodle_exception
* @throws \ReflectionException
*/
public function test_adding() {
global $DB;
$this->resetAfterTest();
$record = self::get_random_record();
$record->id = api::add_service($record);
$events = $DB->get_records(LW_TABLE_EVENTS);
$services = $DB->get_records(LW_TABLE_SERVICES);
self::assertCount(1, $services);
$service = array_shift($services);
self::assertEquals($record->header, $service->header);
self::assertEquals($record->id, $service->id);
self::assertEquals($record->name, $service->name);
self::assertEquals($record->point, $service->point);
self::assertEquals($record->status, (bool) $service->status);
self::assertEquals($record->token, $service->token);
self::assertCount(count($record->events), $events);
foreach ($events as $event) {
self::assertContains($event->name, $record->events);
self::assertEquals($record->id, $event->serviceid);
}
}
/**
* Test deletion of the service.
*
* @group local_webhooks
*
* @throws \dml_exception
* @throws \moodle_exception
* @throws \ReflectionException
*/
public function test_deleting() {
global $DB;
$this->resetAfterTest();
// Testing correct delete record of the database.
$record = self::get_random_record();
$record->id = api::add_service($record);
self::assertTrue(api::del_service($record->id));
self::assertCount(0, $DB->get_records(LW_TABLE_EVENTS));
self::assertCount(0, $DB->get_records(LW_TABLE_SERVICES));
$ids = [];
$total = random_int(5, 20);
// Testing correct delete record of the record's list.
for ($i = 0; $i < $total; $i++) {
$record = self::get_random_record();
$ids[] = api::add_service($record);
}
self::assertEquals(count($ids), api::get_total_count());
self::assertTrue(api::del_service($ids[array_rand($ids, 1)]));
self::assertEquals(count($ids) - 1, api::get_total_count());
}
/**
* Testing get an event's list.
*
* @group local_webhooks
*
* @throws \ReflectionException
*/
public function test_get_events() {
$this->resetAfterTest();
$events = api::get_events();
self::assertNotCount(0, $events);
foreach ($events as $event) {
self::assertInternalType('array', $event);
self::assertEquals([
'eventname', 'component', 'target', 'action', 'crud', 'edulevel', 'objecttable',
], array_keys($event));
}
}
/**
* Testing get to a service.
*
* @group local_webhooks
*
* @throws \dml_exception
* @throws \moodle_exception
* @throws \ReflectionException
*/
public function test_get_service() {
$this->resetAfterTest();
$record = self::get_random_record();
$record->id = api::add_service($record);
$service = api::get_service($record->id);
self::assertEquals($record->header, $service->header);
self::assertEquals($record->id, $service->id);
self::assertEquals($record->name, $service->name);
self::assertEquals($record->point, $service->point);
self::assertEquals($record->status, (bool) $service->status);
self::assertEquals($record->token, $service->token);
self::assertInternalType('array', $service->events);
self::assertCount(count($record->events), $service->events);
foreach ($service->events as $event) {
self::assertContains($event, $record->events);
}
}
/**
* Testing get to the list services.
*
* @group local_webhooks
*
* @throws \dml_exception
* @throws \moodle_exception
* @throws \ReflectionException
*/
public function test_get_services() {
$this->resetAfterTest();
$records = [];
$total = random_int(5, 20);
for ($i = 0; $i < $total; $i++) {
$record = self::get_random_record();
$record->id = api::add_service($record);
$records[$record->id] = $record;
}
$services = api::get_services();
self::assertCount(count($records), $services);
foreach ($services as $service) {
$record = $records[$service->id];
self::assertEquals($record->header, $service->header);
self::assertEquals($record->id, $service->id);
self::assertEquals($record->name, $service->name);
self::assertEquals($record->point, $service->point);
self::assertEquals($record->status, $service->status);
self::assertEquals($record->token, $service->token);
self::assertInternalType('array', $service->events);
self::assertCount(count($record->events), $service->events);
foreach ($service->events as $event) {
self::assertContains($event, $record->events);
}
}
}
/**
* Testing get to the list services by event name.
*
* @group local_webhooks
*
* @throws \dml_exception
* @throws \moodle_exception
* @throws \ReflectionException
*/
public function test_get_services_by_event() {
$this->resetAfterTest();
$eventname = generate_uuid();
$limit = random_int(1, 5);
$total = random_int(5, 20);
$ids = [];
for ($i = 0; $i < $total; $i++) {
$record = self::get_random_record();
$record->events[] = $i < $limit ? $eventname : '';
$ids[] = api::add_service($record);
}
self::assertEquals(count($ids), api::get_total_count());
$services = api::get_services_by_event($eventname);
self::assertCount($limit, $services);
foreach ($services as $service) {
self::assertContains($service->id, $ids);
}
}
/**
* Testing get to the list services with conditions.
*
* @group local_webhooks
*
* @throws \dml_exception
* @throws \moodle_exception
* @throws \ReflectionException
*/
public function test_get_services_with_conditions() {
$this->resetAfterTest();
$records = [];
$total = random_int(5, 20);
$limit = intdiv($total, 2);
// Creating some records.
for ($i = 0; $i < $total; $i++) {
$record = self::get_random_record();
$record->id = api::add_service($record);
$records[] = $record;
}
// Testing condition fields.
$record = $records[array_rand($records, 1)];
self::assertCount(1, api::get_services([
'point' => $record->point,
]));
// Testing limit fields.
self::assertCount($limit, api::get_services([], null, 1, $limit));
// Testing sort fields.
$service1 = api::get_services(null, 'id asc')[0];
$service2 = api::get_services(null, 'id desc')[0];
self::assertNotEquals($service1->id, $service2->id);
}
/**
* Testing get a total count of existing records.
*
* @throws \coding_exception
* @throws \dml_exception
* @throws \ReflectionException
*/
public function test_total() {
$this->resetAfterTest();
$total = random_int(5, 20);
for ($i = 0; $i < $total; $i++) {
$record = self::get_random_record();
api::add_service($record);
}
self::assertEquals($total, api::get_total_count());
}
/**
* Testing of the service update.
*
* @group local_webhooks
*
* @throws \dml_exception
* @throws \moodle_exception
* @throws \ReflectionException
*/
public function test_updating() {
global $DB;
$this->resetAfterTest();
$record1 = self::get_random_record();
$record2 = self::get_random_record();
$record2->id = api::add_service($record1);
self::assertTrue(api::set_service($record2));
$events = $DB->get_records(LW_TABLE_EVENTS);
$services = $DB->get_records(LW_TABLE_SERVICES);
self::assertCount(1, $services);
$service = array_shift($services);
self::assertEquals($record2->header, $service->header);
self::assertEquals($record2->id, $service->id);
self::assertEquals($record2->name, $service->name);
self::assertEquals($record2->point, $service->point);
self::assertEquals($record2->status, (bool) $service->status);
self::assertEquals($record2->token, $service->token);
self::assertCount(count($record2->events), $events);
foreach ($events as $event) {
self::assertContains($event->name, $record2->events);
self::assertEquals($record2->id, $event->serviceid);
}
}
}
+91
View File
@@ -0,0 +1,91 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Runtime autonomy tests.
*
* @package local_webhooks
* @copyright 2026 "Valentin Popov" <info@valentineus.link>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace local_webhooks;
/**
* Runtime autonomy tests.
*/
#[\PHPUnit\Framework\Attributes\CoversFunction('local_webhooks_get_event_choices')]
final class autonomy_test extends \advanced_testcase {
/**
* Event choices keep their storage format and custom event names are strings.
*/
public function test_event_contracts(): void {
global $CFG;
require_once($CFG->dirroot . '/local/webhooks/lib.php');
require_once($CFG->dirroot . '/local/webhooks/classes/service_edit_form.php');
$debugsettings = [$CFG->debug, $CFG->debugdisplay, $CFG->debugdeveloper];
$choices = \local_webhooks_get_event_choices();
$this->assertNotEmpty($choices);
$this->assertSame($debugsettings, [$CFG->debug, $CFG->debugdisplay, $CFG->debugdeveloper]);
foreach ($choices as $component => $events) {
foreach ($events as $key => $eventname) {
$classname = ltrim($eventname, '\\');
$this->assertSame(base64_encode($eventname), $key);
$this->assertSame($component, \core_component::get_component_from_classname($classname));
$this->assertTrue(is_subclass_of($classname, \core\event\base::class));
$this->assertFalse((new \ReflectionClass($classname))->isAbstract());
$this->assertFalse($classname::is_deprecated());
}
}
$coreevent = '\\' . \core\event\user_created::class;
$localevent = '\\' . \local_webhooks\event\service_added::class;
$unknown = '\\' . \core\event\unknown_logged::class;
$deprecated = '\\' . \core\event\role_capabilities_updated::class;
$this->assertSame($coreevent, $choices['core'][base64_encode($coreevent)]);
$this->assertSame($localevent, $choices['local_webhooks'][base64_encode($localevent)]);
$this->assertArrayNotHasKey(base64_encode($unknown), $choices['core']);
$this->assertArrayNotHasKey(base64_encode($deprecated), $choices['core']);
$events = [
\local_webhooks\event\backup_performed::class => 'create',
\local_webhooks\event\backup_restored::class => 'update',
\local_webhooks\event\response_answer::class => 'answer',
\local_webhooks\event\service_added::class => 'create',
\local_webhooks\event\service_deleted::class => 'deleted',
\local_webhooks\event\service_updated::class => 'update',
];
foreach ($events as $event => $stringkey) {
$name = $event::get_name();
$this->assertIsString($name);
$this->assertNotSame('', trim($name));
$this->assertSame(get_string($stringkey, 'local_webhooks'), $name);
}
$this->assertFalse(class_exists('report_eventlist_list_generator', false));
$form = new \service_edit_form(new \moodle_url('/local/webhooks/editservice.php'));
$html = $form->render();
$this->assertStringContainsString($coreevent, $html);
$this->assertStringContainsString($localevent, $html);
$this->assertFalse(class_exists('report_eventlist_list_generator', false));
}
}
-386
View File
@@ -1,386 +0,0 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
defined('MOODLE_INTERNAL') || die();
global $CFG;
require_once($CFG->dirroot . '/local/webhooks/externallib.php');
require_once($CFG->dirroot . '/webservice/tests/helpers.php');
use local_webhooks\local\api;
use local_webhooks\local\record;
/**
* Testing external functions.
*
* @copyright 2019 'Valentin Popov' <info@valentineus.link>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
final class local_webhooks_external_testcase extends externallib_advanced_testcase {
/**
* Generate random an event's list.
*
* @return array
*
* @throws \ReflectionException
*/
private static function get_random_events(): array {
$result = array_rand(api::get_events(), random_int(2, 10));
return is_array($result) ? $result : [];
}
/**
* Generate a random record.
*
* @return \local_webhooks\local\record
*
* @throws \ReflectionException
*/
private static function get_random_record(): record {
$record = new record();
$record->events = self::get_random_events();
$record->header = 'application/json';
$record->name = uniqid('', false);
$record->point = 'http://example.org/' . urlencode($record->name);
$record->status = true;
$record->token = generate_uuid();
return $record;
}
/**
* Testing external add service.
*
* @throws \ReflectionException
* @throws \coding_exception
* @throws \dml_exception
* @throws \invalid_parameter_exception
* @throws \invalid_response_exception
* @throws \restricted_context_exception
*/
public function test_adding() {
$this->resetAfterTest();
self::setAdminUser();
$record = self::get_random_record();
$return = local_webhooks_external::add_service((array) $record);
$return = external_api::clean_returnvalue(local_webhooks_external::add_service_returns(), $return);
self::assertInternalType('integer', $return);
self::assertEquals(1, api::get_total_count());
$service = api::get_service($return);
self::assertEquals($record->header, $service->header);
self::assertEquals($record->name, $service->name);
self::assertEquals($record->point, $service->point);
self::assertEquals($record->status, $service->status);
self::assertEquals($record->token, $service->token);
self::assertEquals($return, $service->id);
self::assertInternalType('array', $service->events);
self::assertCount(count($record->events), $service->events);
foreach ($service->events as $event) {
self::assertContains($event, $record->events);
}
}
/**
* Testing the external delete service.
*
* @throws \ReflectionException
* @throws \coding_exception
* @throws \dml_exception
* @throws \invalid_parameter_exception
* @throws \invalid_response_exception
* @throws \restricted_context_exception
*/
public function test_deleting() {
$this->resetAfterTest();
self::setAdminUser();
// Testing correct delete record of the database.
$record = self::get_random_record();
$record->id = api::add_service($record);
$return = local_webhooks_external::del_service($record->id);
$return = external_api::clean_returnvalue(local_webhooks_external::del_service_returns(), $return);
self::assertEquals(0, api::get_total_count());
self::assertInternalType('bool', $return);
$ids = [];
$total = random_int(5, 20);
// Testing correct delete record of the record's list.
for ($i = 0; $i < $total; $i++) {
$record = self::get_random_record();
$ids[] = api::add_service($record);
}
self::assertEquals(count($ids), api::get_total_count());
$return = local_webhooks_external::del_service($ids[array_rand($ids, 1)]);
$return = external_api::clean_returnvalue(local_webhooks_external::del_service_returns(), $return);
self::assertEquals(count($ids) - 1, api::get_total_count());
self::assertInternalType('bool', $return);
}
/**
* Testing external function get the event's list.
*
* @throws \ReflectionException
* @throws \dml_exception
* @throws \invalid_parameter_exception
* @throws \invalid_response_exception
* @throws \restricted_context_exception
*/
public function test_get_events() {
$this->resetAfterTest();
self::setAdminUser();
$return = local_webhooks_external::get_events();
$return = external_api::clean_returnvalue(local_webhooks_external::get_events_returns(), $return);
self::assertInternalType('array', $return);
self::assertCount(count(api::get_events()), $return);
foreach ($return as $item) {
self::assertInternalType('array', $item);
self::assertEquals([
'action', 'component', 'crud', 'edulevel', 'eventname', 'objecttable', 'target',
], array_keys($item));
}
}
/**
* Testing external get record's data.
*
* @throws \ReflectionException
* @throws \coding_exception
* @throws \dml_exception
* @throws \invalid_parameter_exception
* @throws \invalid_response_exception
* @throws \restricted_context_exception
*/
public function test_get_service() {
$this->resetAfterTest();
self::setAdminUser();
// Creating a new record.
$record = self::get_random_record();
$record->id = api::add_service($record);
$return = local_webhooks_external::get_service($record->id);
$return = external_api::clean_returnvalue(local_webhooks_external::get_service_returns(), $return);
self::assertInternalType('array', $return);
// Testing the main fields.
self::assertEquals($record->header, $return['header']);
self::assertEquals($record->id, $return['id']);
self::assertEquals($record->name, $return['name']);
self::assertEquals($record->point, $return['point']);
self::assertEquals($record->status, (int) $return['status']);
self::assertEquals($record->token, $return['token']);
// Testing an event's list.
self::assertInternalType('array', $return['events']);
self::assertNotCount(0, $return['events']);
foreach ($return['events'] as $event) {
self::assertContains($event, $record->events);
}
}
/**
* Testing external get the record's list.
*
* @throws \ReflectionException
* @throws \coding_exception
* @throws \dml_exception
* @throws \invalid_parameter_exception
* @throws \invalid_response_exception
* @throws \restricted_context_exception
*/
public function test_get_services() {
$this->resetAfterTest();
self::setAdminUser();
$records = [];
$total = random_int(5, 10);
// Creating some records.
for ($i = 0; $i < $total; $i++) {
$record = self::get_random_record();
$record->id = api::add_service($record);
$records[$record->id] = $record;
}
self::assertEquals(count($records), api::get_total_count());
$return = local_webhooks_external::get_services();
$return = external_api::clean_returnvalue(local_webhooks_external::get_services_returns(), $return);
// Testing received item's list.
self::assertInternalType('array', $return);
self::assertCount(count($records), $return);
foreach ($return as $item) {
self::assertInternalType('array', $item);
$record = $records[$item['id']];
self::assertEquals($record->header, $item['header']);
self::assertEquals($record->id, $item['id']);
self::assertEquals($record->name, $item['name']);
self::assertEquals($record->point, $item['point']);
self::assertEquals($record->status, (int) $item['status']);
self::assertEquals($record->token, $item['token']);
self::assertInternalType('array', $item['events']);
self::assertNotCount(0, $item['events']);
foreach ($item['events'] as $event) {
self::assertContains($event, $record->events);
}
}
}
/**
* Testing external get to the list services with conditions.
*
* @throws \ReflectionException
* @throws \coding_exception
* @throws \dml_exception
* @throws \invalid_parameter_exception
* @throws \invalid_response_exception
* @throws \restricted_context_exception
*/
public function test_get_services_with_conditions() {
$this->resetAfterTest();
self::setAdminUser();
$records = [];
$total = random_int(5, 10);
$limit = intdiv($total, 2);
// Creating some records.
for ($i = 0; $i < $total; $i++) {
$record = self::get_random_record();
$record->id = api::add_service($record);
$records[$record->id] = $record;
}
self::assertEquals(count($records), api::get_total_count());
// Testing condition fields.
$record = $records[array_rand($records, 1)];
$return = local_webhooks_external::get_services(['point' => $record->point]);
$return = external_api::clean_returnvalue(local_webhooks_external::get_services_returns(), $return);
self::assertCount(1, $return);
self::assertEquals($return[0]['id'], $record->id);
// Testing limit fields.
$return = local_webhooks_external::get_services(null, null, 1, $limit);
$return = external_api::clean_returnvalue(local_webhooks_external::get_services_returns(), $return);
self::assertCount($limit, $return);
// Testing sort fields.
$return = local_webhooks_external::get_services(null, 'id asc');
$return = external_api::clean_returnvalue(local_webhooks_external::get_services_returns(), $return);
$service1 = array_shift($return);
$return = local_webhooks_external::get_services(null, 'id desc');
$return = external_api::clean_returnvalue(local_webhooks_external::get_services_returns(), $return);
$service2 = array_shift($return);
self::assertNotEquals($service1['id'], $service2['id']);
}
/**
* Testing full update parameters of the service.
*
* @throws \ReflectionException
* @throws \coding_exception
* @throws \dml_exception
* @throws \invalid_parameter_exception
* @throws \restricted_context_exception
*/
public function test_updating_full() {
$this->resetAfterTest();
self::setAdminUser();
$record = self::get_random_record();
$record2 = self::get_random_record();
$record2->id = api::add_service($record);
$return = local_webhooks_external::set_service((array) $record2);
$return = external_api::validate_parameters(local_webhooks_external::set_service_returns(), $return);
self::assertInternalType('bool', $return);
$service = api::get_service($record2->id);
self::assertEquals($record2->id, $service->id);
self::assertEquals($record2->header, $service->header);
self::assertEquals($record2->name, $service->name);
self::assertEquals($record2->point, $service->point);
self::assertEquals($record2->status, $service->status);
self::assertEquals($record2->token, $service->token);
self::assertInternalType('array', $service->events);
self::assertCount(count($record2->events), $service->events);
foreach ($service->events as $event) {
self::assertContains($event, $record2->events);
}
}
/**
* Testing selective update parameters of the service.
*
* @throws \ReflectionException
* @throws \coding_exception
* @throws \dml_exception
* @throws \invalid_parameter_exception
* @throws \restricted_context_exception
*/
public function test_updating_short() {
$this->resetAfterTest();
self::setAdminUser();
$record = self::get_random_record();
$record2 = self::get_random_record();
$record->id = api::add_service($record);
$return = local_webhooks_external::set_service(['id' => $record->id, 'name' => $record2->name, 'point' => $record2->point]);
$return = external_api::validate_parameters(local_webhooks_external::set_service_returns(), $return);
self::assertInternalType('bool', $return);
$service = api::get_service($record->id);
self::assertEquals($record->header, $service->header);
self::assertEquals($record->id, $service->id);
self::assertEquals($record->status, $service->status);
self::assertEquals($record->token, $service->token);
self::assertEquals($record2->name, $service->name);
self::assertEquals($record2->point, $service->point);
self::assertInternalType('array', $service->events);
self::assertCount(count($record->events), $service->events);
foreach ($service->events as $event) {
self::assertContains($event, $record->events);
}
}
}
-205
View File
@@ -1,205 +0,0 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
defined('MOODLE_INTERNAL') || die();
global $CFG;
require_once($CFG->dirroot . '/local/webhooks/classes/local/api.php');
use core\event\course_created;
use core\task\manager;
use local_webhooks\local\api;
use local_webhooks\local\record;
use local_webhooks\task\notify;
/**
* Class local_webhooks_task_testcase.
*
* @copyright 2019 'Valentin Popov' <info@valentineus.link>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
final class local_webhooks_task_testcase extends advanced_testcase {
const EVENTNAME = '\\' . course_created::class;
/**
* Generate a random record.
*
* @return \local_webhooks\local\record
*/
private static function get_random_record(): record {
$record = new record();
$record->events = [self::EVENTNAME];
$record->header = 'application/json';
$record->name = uniqid('', false);
$record->point = 'http://example.org/' . urlencode($record->name);
$record->status = true;
$record->token = generate_uuid();
return $record;
}
/**
* Testing add a task to the queue.
*/
public function test_add_task() {
global $DB;
$DB->delete_records('task_adhoc');
$this->resetAfterTest();
manager::queue_adhoc_task(new notify());
$tasks = manager::get_adhoc_tasks(notify::class);
self::assertCount(1, $tasks);
self::assertInstanceOf(notify::class, array_shift($tasks));
}
/**
* Testing disabled processing service.
*
* @throws \coding_exception
* @throws \dml_exception
*/
public function test_execute_disabled() {
global $DB;
$DB->delete_records('task_adhoc');
curl::mock_response('{}');
$this->resetAfterTest();
$record = self::get_random_record();
$record->status = false;
$record->id = api::add_service($record);
$task = new notify();
$task->set_custom_data(['eventname' => self::EVENTNAME]);
$task->execute();
self::assertNull($task->debug);
}
/**
* Testing enabled processing service.
*
* @throws \coding_exception
* @throws \dml_exception
*/
public function test_execute_enabled() {
global $DB;
$DB->delete_records('task_adhoc');
curl::mock_response('{}');
$this->resetAfterTest();
$record = self::get_random_record();
$record->id = api::add_service($record);
$task = new notify();
$task->set_custom_data(['eventname' => self::EVENTNAME]);
$task->execute();
self::assertCount(1, $task->debug);
self::assertInternalType('array', $task->debug);
$element = array_shift($task->debug);
self::assertInternalType('array', $element['data']);
self::assertInternalType('object', $element['service']);
self::assertEquals($record->events[0], $element['data']['eventname']);
self::assertEquals($record->id, $element['service']->id);
self::assertEquals($record->token, $element['data']['token']);
}
/**
* Testing count creating tasks.
*
* @throws \coding_exception
* @throws \dml_exception
*/
public function test_observer_multiple() {
global $DB;
$DB->delete_records('task_adhoc');
curl::mock_response('{}');
$this->resetAfterTest();
$generator = self::getDataGenerator();
$record = self::get_random_record();
$record->id = api::add_service($record);
$total = random_int(5, 20);
for ($i = 0; $i < $total; $i++) {
$generator->create_course();
}
$debug = [];
foreach (manager::get_adhoc_tasks(notify::class) as $event) {
self::assertInstanceOf(notify::class, $event);
/** @var \local_webhooks\task\notify $event */
$event->execute();
if (isset($event->debug) && is_array($event->debug)) {
$debug[] = array_merge(...$event->debug);
}
}
self::assertCount($total, $debug);
}
/**
* Testing structure a creating task.
*
* @throws \coding_exception
* @throws \dml_exception
*/
public function test_observer_single() {
global $DB;
$DB->delete_records('task_adhoc');
curl::mock_response('{}');
$this->resetAfterTest();
$generator = self::getDataGenerator();
$record = self::get_random_record();
$record->id = api::add_service($record);
$course = $generator->create_course();
$debug = [];
foreach (manager::get_adhoc_tasks(notify::class) as $event) {
self::assertInstanceOf(notify::class, $event);
/** @var \local_webhooks\task\notify $event */
$event->execute();
if (isset($event->debug) && is_array($event->debug)) {
$debug[] = array_merge(...$event->debug);
}
}
self::assertCount(1, $debug);
$element = array_shift($debug);
self::assertInternalType('array', $element['data']);
self::assertEquals($course->id, $element['data']['courseid']);
}
}
+12 -4
View File
@@ -14,10 +14,18 @@
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Information about the version of the plugin.
*
* @package local_webhooks
* @copyright 2017 "Valentin Popov" <info@valentineus.link>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$plugin->component = 'local_webhooks';
$plugin->maturity = MATURITY_ALPHA;
$plugin->release = '5.0.0-rc.1 (Build: 2019040100)';
$plugin->requires = 2016052300;
$plugin->version = 2019040100;
$plugin->maturity = MATURITY_STABLE;
$plugin->release = '3.0.5 (Build: 2020051600)';
$plugin->requires = 2019052000;
$plugin->version = 2020051600;