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);
}
}