first commit

This commit is contained in:
CHIEFSOFT\ameye
2024-09-30 18:11:26 -04:00
commit e592ca6823
27270 changed files with 5002257 additions and 0 deletions
@@ -0,0 +1,483 @@
<?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/>.
/**
* Incoming Message address manager.
*
* @package core_message
* @copyright 2014 Andrew Nicols <andrew@nicols.co.uk>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace core\message\inbound;
defined('MOODLE_INTERNAL') || die();
/**
* Incoming Message address manager.
*
* @copyright 2014 Andrew Nicols <andrew@nicols.co.uk>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class address_manager {
/**
* @var int The size of the hash component of the address.
* Note: Increasing this value will invalidate all previous key values
* and reduce the potential length of the e-mail address being checked.
* Do not change this value.
*/
const HASHSIZE = 24;
/**
* @var int A validation status indicating successful validation
*/
const VALIDATION_SUCCESS = 0;
/**
* @var int A validation status indicating an invalid address format.
* Typically this is an address which does not contain a subaddress or
* all of the required data.
*/
const VALIDATION_INVALID_ADDRESS_FORMAT = 1;
/**
* @var int A validation status indicating that a handler could not
* be found for this address.
*/
const VALIDATION_UNKNOWN_HANDLER = 2;
/**
* @var int A validation status indicating that an unknown user was specified.
*/
const VALIDATION_UNKNOWN_USER = 4;
/**
* @var int A validation status indicating that the data key specified could not be found.
*/
const VALIDATION_UNKNOWN_DATAKEY = 8;
/**
* @var int A validation status indicating that the mail processing handler was not enabled.
*/
const VALIDATION_DISABLED_HANDLER = 16;
/**
* @var int A validation status indicating that the user specified was deleted or unconfirmed.
*/
const VALIDATION_DISABLED_USER = 32;
/**
* @var int A validation status indicating that the datakey specified had reached it's expiration time.
*/
const VALIDATION_EXPIRED_DATAKEY = 64;
/**
* @var int A validation status indicating that the hash could not be verified.
*/
const VALIDATION_INVALID_HASH = 128;
/**
* @var int A validation status indicating that the originator address did not match the user on record.
*/
const VALIDATION_ADDRESS_MISMATCH = 256;
/**
* The handler for the subsequent Inbound Message commands.
* @var \core\message\inbound\handler
*/
private $handler;
/**
* The ID of the data record
* @var int
*/
private $datavalue;
/**
* The ID of the data record
* @var string
*/
private $datakey;
/**
* The processed data record.
* @var \stdClass
*/
private $record;
/**
* The user.
* @var \stdClass
*/
private $user;
/**
* Set the handler to use for the subsequent Inbound Message commands.
*
* @param string $classname The name of the class for the handler.
*/
public function set_handler($classname) {
$this->handler = manager::get_handler($classname);
}
/**
* Return the active handler.
*
* @return \core\message\inbound\handler|null;
*/
public function get_handler() {
return $this->handler;
}
/**
* Specify an integer data item value for this record.
*
* @param int $datavalue The value of the data item.
* @param string $datakey A hash to use for the datakey
*/
public function set_data($datavalue, $datakey = null) {
$this->datavalue = $datavalue;
// We must clear the datakey when changing the datavalue.
$this->set_data_key($datakey);
}
/**
* Specify a known data key for this data item.
*
* If specified, the datakey must already exist in the messageinbound_datakeys
* table, typically as a result of a previous Inbound Message setup.
*
* This is intended as a performance optimisation when sending many
* e-mails with different data to many users.
*
* @param string $datakey A hash to use for the datakey
*/
public function set_data_key($datakey = null) {
$this->datakey = $datakey;
}
/**
* Return the data key for the data item.
*
* If no data key has been defined yet, this will call generate_data_key() to generate a new key on the fly.
* @return string The secret key for this data item.
*/
public function fetch_data_key() {
global $CFG, $DB;
// Only generate a key if Inbound Message is actually enabled, and the handler is enabled.
if (!isset($CFG->messageinbound_enabled) || !$this->handler || !$this->handler->enabled) {
return null;
}
if (!isset($this->datakey)) {
// Attempt to fetch an existing key first if one has not already been specified.
$datakey = $DB->get_field('messageinbound_datakeys', 'datakey', array(
'handler' => $this->handler->id,
'datavalue' => $this->datavalue,
));
if (!$datakey) {
$datakey = $this->generate_data_key();
}
$this->datakey = $datakey;
}
return $this->datakey;
}
/**
* Generate a new secret key for the current data item and handler combination.
*
* @return string The new generated secret key for this data item.
*/
protected function generate_data_key() {
global $DB;
$key = new \stdClass();
$key->handler = $this->handler->id;
$key->datavalue = $this->datavalue;
$key->datakey = md5($this->datavalue . '_' . time() . random_string(40));
$key->timecreated = time();
if ($this->handler->defaultexpiration) {
// Apply the default expiration time to the datakey.
$key->expires = $key->timecreated + $this->handler->defaultexpiration;
}
$DB->insert_record('messageinbound_datakeys', $key);
return $key->datakey;
}
/**
* Generate an e-mail address for the Inbound Message handler, storing a private
* key for the data object if one was not specified.
*
* @param int $userid The ID of the user to generated an address for.
* @param string $userkey The unique key for this user. If not specified this will be retrieved using
* get_user_key(). This key must have been created using get_user_key(). This parameter is provided as a performance
* optimisation for when generating multiple addresses for the same user.
* @return string|null The generated address, or null if an address could not be generated.
*/
public function generate($userid, $userkey = null) {
global $CFG;
// Ensure that Inbound Message is enabled and that there is enough information to proceed.
if (!manager::is_enabled()) {
return null;
}
if ($userkey == null) {
$userkey = get_user_key('messageinbound_handler', $userid);
}
// Ensure that the minimum requirements are in place.
if (!isset($this->handler) || !$this->handler) {
throw new \coding_exception('Inbound Message handler not specified.');
}
// Ensure that the requested handler is actually enabled.
if (!$this->handler->enabled) {
return null;
}
if (!isset($this->datavalue)) {
throw new \coding_exception('Inbound Message data item has not been specified.');
}
$data = array(
self::pack_int($this->handler->id),
self::pack_int($userid),
self::pack_int($this->datavalue),
pack('H*', substr(md5($this->fetch_data_key() . $userkey), 0, self::HASHSIZE)),
);
$subaddress = base64_encode(implode($data));
return $CFG->messageinbound_mailbox . '+' . $subaddress . '@' . $CFG->messageinbound_domain;
}
/**
* Determine whether the supplied address is of the correct format.
*
* @param string $address The address to test
* @return bool Whether the address matches the correct format
*/
public static function is_correct_format($address) {
global $CFG;
// Messages must match the format mailbox+[data]@domain.
return preg_match('/' . $CFG->messageinbound_mailbox . '\+[^@]*@' . $CFG->messageinbound_domain . '/', $address);
}
/**
* Process an inbound address to obtain the data stored within it.
*
* @param string $address The fully formed e-mail address to process.
*/
protected function process($address) {
global $DB;
if (!self::is_correct_format($address)) {
// This address does not contain a subaddress to parse.
return;
}
// Ensure that the instance record is empty.
$this->record = null;
$record = new \stdClass();
$record->address = $address;
list($localpart) = explode('@', $address, 2);
list($record->mailbox, $encodeddata) = explode('+', $localpart, 2);
$data = base64_decode($encodeddata, true);
if (!$data) {
// This address has no valid data.
return;
}
$content = @unpack('N2handlerid/N2userid/N2datavalue/H*datakey', $data);
if (!$content) {
// This address has no data.
return;
}
if (PHP_INT_SIZE === 8) {
// 64-bit machine.
$content['handlerid'] = $content['handlerid1'] << 32 | $content['handlerid2'];
$content['userid'] = $content['userid1'] << 32 | $content['userid2'];
$content['datavalue'] = $content['datavalue1'] << 32 | $content['datavalue2'];
} else {
if ($content['handlerid1'] > 0 || $content['userid1'] > 0 || $content['datavalue1'] > 0) {
// Any 64-bit integer which is greater than the 32-bit integer size will have a non-zero value in the first
// half of the integer.
throw new \moodle_exception('Mixed environment.' .
' Key generated with a 64-bit machine but received into a 32-bit machine.');
}
$content['handlerid'] = $content['handlerid2'];
$content['userid'] = $content['userid2'];
$content['datavalue'] = $content['datavalue2'];
}
// Clear the 32-bit to 64-bit variables away.
unset($content['handlerid1']);
unset($content['handlerid2']);
unset($content['userid1']);
unset($content['userid2']);
unset($content['datavalue1']);
unset($content['datavalue2']);
$record = (object) array_merge((array) $record, $content);
// Fetch the user record.
$record->user = $DB->get_record('user', array('id' => $record->userid));
// Fetch and set the handler.
if ($handler = manager::get_handler_from_id($record->handlerid)) {
$this->handler = $handler;
// Retrieve the record for the data key.
$record->data = $DB->get_record('messageinbound_datakeys',
array('handler' => $handler->id, 'datavalue' => $record->datavalue));
}
$this->record = $record;
}
/**
* Retrieve the data parsed from the address.
*
* @return \stdClass the parsed data.
*/
public function get_data() {
return $this->record;
}
/**
* Ensure that the parsed data is valid, and if the handler requires address validation, validate the sender against
* the user record of identified user record.
*
* @param string $address The fully formed e-mail address to process.
* @return int The validation status.
*/
protected function validate($address) {
if (!$this->record) {
// The record does not exist, so there is nothing to validate against.
return self::VALIDATION_INVALID_ADDRESS_FORMAT;
}
// Build the list of validation errors.
$returnvalue = 0;
if (!$this->handler) {
$returnvalue += self::VALIDATION_UNKNOWN_HANDLER;
} else if (!$this->handler->enabled) {
$returnvalue += self::VALIDATION_DISABLED_HANDLER;
}
if (!isset($this->record->data) || !$this->record->data) {
$returnvalue += self::VALIDATION_UNKNOWN_DATAKEY;
} else if ($this->record->data->expires != 0 && $this->record->data->expires < time()) {
$returnvalue += self::VALIDATION_EXPIRED_DATAKEY;
} else {
if (!$this->record->user) {
$returnvalue += self::VALIDATION_UNKNOWN_USER;
} else {
if ($this->record->user->deleted || !$this->record->user->confirmed) {
$returnvalue += self::VALIDATION_DISABLED_USER;
}
$userkey = get_user_key('messageinbound_handler', $this->record->user->id);
$hashvalidation = substr(md5($this->record->data->datakey . $userkey), 0, self::HASHSIZE) == $this->record->datakey;
if (!$hashvalidation) {
// The address data did not check out, so the originator is deemed invalid.
$returnvalue += self::VALIDATION_INVALID_HASH;
}
if ($this->handler->validateaddress) {
// Validation of the sender's e-mail address is also required.
if ($address !== $this->record->user->email) {
// The e-mail address of the originator did not match the
// address held on record for this user.
$returnvalue += self::VALIDATION_ADDRESS_MISMATCH;
}
}
}
}
return $returnvalue;
}
/**
* Process the message recipient, load the handler, and then validate
* the sender with the associated data record.
*
* @param string $recipient The recipient of the message
* @param string $sender The sender of the message
*/
public function process_envelope($recipient, $sender) {
// Process the recipient address to retrieve the handler data.
$this->process($recipient);
// Validate the retrieved data against the e-mail address of the originator.
return $this->validate($sender);
}
/**
* Process the message against the relevant handler.
*
* @param \stdClass $messagedata The data for the current message being processed.
* @return mixed The result of the handler's message processor. A truthy result suggests a successful send.
*/
public function handle_message(\stdClass $messagedata) {
$this->record = $this->get_data();
return $this->handler->process_message($this->record, $messagedata);
}
/**
* Pack an integer into a pair of 32-bit numbers.
*
* @param int $int The integer to pack
* @return string The encoded binary data
*/
protected function pack_int($int) {
// If PHP environment is running on a 64-bit.
if (PHP_INT_SIZE === 8) {
// Will be used to ensures that the result remains as a 32-bit unsigned integer and
// doesn't extend beyond 32 bits.
$notation = 0xffffffff;
if ($int < 0) {
// If the given integer is negative, set it to -1.
$l = -1;
} else {
// Otherwise, calculate the upper 32 bits of the 64-bit integer.
$l = ($int >> 32) & $notation;
}
// Calculate the lower 32 bits of the 64-bit integer.
$r = $int & $notation;
// Pack the values of $l (upper 32 bits) and $r (lower 32 bits) into a binary string format.
return pack('NN', $l, $r);
} else {
// Pack the values into a binary string format.
return pack('NN', 0, $int);
}
}
}
+306
View File
@@ -0,0 +1,306 @@
<?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/>.
/**
* Abstract class describing Inbound Message Handlers.
*
* @package core_message
* @copyright 2014 Andrew Nicols
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace core\message\inbound;
/**
* Abstract class describing Inbound Message Handlers.
*
* @copyright 2014 Andrew NIcols
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*
* @property-read int $id The ID of the handler in the database
* @property-read string $component The component of this handler
* @property-read int $defaultexpiration Default expiration of new addresses for this handler
* @property-read string $description The description of this handler
* @property-read string $name The name of this handler
* @property-read bool $validateaddress Whether the address validation is a requiredment
* @property-read bool $enabled Whether this handler is currently enabled
* @property-read string $classname The name of handler class
*/
abstract class handler {
/**
* @var int $id The id of the handler in the database.
*/
private $id = null;
/**
* @var string $component The component to which this handler belongs.
*/
private $component = '';
/**
* @var int $defaultexpiration The default expiration time to use when created a new key.
*/
private $defaultexpiration = WEEKSECS;
/**
* @var bool $validateaddress Whether to validate the sender address when processing this handler.
*/
private $validateaddress = true;
/**
* @var bool $enabled Whether this handler is currently enabled.
*/
private $enabled = false;
/**
* @var $accessibleproperties A list of the properties which can be read.
*/
private $accessibleproperties = array(
'id' => true,
'component' => true,
'defaultexpiration' => true,
'validateaddress' => true,
'enabled' => true,
);
/**
* Magic getter to fetch the specified key.
*
* @param string $key The name of the key to retrieve
*/
public function __get($key) {
// Some properties have logic behind them.
$getter = 'get_' . $key;
if (method_exists($this, $getter)) {
return $this->$getter();
}
// Check for a commonly accessibly property.
if (isset($this->accessibleproperties[$key])) {
return $this->$key;
}
// Unknown property - bail.
throw new \coding_exception('unknown_property ' . $key);
}
/**
* Set the id name.
*
* @param int $id The id to set
* @return int The newly set id
*/
public function set_id($id) {
return $this->id = $id;
}
/**
* Set the component name.
*
* @param string $component The component to set
* @return string The newly set component
*/
public function set_component($component) {
return $this->component = $component;
}
/**
* Whether the current handler allows changes to the address validation
* setting.
*
* By default this will return true, but for some handlers it may be
* necessary to disallow such changes.
*
* @return boolean
*/
public function can_change_validateaddress() {
return true;
}
/**
* Set whether validation of the address is required.
*
* @param bool $validateaddress The new state of validateaddress
* @return bool
*/
public function set_validateaddress($validateaddress) {
return $this->validateaddress = $validateaddress;
}
/**
* Whether the current handler allows changes to expiry of the generated email address.
*
* By default this will return true, but for some handlers it may be
* necessary to disallow such changes.
*
* @return boolean
*/
public function can_change_defaultexpiration() {
return true;
}
/**
* Whether this handler can be disabled (or enabled).
*
* By default this will return true, but for some handlers it may be
* necessary to disallow such changes. For example, a core handler to
* handle rejected mail validation should not be disabled.
*
* @return boolean
*/
public function can_change_enabled() {
return true;
}
/**
* Set the enabled name.
*
* @param bool $enabled The new state of enabled
* @return bool
*/
public function set_enabled($enabled) {
return $this->enabled = $enabled;
}
/**
* Set the default validity for new keys.
*
* @param int $period The time in seconds before a key expires
* @return int
*/
public function set_defaultexpiration($period) {
return $this->defaultexpiration = $period;
}
/**
* Get the non-namespaced name of the current class.
*
* @return string The classname
*/
private function get_classname() {
$classname = get_class($this);
if (strpos($classname, '\\') !== 0) {
$classname = '\\' . $classname;
}
return $classname;
}
/**
* Return a description for the current handler.
*
* @return string
*/
abstract protected function get_description();
/**
* Return a name for the current handler.
* This appears in the admin pages as a human-readable name.
*
* @return string
*/
abstract protected function get_name();
/**
* Process the message against the current handler.
*
* @param \stdClass $record The Inbound Message Handler record
* @param \stdClass $messagedata The message data
*/
abstract public function process_message(\stdClass $record, \stdClass $messagedata);
/**
* Return the content of any success notification to be sent.
* Both an HTML and Plain Text variant must be provided.
*
* If this handler does not need to send a success notification, then
* it should return a falsey value.
*
* @param \stdClass $messagedata The message data.
* @param \stdClass $handlerresult The record for the newly created post.
* @return \stdClass with keys `html` and `plain`.
*/
public function get_success_message(\stdClass $messagedata, $handlerresult) {
return false;
}
/**
* Remove quoted message string from the text (NOT HTML) message.
*
* @param \stdClass $messagedata The Inbound Message record
*
* @return array message and message format to use.
*/
protected static function remove_quoted_text($messagedata) {
if (!empty($messagedata->plain)) {
$text = $messagedata->plain;
} else {
$text = html_to_text($messagedata->html);
}
$messageformat = FORMAT_PLAIN;
$splitted = preg_split("/\n|\r/", $text);
if (empty($splitted)) {
return array($text, $messageformat);
}
$i = 0;
$flag = false;
foreach ($splitted as $i => $element) {
if (stripos($element, ">") === 0) {
// Quoted text found.
$flag = true;
// Remove 2 non empty line before this.
for ($j = $i - 1; ($j >= 0); $j--) {
$element = $splitted[$j];
if (!empty($element)) {
unset($splitted[$j]);
break;
}
}
break;
}
}
if ($flag) {
// Quoted text was found.
// Retrieve everything from the start until the line before the quoted text.
$splitted = array_slice($splitted, 0, $i-1);
// Strip out empty lines towards the end, since a lot of clients add a huge chunk of empty lines.
$reverse = array_reverse($splitted);
foreach ($reverse as $i => $line) {
if (empty($line)) {
unset($reverse[$i]);
} else {
// Non empty line found.
break;
}
}
$replaced = implode(PHP_EOL, array_reverse($reverse));
$message = trim($replaced);
} else {
// No quoted text, fallback to original text.
if (!empty($messagedata->html)) {
$message = $messagedata->html;
$messageformat = FORMAT_HTML;
} else {
$message = $messagedata->plain;
}
}
return array($message, $messageformat);
}
}
+258
View File
@@ -0,0 +1,258 @@
<?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/>.
/**
* Variable Envelope Return Path management.
*
* @package core_message
* @copyright 2014 Andrew Nicols <andrew@nicols.co.uk>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace core\message\inbound;
defined('MOODLE_INTERNAL') || die();
/**
* Variable Envelope Return Path manager class.
*
* @copyright 2014 Andrew Nicols <andrew@nicols.co.uk>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class manager {
/**
* Whether the Inbound Message interface is enabled.
*
* @return bool
*/
public static function is_enabled() {
global $CFG;
// Check whether Inbound Message is enabled at all.
if (!isset($CFG->messageinbound_enabled) || !$CFG->messageinbound_enabled) {
return false;
}
// Check whether the outgoing mailbox and domain are configured properly.
if (!isset($CFG->messageinbound_mailbox) || empty($CFG->messageinbound_mailbox)) {
return false;
}
if (!isset($CFG->messageinbound_domain) || empty($CFG->messageinbound_domain)) {
return false;
}
return true;
}
/**
* Update the database to create, update, and remove handlers.
*
* @param string $componentname - The frankenstyle component name.
*/
public static function update_handlers_for_component($componentname) {
global $DB;
$componentname = \core_component::normalize_componentname($componentname);
$existinghandlers = $DB->get_recordset('messageinbound_handlers', array('component' => $componentname));
foreach ($existinghandlers as $handler) {
if (!class_exists($handler->classname)) {
self::remove_messageinbound_handler($handler);
}
}
$existinghandlers->close();
self::create_missing_messageinbound_handlers_for_component($componentname);
}
/**
* Load handler instances for all of the handlers defined in db/messageinbound_handlers.php for the specified component.
*
* @param string $componentname - The name of the component to fetch the handlers for.
* @return \core\message\inbound\handler[] - List of handlers for this component.
*/
public static function load_default_handlers_for_component($componentname) {
$componentname = \core_component::normalize_componentname($componentname);
$dir = \core_component::get_component_directory($componentname);
if (!$dir) {
return array();
}
$file = $dir . '/db/messageinbound_handlers.php';
if (!file_exists($file)) {
return array();
}
$handlers = null;
require_once($file);
if (!isset($handlers)) {
return array();
}
$handlerinstances = array();
foreach ($handlers as $handler) {
$record = (object) $handler;
$record->component = $componentname;
if ($handlerinstance = self::handler_from_record($record)) {
$handlerinstances[] = $handlerinstance;
} else {
throw new \coding_exception("Inbound Message Handler not found for '{$componentname}'.");
}
}
return $handlerinstances;
}
/**
* Update the database to contain a list of handlers for a component,
* adding any handlers which do not exist in the database.
*
* @param string $componentname - The frankenstyle component name.
*/
public static function create_missing_messageinbound_handlers_for_component($componentname) {
global $DB;
$componentname = \core_component::normalize_componentname($componentname);
$expectedhandlers = self::load_default_handlers_for_component($componentname);
foreach ($expectedhandlers as $handler) {
$recordexists = $DB->record_exists('messageinbound_handlers', array(
'component' => $componentname,
'classname' => $handler->classname,
));
if (!$recordexists) {
$record = self::record_from_handler($handler);
$record->component = $componentname;
$DB->insert_record('messageinbound_handlers', $record);
}
}
}
/**
* Remove the specified handler.
*
* @param \core\message\inbound\handler $handler The handler to remove
*/
public static function remove_messageinbound_handler($handler) {
global $DB;
// Delete Inbound Message datakeys.
$DB->delete_records('messageinbound_datakeys', array('handler' => $handler->id));
// Delete Inbound Message handlers.
$DB->delete_records('messageinbound_handlers', array('id' => $handler->id));
}
/**
* Create a flat stdClass for the handler, appropriate for inserting
* into the database.
*
* @param \core\message\inbound\handler $handler The handler to retrieve the record for.
* @return \stdClass
*/
public static function record_from_handler($handler) {
$record = new \stdClass();
$record->id = $handler->id;
$record->component = $handler->component;
$record->classname = get_class($handler);
if (strpos($record->classname, '\\') !== 0) {
$record->classname = '\\' . $record->classname;
}
$record->defaultexpiration = $handler->defaultexpiration;
$record->validateaddress = $handler->validateaddress;
$record->enabled = $handler->enabled;
return $record;
}
/**
* Load the Inbound Message handler details for a given record.
*
* @param \stdClass $record The record to retrieve the handler for.
* @return \core\message\inbound\handler or false
*/
protected static function handler_from_record($record) {
$classname = $record->classname;
if (strpos($classname, '\\') !== 0) {
$classname = '\\' . $classname;
}
if (!class_exists($classname)) {
return false;
}
$handler = new $classname;
if (isset($record->id)) {
$handler->set_id($record->id);
}
$handler->set_component($record->component);
// Overload fields which can be modified.
if (isset($record->defaultexpiration)) {
$handler->set_defaultexpiration($record->defaultexpiration);
}
if (isset($record->validateaddress)) {
$handler->set_validateaddress($record->validateaddress);
}
if (isset($record->enabled)) {
$handler->set_enabled($record->enabled);
}
return $handler;
}
/**
* Load the Inbound Message handler details for a given classname.
*
* @param string $classname The name of the class for the handler.
* @return \core\message\inbound\handler or false
*/
public static function get_handler($classname) {
global $DB;
if (strpos($classname, '\\') !== 0) {
$classname = '\\' . $classname;
}
$record = $DB->get_record('messageinbound_handlers', array('classname' => $classname), '*', IGNORE_MISSING);
if (!$record) {
return false;
}
return self::handler_from_record($record);
}
/**
* Load the Inbound Message handler with a given ID
*
* @param int $id
* @return \core\message\inbound\handler or false
*/
public static function get_handler_from_id($id) {
global $DB;
$record = $DB->get_record('messageinbound_handlers', array('id' => $id), '*', IGNORE_MISSING);
if (!$record) {
return false;
}
return self::handler_from_record($record);
}
}
@@ -0,0 +1,152 @@
<?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/>.
/**
* A Handler to store attachments sent in e-mails as private files.
*
* @package core_message
* @copyright 2014 Andrew Nicols
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace core\message\inbound;
defined('MOODLE_INTERNAL') || die();
require_once($CFG->libdir . '/filelib.php');
/**
* A Handler to store attachments sent in e-mails as private files.
*
* @package core
* @copyright 2014 Andrew Nicols
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class private_files_handler extends handler {
/**
* Email generated by this handler should not expire.
*
* @return bool
*/
public function can_change_defaultexpiration() {
return false;
}
/**
* Return a description for the current handler.
*
* @return string
*/
public function get_description() {
return get_string('private_files_handler', 'moodle');
}
/**
* Return a short name for the current handler.
* This appears in the admin pages as a human-readable name.
*
* @return string
*/
public function get_name() {
return get_string('private_files_handler_name', 'moodle');
}
/**
* Process a message received and validated by the Inbound Message processor.
*
* @throws \core\message\inbound\processing_failed_exception
* @param \stdClass $record The Inbound Message record
* @param \stdClass $data The message data packet
* @return bool Whether the message was successfully processed.
*/
public function process_message(\stdClass $record, \stdClass $data) {
global $USER, $CFG;
$context = \context_user::instance($USER->id);
if (!has_capability('moodle/user:manageownfiles', $context)) {
throw new \core\message\inbound\processing_failed_exception('emailtoprivatefilesdenied', 'moodle', $data);
}
// Initial setup.
$component = 'user';
$filearea = 'private';
$itemid = 0;
$license = $CFG->sitedefaultlicense;
$author = fullname($USER);
// Determine the quota space for this user.
$maxbytes = $CFG->userquota;
if (has_capability('moodle/user:ignoreuserquota', $context)) {
$maxbytes = USER_CAN_IGNORE_FILE_SIZE_LIMITS;
}
// Keep track of files which were uploaded, and which were skipped.
$skippedfiles = array();
$uploadedfiles = array();
$failedfiles = array();
$usedspace = file_get_user_used_space();
$fs = get_file_storage();
foreach ($data->attachments as $attachmenttype => $attachments) {
foreach ($attachments as $attachment) {
mtrace("--- Processing attachment '{$attachment->filename}'");
if ($maxbytes != USER_CAN_IGNORE_FILE_SIZE_LIMITS &&
($attachment->filesize + $usedspace) > $maxbytes) {
// The user quota will be exceeded if this file is included.
$skippedfiles[] = $attachment;
mtrace("---- Skipping attachment. User will be over quota.");
continue;
}
// Create a new record for this file.
$record = new \stdClass();
$record->filearea = $filearea;
$record->component = $component;
$record->filepath = '/';
$record->itemid = $itemid;
$record->license = $license;
$record->author = $author;
$record->contextid = $context->id;
$record->userid = $USER->id;
$record->filename = $fs->get_unused_filename($context->id, $record->component, $record->filearea,
$record->itemid, $record->filepath, $attachment->filename);
mtrace("--> Attaching {$record->filename} to " .
"/{$record->contextid}/{$record->component}/{$record->filearea}/" .
"{$record->itemid}{$record->filepath}{$record->filename}");
if ($fs->create_file_from_string($record, $attachment->content)) {
// File created successfully.
mtrace("---- File uploaded successfully as {$record->filename}.");
$uploadedfiles[] = $attachment;
$usedspace += $attachment->filesize;
} else {
mtrace("---- Skipping attachment. Unknown failure during creation.");
$failedfiles[] = $attachment;
}
}
}
// TODO send the user a confirmation e-mail.
// Note, some files may have failed because the user has been pushed over quota. This does not constitute a failure.
return true;
}
}
@@ -0,0 +1,46 @@
<?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/>.
/**
* Variable Envelope Return Path message processing failure exception.
*
* @package core_message
* @copyright 2014 Andrew Nicols <andrew@nicols.co.uk>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace core\message\inbound;
defined('MOODLE_INTERNAL') || die();
/**
* Variable Envelope Return Path message processing failure exception.
*
* @copyright 2014 Andrew Nicols <andrew@nicols.co.uk>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class processing_failed_exception extends \moodle_exception {
/**
* Constructor
*
* @param string $identifier The string identifier to use when displaying this exception.
* @param string $component The string component
* @param \stdClass $data The data to pass to get_string
*/
public function __construct($identifier, $component, \stdClass $data = null) {
return parent::__construct($identifier, $component, '', $data);
}
}
+513
View File
@@ -0,0 +1,513 @@
<?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/>.
/**
* New messaging manager class.
*
* @package core_message
* @since Moodle 2.8
* @copyright 2014 Totara Learning Solutions Ltd {@link http://www.totaralms.com/}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @author Petr Skoda <petr.skoda@totaralms.com>
*/
namespace core\message;
defined('MOODLE_INTERNAL') || die();
/**
* Class used for various messaging related stuff.
*
* Note: Do NOT use directly in your code, it is intended to be used from core code only.
*
* @access private
*
* @package core_message
* @since Moodle 2.8
* @copyright 2014 Totara Learning Solutions Ltd {@link http://www.totaralms.com/}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @author Petr Skoda <petr.skoda@totaralms.com>
*/
class manager {
/** @var array buffer of pending messages */
protected static $buffer = array();
/** @var array buffer of pending messages to conversations */
protected static $convmessagebuffer = array();
/**
* Used for calling processors, and generating event data when sending a message to a conversation.
*
* This is ONLY used for messages of type 'message' (notification=0), and is responsible for:
*
* 1. generation of per-user event data (to pass to processors)
* 2. generation of the processors for each recipient member of the conversation
* 3. calling said processors for each member, passing in the per-user (local) eventdata.
* 4. generation of an appropriate event for the message send, depending on the conversation type
* - messages to individual conversations generate a 'message_sent' event (as per legacy send_message())
* - messages to group conversations generate a 'group_message_sent' event.
*
* @param message $eventdata
* @param \stdClass $savemessage
* @return int
*/
public static function send_message_to_conversation(message $eventdata, \stdClass $savemessage): int {
global $DB, $CFG, $SITE;
if (empty($eventdata->convid)) {
throw new \moodle_exception("Message is not being sent to a conversation. Please check event data.");
}
// Fetch default (site) preferences.
$defaultpreferences = get_message_output_default_preferences();
$preferencebase = $eventdata->component.'_'.$eventdata->name;
// Because we're dealing with multiple recipients, we need to send a localised (per-user) version of the eventdata to each
// processor, because of things like the language-specific subject. We're going to modify this, for each recipient member.
// Any time we're modifying the event data here, we should be using the localised version.
// This localised version is based on the generic event data, but we should keep that object intact, so we clone it.
$localisedeventdata = clone $eventdata;
// Get user records for all members of the conversation.
// We must fetch distinct users, because it's possible for a user to message themselves via bulk user actions.
// In such cases, there will be 2 records referring to the same user.
$sql = "SELECT u.*, mca.id as ismuted
FROM {user} u
LEFT JOIN {message_conversation_actions} mca
ON mca.userid = u.id AND mca.conversationid = ? AND mca.action = ?
WHERE u.id IN (
SELECT mcm.userid FROM {message_conversation_members} mcm
WHERE mcm.conversationid = ?
)";
$members = $DB->get_records_sql($sql, [$eventdata->convid, \core_message\api::CONVERSATION_ACTION_MUTED,
$eventdata->convid]);
if (empty($members)) {
throw new \moodle_exception("Conversation has no members or does not exist.");
}
if (!is_object($localisedeventdata->userfrom)) {
$localisedeventdata->userfrom = $members[$localisedeventdata->userfrom];
}
// This should now hold only the other users (recipients).
unset($members[$localisedeventdata->userfrom->id]);
$otherusers = $members;
// Get conversation type and name. We'll use this to determine which message subject to generate, depending on type.
$conv = $DB->get_record('message_conversations', ['id' => $eventdata->convid], 'id, type, name');
// For now Self conversations are not processed because users are aware of the messages sent by themselves, so we
// can return early.
if ($conv->type == \core_message\api::MESSAGE_CONVERSATION_TYPE_SELF) {
return $savemessage->id;
}
$localisedeventdata->conversationtype = $conv->type;
// We treat individual conversations the same as any direct message with 'userfrom' and 'userto' specified.
// We know the other user, so set the 'userto' field so that the event code will get access to this field.
// If this was a legacy caller (eventdata->userto is set), then use that instead, as we want to use the fields specified
// in that object instead of using one fetched from the DB.
$legacymessage = false;
if ($conv->type == \core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL) {
if (isset($eventdata->userto)) {
$legacymessage = true;
} else {
$otheruser = reset($otherusers);
$eventdata->userto = $otheruser;
}
}
// Fetch enabled processors.
// If we are dealing with a message some processors may want to handle it regardless of user and site settings.
$processors = array_filter(get_message_processors(false), function($processor) {
if ($processor->object->force_process_messages()) {
return true;
}
return ($processor->enabled && $processor->configured);
});
// For each member of the conversation, other than the sender:
// 1. Set recipient specific event data (language specific, user prefs, etc)
// 2. Generate recipient specific processor list
// 3. Call send_message() to pass the message to processors and generate the relevant per-user events.
$eventprocmaps = []; // Init the event/processors buffer.
foreach ($otherusers as $recipient) {
// If this message was a legacy (1:1) message, then we use the userto.
if ($legacymessage) {
$ismuted = $recipient->ismuted;
$recipient = $eventdata->userto;
$recipient->ismuted = $ismuted;
}
$usertoisrealuser = (\core_user::is_real_user($recipient->id) != false);
// Using string manager directly so that strings in the message will be in the message recipients language rather than
// the sender's.
if ($conv->type == \core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL) {
$localisedeventdata->subject = get_string_manager()->get_string('unreadnewmessage', 'message',
fullname($localisedeventdata->userfrom), $recipient->lang);
} else if ($conv->type == \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP) {
$stringdata = (object) ['name' => fullname($localisedeventdata->userfrom), 'conversationname' => $conv->name];
$localisedeventdata->subject = get_string_manager()->get_string('unreadnewgroupconversationmessage', 'message',
$stringdata, $recipient->lang);
}
// Spoof the userto based on the current member id.
$localisedeventdata->userto = $recipient;
// Check if the notification is including images that will need a user token to be displayed outside Moodle.
if (!empty($localisedeventdata->customdata)) {
$customdata = json_decode($localisedeventdata->customdata);
if (is_object($customdata) && !empty($customdata->notificationiconurl)) {
$customdata->tokenpluginfile = get_user_key('core_files', $localisedeventdata->userto->id);
$localisedeventdata->customdata = $customdata; // Message class will JSON encode again.
}
}
$s = new \stdClass();
$s->sitename = format_string($SITE->shortname, true, array('context' => \context_course::instance(SITEID)));
$s->url = $CFG->wwwroot.'/message/index.php?id='.$eventdata->userfrom->id;
$emailtagline = get_string_manager()->get_string('emailtagline', 'message', $s, $recipient->lang);
$localisedeventdata->fullmessage = $eventdata->fullmessage;
$localisedeventdata->fullmessagehtml = $eventdata->fullmessagehtml;
if (!empty($localisedeventdata->fullmessage)) {
// Prevent unclosed HTML elements.
$localisedeventdata->fullmessage =
\core_message\helper::prevent_unclosed_html_tags($localisedeventdata->fullmessage, true);
$localisedeventdata->fullmessage .= "\n\n---------------------------------------------------------------------\n"
. $emailtagline;
}
if (!empty($localisedeventdata->fullmessagehtml)) {
// Prevent unclosed HTML elements.
$localisedeventdata->fullmessagehtml =
\core_message\helper::prevent_unclosed_html_tags($localisedeventdata->fullmessagehtml, true);
$localisedeventdata->fullmessagehtml .=
"<br><br>---------------------------------------------------------------------<br>" . $emailtagline;
}
// If recipient is internal user (noreply user), and emailstop is set then don't send any msg.
if (!$usertoisrealuser && !empty($recipient->emailstop)) {
debugging('Attempt to send msg to internal (noreply) user', DEBUG_NORMAL);
return false;
}
// Fill in the array of processors to be used based on default and user preferences.
// Do not process muted conversations.
$processorlist = [];
if (!$recipient->ismuted) {
foreach ($processors as $processor) {
// Skip adding processors for internal user, if processor doesn't support sending message to internal user.
if (!$usertoisrealuser && !$processor->object->can_send_to_any_users()) {
continue;
}
// First find out permissions.
$defaultlockedpreference = $processor->name . '_provider_' . $preferencebase . '_locked';
$locked = false;
if (isset($defaultpreferences->{$defaultlockedpreference})) {
$locked = $defaultpreferences->{$defaultlockedpreference};
} else {
// MDL-25114 They supplied an $eventdata->component $eventdata->name combination which doesn't
// exist in the message_provider table (thus there is no default settings for them).
$preferrormsg = "Could not load preference $defaultlockedpreference.
Make sure the component and name you supplied to message_send() are valid.";
throw new \coding_exception($preferrormsg);
}
$enabledpreference = 'message_provider_'.$preferencebase . '_enabled';
$forced = false;
if ($locked && isset($defaultpreferences->{$enabledpreference})) {
$forced = $defaultpreferences->{$enabledpreference};
}
// Find out if user has configured this output.
// Some processors cannot function without settings from the user.
$userisconfigured = $processor->object->is_user_configured($recipient);
// DEBUG: notify if we are forcing unconfigured output.
if ($forced && !$userisconfigured) {
debugging('Attempt to force message delivery to user who has "' . $processor->name .
'" output unconfigured', DEBUG_NORMAL);
}
// Populate the list of processors we will be using.
if (!$eventdata->notification && $processor->object->force_process_messages()) {
$processorlist[] = $processor->name;
} else if ($forced && $userisconfigured) {
// An admin is forcing users to use this message processor. Use this processor unconditionally.
$processorlist[] = $processor->name;
} else if (!$locked && $userisconfigured && !$recipient->emailstop) {
// User has not disabled notifications.
// See if user set any notification preferences, otherwise use site default ones.
$userpreferencename = 'message_provider_' . $preferencebase . '_enabled';
if ($userpreference = get_user_preferences($userpreferencename, null, $recipient)) {
if (in_array($processor->name, explode(',', $userpreference))) {
$processorlist[] = $processor->name;
}
} else if (isset($defaultpreferences->{$userpreferencename})) {
if (in_array($processor->name, explode(',', $defaultpreferences->{$userpreferencename}))) {
$processorlist[] = $processor->name;
}
}
}
}
}
// Batch up the localised event data and processor list for all users into a local buffer.
$eventprocmaps[] = [clone($localisedeventdata), $processorlist];
}
// Then pass it off as one item of work, to be processed by send_conversation_message_to_processors(), which will
// handle all transaction buffering logic.
self::send_conversation_message_to_processors($eventprocmaps, $eventdata, $savemessage);
return $savemessage->id;
}
/**
* Takes a list of localised event data, and tries to send them to their respective member's message processors.
*
* Input format:
* [CONVID => [$localisedeventdata, $savemessage, $processorlist], ].
*
* @param array $eventprocmaps the array of localised event data and processors for each member of the conversation.
* @param message $eventdata the original conversation message eventdata
* @param \stdClass $savemessage the saved message record.
* @throws \coding_exception
*/
protected static function send_conversation_message_to_processors(array $eventprocmaps, message $eventdata,
\stdClass $savemessage) {
global $DB;
// We cannot communicate with external systems in DB transactions,
// buffer the messages if necessary.
if ($DB->is_transaction_started()) {
// Buffer this group conversation message and it's record.
self::$convmessagebuffer[] = [$eventprocmaps, $eventdata, $savemessage];
return;
}
// Send each localised version of the event data to each member's respective processors.
foreach ($eventprocmaps as $eventprocmap) {
$eventdata = $eventprocmap[0];
$processorlist = $eventprocmap[1];
self::call_processors($eventdata, $processorlist);
}
// Trigger event for sending a message or notification - we need to do this before marking as read!
self::trigger_message_events($eventdata, $savemessage);
}
/**
* Do the message sending.
*
* NOTE: to be used from message_send() only.
*
* @param \core\message\message $eventdata fully prepared event data for processors
* @param \stdClass $savemessage the message saved in 'message' table
* @param array $processorlist list of processors for target user
* @return int $messageid the id from 'messages' (false is not returned)
*/
public static function send_message(message $eventdata, \stdClass $savemessage, array $processorlist) {
global $CFG;
require_once($CFG->dirroot.'/message/lib.php'); // This is most probably already included from messagelib.php file.
if (empty($processorlist)) {
// Trigger event for sending a message or notification - we need to do this before marking as read!
self::trigger_message_events($eventdata, $savemessage);
if ($eventdata->notification) {
// If they have deselected all processors and it's a notification mark it read. The user doesn't want to be
// bothered.
$savemessage->timeread = null;
\core_message\api::mark_notification_as_read($savemessage);
} else if (empty($CFG->messaging)) {
// If it's a message and messaging is disabled mark it read.
\core_message\api::mark_message_as_read($eventdata->userto->id, $savemessage);
}
return $savemessage->id;
}
// Let the manager do the sending or buffering when db transaction in progress.
return self::send_message_to_processors($eventdata, $savemessage, $processorlist);
}
/**
* Send message to message processors.
*
* @param \stdClass|\core\message\message $eventdata
* @param \stdClass $savemessage
* @param array $processorlist
* @throws \moodle_exception
* @return int $messageid
*/
protected static function send_message_to_processors($eventdata, \stdClass $savemessage, array
$processorlist) {
global $CFG, $DB;
// We cannot communicate with external systems in DB transactions,
// buffer the messages if necessary.
if ($DB->is_transaction_started()) {
// We need to clone all objects so that devs may not modify it from outside later.
$eventdata = clone($eventdata);
$eventdata->userto = clone($eventdata->userto);
$eventdata->userfrom = clone($eventdata->userfrom);
// Conserve some memory the same was as $USER setup does.
unset($eventdata->userto->description);
unset($eventdata->userfrom->description);
self::$buffer[] = array($eventdata, $savemessage, $processorlist);
return $savemessage->id;
}
// Send the message to processors.
if (!self::call_processors($eventdata, $processorlist)) {
throw new \moodle_exception("Message was not sent.");
}
// Trigger event for sending a message or notification - we need to do this before marking as read!
self::trigger_message_events($eventdata, $savemessage);
if (!$eventdata->notification && empty($CFG->messaging)) {
// If it's a message and messaging is disabled mark it read.
\core_message\api::mark_message_as_read($eventdata->userto->id, $savemessage);
}
return $savemessage->id;
}
/**
* Notification from DML layer.
*
* Note: to be used from DML layer only.
*/
public static function database_transaction_commited() {
if (!self::$buffer && !self::$convmessagebuffer) {
return;
}
self::process_buffer();
}
/**
* Notification from DML layer.
*
* Note: to be used from DML layer only.
*/
public static function database_transaction_rolledback() {
self::$buffer = array();
self::$convmessagebuffer = array();
}
/**
* Sent out any buffered messages if necessary.
*/
protected static function process_buffer() {
// Reset the buffers first in case we get exception from processor.
$messages = self::$buffer;
self::$buffer = array();
$convmessages = self::$convmessagebuffer;
self::$convmessagebuffer = array();
foreach ($messages as $message) {
list($eventdata, $savemessage, $processorlist) = $message;
self::send_message_to_processors($eventdata, $savemessage, $processorlist);
}
foreach ($convmessages as $convmessage) {
list($eventprocmap, $eventdata, $savemessage) = $convmessage;
self::send_conversation_message_to_processors($eventprocmap, $eventdata, $savemessage);
}
}
/**
* Trigger an appropriate message creation event, based on the supplied $eventdata and $savemessage.
*
* @param message $eventdata the eventdata for the message.
* @param \stdClass $savemessage the message record.
* @throws \coding_exception
*/
protected static function trigger_message_events(message $eventdata, \stdClass $savemessage) {
global $DB;
if ($eventdata->notification) {
\core\event\notification_sent::create_from_ids(
$eventdata->userfrom->id,
$eventdata->userto->id,
$savemessage->id,
$eventdata->courseid
)->trigger();
} else { // Must be a message.
// If the message is a group conversation, then trigger the 'group_message_sent' event.
if ($eventdata->convid) {
$conv = $DB->get_record('message_conversations', ['id' => $eventdata->convid], 'id, type');
if ($conv->type == \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP) {
\core\event\group_message_sent::create_from_ids(
$eventdata->userfrom->id,
$eventdata->convid,
$savemessage->id,
$eventdata->courseid
)->trigger();
return;
}
// Individual type conversations fall through to the default 'message_sent' event.
}
\core\event\message_sent::create_from_ids(
$eventdata->userfrom->id,
$eventdata->userto->id,
$savemessage->id,
$eventdata->courseid
)->trigger();
}
}
/**
* For each processor, call it's send_message() method.
*
* @param message $eventdata the message object.
* @param array $processorlist the list of processors for a single user.
* @return bool false if error calling message processor
*/
protected static function call_processors(message $eventdata, array $processorlist) {
// Allow plugins to change the message/notification data before sending it.
$pluginsfunction = get_plugins_with_function('pre_processor_message_send');
$sendmsgsuccessful = true;
foreach ($processorlist as $procname) {
// Let new messaging class add custom content based on the processor.
$proceventdata = ($eventdata instanceof message) ? $eventdata->get_eventobject_for_processor($procname) : $eventdata;
if ($pluginsfunction) {
foreach ($pluginsfunction as $plugintype => $plugins) {
foreach ($plugins as $pluginfunction) {
$pluginfunction($procname, $proceventdata);
}
}
}
$stdproc = new \stdClass();
$stdproc->name = $procname;
$processor = \core_message\api::get_processed_processor_object($stdproc);
if (!$processor->object->send_message($proceventdata)) {
debugging('Error calling message processor ' . $procname);
$sendmsgsuccessful = false;
}
}
return $sendmsgsuccessful;
}
}
+341
View File
@@ -0,0 +1,341 @@
<?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/>.
/**
* New messaging class.
*
* @package core_message
* @since Moodle 2.9
* @copyright 2015 onwards Ankit Agarwal
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace core\message;
defined('MOODLE_INTERNAL') || die();
/**
* New messaging class.
*
* Required parameters of the $eventdata object:
* component string Component name. must exist in message_providers
* name string Message type name. must exist in message_providers
* userfrom object|int The user sending the message
* userto object|int The message recipient. This is mandatory for NOTIFICACIONS and 1:1 personal messages.
* subject string The message subject
* fullmessage string The full message in a given format
* fullmessageformat int The format if the full message (FORMAT_MOODLE, FORMAT_HTML, ..)
* fullmessagehtml string The full version (the message processor will choose with one to use)
* smallmessage string The small version of the message
*
* Required parameters of the $eventdata object for PERSONAL MESSAGES:
* convid int The conversation identifier where this message will be sent
*
* Optional parameters of the $eventdata object:
* notification bool Should the message be considered as a notification rather than a personal message
* contexturl string If this is a notification then you can specify a url to view the event.
* For example the forum post the user is being notified of.
* contexturlname string The display text for contexturl.
* replyto string An email address which can be used to send an reply.
* attachment stored_file File instance that needs to be sent as attachment.
* attachname string Name of the attachment.
* customdata mixed Custom data to be passed to the message processor. Must be serialisable using json_encode().
*
* @package core_message
* @since Moodle 2.9
* @copyright 2015 onwards Ankit Agarwal
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class message {
/** @var int Course id. */
private $courseid;
/** @var string Module name. */
private $modulename;
/** @var string Component name. */
private $component;
/** @var string Name. */
private $name;
/** @var object|int The user who is sending this message. */
private $userfrom;
/** @var int The conversation id where userfrom is sending this message. */
private $convid;
/** @var int The conversation type, eg. \core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL */
private $conversationtype;
/** @var object|int The user who is receiving from which is sending this message. */
private $userto;
/** @var string Subject of the message. */
private $subject;
/** @var string Complete message. */
private $fullmessage;
/** @var int Message format. */
private $fullmessageformat;
/** @var string Complete message in html format. */
private $fullmessagehtml;
/** @var string Smaller version of the message. */
private $smallmessage;
/** @var int Is it a notification? */
private $notification;
/** @var string context url. */
private $contexturl;
/** @var string context name. */
private $contexturlname;
/** @var string An email address which can be used to send an reply. */
private $replyto;
/** @var string A name which can be used with replyto. */
private $replytoname;
/** @var int Used internally to store the id of the row representing this message in DB. */
private $savedmessageid;
/** @var \stored_file File to be attached to the message. Note:- not all processors support this.*/
private $attachment;
/** @var string Name of the attachment. Note:- not all processors support this.*/
private $attachname;
/** @var int The time the message was created.*/
private $timecreated;
/** @var boolean Mark trust content. */
private $fullmessagetrust;
/** @var mixed Custom data to be passed to the message processor. Must be serialisable using json_encode(). */
private $customdata;
/** @var boolean If message is anonymous. */
private $anonymous;
/** @var array a list of properties that is allowed for each message. */
private $properties = array(
'courseid',
'modulename',
'component',
'name',
'userfrom',
'convid',
'conversationtype',
'userto',
'subject',
'fullmessage',
'fullmessageformat',
'fullmessagehtml',
'smallmessage',
'notification',
'contexturl',
'contexturlname',
'replyto',
'replytoname',
'savedmessageid',
'attachment',
'attachname',
'timecreated',
'fullmessagetrust',
'customdata',
'anonymous',
);
/** @var array property to store any additional message processor specific content */
private $additionalcontent = array();
/**
* Fullmessagehtml content including any processor specific content.
*
* @param string $processorname Name of the processor.
*
* @return mixed|string
*/
protected function get_fullmessagehtml($processorname = '') {
if (!empty($processorname) && isset($this->additionalcontent[$processorname])) {
return $this->get_message_with_additional_content($processorname, 'fullmessagehtml');
} else {
return $this->fullmessagehtml;
}
}
/**
* Fullmessage content including any processor specific content.
*
* @param string $processorname Name of the processor.
*
* @return mixed|string
*/
protected function get_fullmessage($processorname = '') {
if (!empty($processorname) && isset($this->additionalcontent[$processorname])) {
return $this->get_message_with_additional_content($processorname, 'fullmessage');
} else {
return $this->fullmessage;
}
}
/**
* Smallmessage content including any processor specific content.
*
* @param string $processorname Name of the processor.
*
* @return mixed|string
*/
protected function get_smallmessage($processorname = '') {
if (!empty($processorname) && isset($this->additionalcontent[$processorname])) {
return $this->get_message_with_additional_content($processorname, 'smallmessage');
} else {
return $this->smallmessage;
}
}
/**
* Always JSON encode customdata.
*
* @param mixed $customdata a data structure that must be serialisable using json_encode().
*/
protected function set_customdata($customdata) {
// Always include the courseid (because is not stored in the notifications or messages table).
if (!empty($this->courseid) && (is_object($customdata) || is_array($customdata))) {
$customdata = (array) $customdata;
$customdata['courseid'] = $this->courseid;
}
$this->customdata = json_encode($customdata);
}
/**
* Helper method used to get message content added with processor specific content.
*
* @param string $processorname Name of the processor.
* @param string $messagetype one of 'fullmessagehtml', 'fullmessage', 'smallmessage'.
*
* @return mixed|string
*/
protected function get_message_with_additional_content($processorname, $messagetype) {
$message = $this->$messagetype;
if (isset($this->additionalcontent[$processorname]['*'])) {
// Content that needs to be added to all format.
$pattern = $this->additionalcontent[$processorname]['*'];
$message = empty($pattern['header']) ? $message : $pattern['header'] . $message;
$message = empty($pattern['footer']) ? $message : $message . $pattern['footer'];
}
if (isset($this->additionalcontent[$processorname][$messagetype])) {
// Content that needs to be added to the specific given format.
$pattern = $this->additionalcontent[$processorname][$messagetype];
$message = empty($pattern['header']) ? $message : $pattern['header'] . $message;
$message = empty($pattern['footer']) ? $message : $message . $pattern['footer'];
}
return $message;
}
/**
* Magic getter method.
*
* @param string $prop name of property to get.
*
* @return mixed
* @throws \coding_exception
*/
public function __get($prop) {
if (in_array($prop, $this->properties)) {
return $this->$prop;
}
throw new \coding_exception("Invalid property $prop specified");
}
/**
* Magic setter method.
*
* @param string $prop name of property to set.
* @param mixed $value value to assign to the property.
*
* @return mixed
* @throws \coding_exception
*/
public function __set($prop, $value) {
// Custom data must be JSON encoded always.
if ($prop == 'customdata') {
return $this->set_customdata($value);
}
if (in_array($prop, $this->properties)) {
return $this->$prop = $value;
}
throw new \coding_exception("Invalid property $prop specified");
}
/**
* Magic method to check if property is set.
*
* @param string $prop name of property to check.
* @return bool
* @throws \coding_exception
*/
public function __isset($prop) {
if (in_array($prop, $this->properties)) {
return isset($this->$prop);
}
throw new \coding_exception("Invalid property $prop specified");
}
/**
* This method lets you define content that would be added to the message only for specific message processors.
*
* Example of $content:-
* array('fullmessagehtml' => array('header' => 'header content', 'footer' => 'footer content'),
* 'smallmessage' => array('header' => 'header content for small message', 'footer' => 'footer content'),
* '*' => array('header' => 'header content for all types', 'footer' => 'footer content')
* )
*
* @param string $processorname name of the processor.
* @param array $content content to add in the above defined format.
*/
public function set_additional_content($processorname, $content) {
$this->additionalcontent[$processorname] = $content;
}
/**
* Get a event object for a specific processor in stdClass format.
*
* @param string $processorname Name of the processor.
*
* @return \stdClass event object in stdClass format.
*/
public function get_eventobject_for_processor($processorname) {
// This is done for Backwards compatibility. We should consider throwing notices here in future versions and requesting
// them to use proper api.
$eventdata = new \stdClass();
foreach ($this->properties as $prop) {
$func = "get_$prop";
$eventdata->$prop = method_exists($this, $func) ? $this->$func($processorname) : $this->$prop;
}
return $eventdata;
}
}