🎉 initial commit
This commit is contained in:
commit
c93a06972b
27 changed files with 4189 additions and 0 deletions
237
Civi/Mailinglistsync/ADGroupMailingList.php
Normal file
237
Civi/Mailinglistsync/ADGroupMailingList.php
Normal file
|
@ -0,0 +1,237 @@
|
|||
<?php /** @noinspection SpellCheckingInspection */
|
||||
|
||||
namespace Civi\Mailinglistsync;
|
||||
|
||||
use CRM_Mailinglistsync_ExtensionUtil as E;
|
||||
use Civi\Mailinglistsync\Exceptions\MailinglistException;
|
||||
|
||||
class ADGroupMailingList extends GroupMailingList {
|
||||
|
||||
public const LOCATION_TYPE = 'AD_Mailing_List_Address';
|
||||
|
||||
protected string $sid;
|
||||
|
||||
/**
|
||||
* Get an AD mailing list by its SID.
|
||||
*
|
||||
* @params string $sid
|
||||
* @param string $sid
|
||||
*
|
||||
* @return \Civi\Mailinglistsync\ADGroupMailingList|null
|
||||
*
|
||||
* @throws \CRM_Core_Exception
|
||||
* @throws \Civi\API\Exception\UnauthorizedException
|
||||
* @throws \Civi\Mailinglistsync\Exceptions\MailinglistException
|
||||
*/
|
||||
public static function getBySID(string $sid): ?self {
|
||||
$id = static::RELATED_CLASS::get()
|
||||
->addSelect('id')
|
||||
->addWhere(static::CUSTOM_GROUP_NAME . '.Active_Directory_SID', '=', $sid)
|
||||
->execute()
|
||||
->first()['id'];
|
||||
|
||||
$groups = \CRM_Contact_BAO_Group::getGroups(['id' => $id]);
|
||||
$groupId = array_pop($groups);
|
||||
return $groupId ? new self($groupId) : NULL;
|
||||
}
|
||||
|
||||
/**
|
||||
* Synchronize recipients with a list of SIDs and e-mail addresses.
|
||||
*
|
||||
* @param array $recipients
|
||||
*
|
||||
* @return array A description of the changes made
|
||||
*
|
||||
* @throws \Civi\Mailinglistsync\Exceptions\MailinglistException
|
||||
*/
|
||||
public function syncRecipients(array $recipients): array {
|
||||
|
||||
$adGroupMembers = $this->getRecipients();
|
||||
|
||||
// Add new recipients
|
||||
$recipientsAdded = [];
|
||||
foreach ($recipients as $recipient) {
|
||||
if (empty($adGroupMembers[$recipient['sid']] ?? NULL)) {
|
||||
$recipientsAdded[$recipient['sid']] = $this->addRecipient($recipient);
|
||||
}
|
||||
}
|
||||
|
||||
// Remove recipients that are no longer in the list
|
||||
$recipientsRemoved = [];
|
||||
foreach ($adGroupMembers as $adGroupMember) {
|
||||
/* @var \Civi\Mailinglistsync\MailingListRecipient $adGroupMember */
|
||||
if (!in_array($adGroupMember->getSid(), array_column($recipients, 'sid'))) {
|
||||
$recipientsRemoved[$adGroupMember->getSid()] = $this->removeRecipient($adGroupMember);
|
||||
}
|
||||
}
|
||||
|
||||
// Update recipients
|
||||
$recipientsUpdated = [];
|
||||
|
||||
$recipientAttributesMap = [
|
||||
// Map recipient attribute names to method names (get/set)
|
||||
'first_name' => 'FirstName',
|
||||
'last_name' => 'LastName',
|
||||
'email' => 'Email',
|
||||
];
|
||||
|
||||
foreach ($recipients as $recipient) {
|
||||
$changed = FALSE;
|
||||
|
||||
// Find the group member by SID
|
||||
$adGroupMemberArray = array_filter(
|
||||
$adGroupMembers,
|
||||
fn($adGroupMember) => $adGroupMember->getSid() === $recipient['sid']
|
||||
);
|
||||
$count = count($adGroupMemberArray);
|
||||
if ($count === 0) {
|
||||
continue;
|
||||
}
|
||||
elseif ($count > 1) {
|
||||
throw new MailinglistException(
|
||||
"Multiple recipients with the same SID",
|
||||
MailinglistException::ERROR_CODE_MULTIPLE_RECIPIENTS
|
||||
);
|
||||
}
|
||||
/* @var \Civi\Mailinglistsync\MailingListRecipient $adGroupMember */
|
||||
$adGroupMember = array_pop($adGroupMemberArray);
|
||||
|
||||
// Update attributes if they have changed
|
||||
foreach ($recipientAttributesMap as $attrName => $methodName) {
|
||||
$changed = self::updateRecipient(
|
||||
$adGroupMember,
|
||||
$recipient,
|
||||
$attrName,
|
||||
fn() => $adGroupMember->{"get$methodName"}(),
|
||||
fn($value) => $adGroupMember->{"set$methodName"}($value),
|
||||
$recipientsUpdated,
|
||||
) || $changed;
|
||||
}
|
||||
|
||||
// Apply changes
|
||||
if ($changed) {
|
||||
$adGroupMember->save();
|
||||
}
|
||||
}
|
||||
|
||||
// Count errors
|
||||
$errorCount = count(array_filter(
|
||||
$recipientsAdded,
|
||||
fn($recipient) => $recipient['is_error']
|
||||
));
|
||||
$errorCount += count(array_filter(
|
||||
$recipientsRemoved,
|
||||
fn($recipient) => $recipient['is_error']
|
||||
));
|
||||
$errorCount += count(array_filter(
|
||||
$recipientsUpdated,
|
||||
fn($recipient) => array_filter($recipient, fn($attr) => $attr['is_error'])
|
||||
));
|
||||
|
||||
return [
|
||||
'error_count' => $errorCount,
|
||||
'recipients_added' => $recipientsAdded,
|
||||
'recipients_removed' => $recipientsRemoved,
|
||||
'recipients_updated' => $recipientsUpdated,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a list of recipients indexed by SID.
|
||||
*
|
||||
* @override GroupMailingList::getRecipients()
|
||||
* @return array
|
||||
* @throws \Civi\Mailinglistsync\Exceptions\MailinglistException
|
||||
*/
|
||||
public function getRecipients(): array {
|
||||
$recipients = parent::getRecipients();
|
||||
return array_column($recipients, null, fn($recipient) => $recipient->getSid());
|
||||
}
|
||||
|
||||
private function addRecipient(array $recipient): array {
|
||||
$result = ['recipient' => $recipient];
|
||||
|
||||
try {
|
||||
// Try to find an existing contact
|
||||
$contactSearch = $this->findExistingContact(
|
||||
firstName: $recipient['first_name'],
|
||||
lastName: $recipient['last_name'],
|
||||
email: $recipient['email'],
|
||||
);
|
||||
if ($contactSearch !== NULL) {
|
||||
$result['is_error'] = FALSE;
|
||||
$result['recipient']['contact_id'] = $contactSearch['contact']['id'];
|
||||
$result['recipient']['found_by'] = $contactSearch['found_by'];
|
||||
$result['recipient']['contact_created'] = FALSE;
|
||||
return $result;
|
||||
}
|
||||
|
||||
// Create a new contact if none was found
|
||||
$newRecipient = MailingListRecipient::createContact(
|
||||
firstName: $recipient['first_name'],
|
||||
lastName: $recipient['last_name'],
|
||||
email: $recipient['email'],
|
||||
sid: $recipient['sid'],
|
||||
);
|
||||
$result['is_error'] = FALSE;
|
||||
$result['recipient']['contact_id'] = $newRecipient->getContactId();
|
||||
$result['recipient']['contact_created'] = TRUE;
|
||||
return $result;
|
||||
}
|
||||
catch (MailinglistException $e) {
|
||||
$error = $e->getLogMessage();
|
||||
\Civi::log(E::LONG_NAME)->error($error);
|
||||
$result['is_error'] = TRUE;
|
||||
$result['error_message'] = $error;
|
||||
$result['recipient']['contact_created'] = FALSE;
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper function to update recipient data dynamically.
|
||||
* OMG, is this DRY!
|
||||
*
|
||||
* @param \Civi\Mailinglistsync\MailingListRecipient $old
|
||||
* @param array $new
|
||||
* @param string $attributeName
|
||||
* @param callable $getter
|
||||
* @param callable $setter
|
||||
* @param array $changes
|
||||
*
|
||||
* @return bool TRUE if the recipient was updated, FALSE otherwise
|
||||
*/
|
||||
private static function updateRecipient(
|
||||
MailingListRecipient $old,
|
||||
array $new,
|
||||
string $attributeName,
|
||||
callable $getter,
|
||||
callable $setter,
|
||||
array &$changes,
|
||||
): bool {
|
||||
$updated = FALSE;
|
||||
if ($new[$attributeName] !== $getter()) {
|
||||
$error = NULL;
|
||||
$oldValue = $getter();
|
||||
try {
|
||||
$setter($new[$attributeName]);
|
||||
$updated = TRUE;
|
||||
}
|
||||
catch (MailinglistException $e) {
|
||||
\Civi::log(E::LONG_NAME)->error($e->getLogMessage());
|
||||
$error = $e->getLogMessage();
|
||||
}
|
||||
finally {
|
||||
$changes[$old['sid']][$attributeName] = [
|
||||
'is_error' => $error !== NULL,
|
||||
'old' => $oldValue,
|
||||
'new' => $new[$attributeName],
|
||||
];
|
||||
if ($error !== NULL) {
|
||||
$changes[$old['sid']][$attributeName]['error'] = $error;
|
||||
}
|
||||
}
|
||||
}
|
||||
return $updated;
|
||||
}
|
||||
}
|
486
Civi/Mailinglistsync/BaseMailingList.php
Normal file
486
Civi/Mailinglistsync/BaseMailingList.php
Normal file
|
@ -0,0 +1,486 @@
|
|||
<?php
|
||||
|
||||
namespace Civi\Mailinglistsync;
|
||||
|
||||
use Civi\API\Exception\UnauthorizedException;
|
||||
use Civi\Api4\CustomField;
|
||||
use Civi\Core\Lock\NullLock;
|
||||
use Civi\Mailinglistsync\Exceptions\MailinglistException;
|
||||
use CRM_Mailinglistsync_ExtensionUtil as E;
|
||||
use Civi\Api4\MockBasicEntity;
|
||||
use Civi\Api4\LocationType;
|
||||
use Dompdf\Exception;
|
||||
|
||||
abstract class BaseMailingList {
|
||||
|
||||
public const GROUP_MAILING_LIST = 'group';
|
||||
|
||||
public const EVENT_MAILING_LIST = 'event';
|
||||
|
||||
public const CUSTOM_GROUP_NAME = 'BASE_Mailing_List';
|
||||
|
||||
protected const RELATED_CLASS = MockBasicEntity::class;
|
||||
protected const RELATED_TYPE = 'base';
|
||||
|
||||
protected MailingListManager $mailingListManager;
|
||||
|
||||
/**
|
||||
* Data to be updated. Use the `save()` method to apply the update.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
private array $updateData;
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @param int|array|null $entity The entity ID or an array of entity data.
|
||||
*
|
||||
* @throws \Civi\Mailinglistsync\Exceptions\MailinglistException
|
||||
*/
|
||||
function __construct(int|array $entity = NULL) {
|
||||
$this->updateData = [];
|
||||
if ($entity) {
|
||||
$this->load($entity);
|
||||
}
|
||||
$this->mailingListManager = new MailingListManager();
|
||||
}
|
||||
|
||||
/**
|
||||
* Set related entity directly or load it from the database by passing an ID.
|
||||
*
|
||||
* @param array|int $entity
|
||||
*
|
||||
* @return void
|
||||
* @throws \Civi\Mailinglistsync\Exceptions\MailinglistException
|
||||
*/
|
||||
protected function load(array|int $entity): void {
|
||||
if (is_int($entity)) {
|
||||
$id = $entity;
|
||||
try {
|
||||
$entity = static::RELATED_CLASS::get()
|
||||
->addSelect('*')
|
||||
->addSelect('custom.*')
|
||||
->addWhere('id', '=', $id)
|
||||
->execute()
|
||||
->first();
|
||||
$this->setEntity($entity);
|
||||
}
|
||||
catch (UnauthorizedException) {
|
||||
$type = static::RELATED_TYPE;
|
||||
throw new MailinglistException(
|
||||
"Could not get $type with id '$id' via API4 due to insufficient permissions",
|
||||
MailinglistException::ERROR_CODE_PERMISSION_DENIED
|
||||
);
|
||||
}
|
||||
catch (\Exception) {
|
||||
$type = static::RELATED_TYPE;
|
||||
throw new MailinglistException(
|
||||
"Could not get $type with id '$id' via API4",
|
||||
$type === self::GROUP_MAILING_LIST ? MailinglistException::ERROR_CODE_GET_GROUP_MAILING_LISTS_FAILED : MailinglistException::ERROR_CODE_GET_EVENT_MAILING_LISTS_FAILED
|
||||
);
|
||||
}
|
||||
}
|
||||
$this->setEntity($entity);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get related custom fields.
|
||||
*
|
||||
* @throws UnauthorizedException
|
||||
* @throws \CRM_Core_Exception
|
||||
*/
|
||||
static protected function getCustomFields(): array {
|
||||
return CustomField::get()
|
||||
->addSelect('*')
|
||||
->addWhere('custom_group_id:name', '=', static::CUSTOM_GROUP_NAME)
|
||||
->execute()
|
||||
->getArrayCopy();
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate e-mail address.
|
||||
*
|
||||
* @param string $emailAddress
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
static public function validateEmailAddress(string $emailAddress): bool {
|
||||
return (bool) filter_var($emailAddress, FILTER_VALIDATE_EMAIL);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate custom fields.
|
||||
*
|
||||
* @param array $fields
|
||||
* @param \CRM_Core_Form $form
|
||||
* @param array $errors
|
||||
*
|
||||
* @return bool
|
||||
* @throws \CRM_Core_Exception
|
||||
* @throws \Civi\API\Exception\UnauthorizedException
|
||||
* @throws \Exception
|
||||
*/
|
||||
static public function validateCustomFields(array $fields, \CRM_Core_Form $form, array &$errors): bool {
|
||||
$result = TRUE;
|
||||
$customFields = self::getCustomFields();
|
||||
$customValues = [];
|
||||
|
||||
// Determine the entity type
|
||||
if ($form instanceof \CRM_Group_Form_Edit) {
|
||||
$entityId = $form->getEntityId();
|
||||
$type = self::GROUP_MAILING_LIST;
|
||||
}
|
||||
elseif ($form instanceof \CRM_Event_Form_ManageEvent_EventInfo) {
|
||||
$entityId = $form->getEventID(); // It's things like this...
|
||||
$type = self::EVENT_MAILING_LIST;
|
||||
}
|
||||
else {
|
||||
throw new \Exception('Unknown form type');
|
||||
}
|
||||
|
||||
// Translate custom field names
|
||||
foreach ($customFields as $customField) {
|
||||
$fieldId = $customField['id'];
|
||||
$fieldName = "custom_$fieldId";
|
||||
$getCustomField = function() use ($fields, $fieldName) {
|
||||
foreach ($fields as $key => $value) {
|
||||
if (preg_match("/^$fieldName" . "_.*/", $key)) {
|
||||
return ['field_name' => $key, 'value' => $value];
|
||||
}
|
||||
}
|
||||
return NULL;
|
||||
};
|
||||
$customValues[$customField['name']] = $getCustomField();
|
||||
}
|
||||
|
||||
// Validate e-mail address
|
||||
if (!empty($customValues['E_mail_address'])) {
|
||||
if (!self::validateEmailAddress($customValues['E_mail_address']['value'])) {
|
||||
$errors[$customValues['E_mail_address']['field_name']] = E::ts('Invalid e-mail address');
|
||||
$result = FALSE;
|
||||
}
|
||||
}
|
||||
|
||||
// E-mail address must be unique for groups and events
|
||||
if (!empty($customValues['E_mail_address']['value'])) {
|
||||
$emailAddress = $customValues['E_mail_address']['value'];
|
||||
$groupId = self::GROUP_MAILING_LIST === $type ? $entityId : NULL;
|
||||
$eventId = self::EVENT_MAILING_LIST === $type ? $entityId : NULL;
|
||||
|
||||
// Check if the e-mail address is already in use for a group
|
||||
$existingGroup = GroupMailingList::getByEmailAddress($emailAddress, $groupId);
|
||||
if ($existingGroup) {
|
||||
$errors[$customValues['E_mail_address']['field_name']] =
|
||||
E::ts("E-mail address '%1' already in use for group '%2'",
|
||||
[
|
||||
1 => $customValues['E_mail_address']['value'],
|
||||
2 => $existingGroup->getTitle(),
|
||||
]);
|
||||
$result = FALSE;
|
||||
}
|
||||
|
||||
// Check if the e-mail address is already in use for an event
|
||||
$existingEvent = EventMailingList::getByEmailAddress($emailAddress, $eventId);
|
||||
if ($existingEvent) {
|
||||
$errors[$customValues['E_mail_address']['field_name']] =
|
||||
E::ts("E-mail address '%1' already in use for event '%2'",
|
||||
[
|
||||
1 => $customValues['E_mail_address']['value'],
|
||||
2 => $existingEvent->getTitle(),
|
||||
]);
|
||||
$result = FALSE;
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get mailing lists by its e-mail address.
|
||||
*
|
||||
* @param string $emailAddress
|
||||
* @param int|null $excludeId ID to exclude from the search
|
||||
*
|
||||
* @return ?self
|
||||
* @throws \CRM_Core_Exception
|
||||
* @throws \Civi\API\Exception\UnauthorizedException
|
||||
*/
|
||||
static public function getByEmailAddress(string $emailAddress, int $excludeId = NULL): ?self {
|
||||
$result = static::RELATED_CLASS::get()
|
||||
->addSelect('*')
|
||||
->addSelect('custom.*')
|
||||
->addWhere(static::CUSTOM_GROUP_NAME . '.E_mail_address', '=', $emailAddress);
|
||||
// If $excludeId is set, exclude it from the search
|
||||
if ($excludeId) {
|
||||
$result->addWhere('id', '!=', $excludeId);
|
||||
}
|
||||
$mailingListData = $result->execute()->first();
|
||||
return !empty($mailingListData) ? new static($mailingListData) : NULL;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the related entity.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
protected abstract function getEntity(): array;
|
||||
|
||||
/**
|
||||
* Set the related entity.
|
||||
*
|
||||
* @param array $value
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected abstract function setEntity(array $value): void;
|
||||
|
||||
/**
|
||||
* Check if the group is a mailing list.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function isMailingList(): bool {
|
||||
return (bool) $this->getEntity()[static::CUSTOM_GROUP_NAME . '.Enable_mailing_list'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the group is an AD mailing list.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function isADGroup(): bool {
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Mark changes to be saved via the `save()` method.
|
||||
*
|
||||
* @param array $values
|
||||
*/
|
||||
protected function update(array $values): void {
|
||||
$this->updateData += $values;
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves the changes marked using the `update()` method.
|
||||
*
|
||||
* @return void
|
||||
* @throws \Civi\Mailinglistsync\Exceptions\MailinglistException
|
||||
*/
|
||||
public function save(): void {
|
||||
if (empty($this->updateData)) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
static::RELATED_CLASS::update()
|
||||
->setValues($this->updateData)
|
||||
->addWhere('id', '=', $this->getEntity()['id'])
|
||||
->execute();
|
||||
}
|
||||
catch (\Exception $e) {
|
||||
$type = static::RELATED_TYPE;
|
||||
throw new MailinglistException(
|
||||
"Could not update $type with id '{$this->getEntity()['id']}'\n$e",
|
||||
MailinglistException::ERROR_CODE_UPDATE_ENTITY_FAILED
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the e-mail address of the mailing list.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getEmailAddress(): string {
|
||||
return $this->getEntity()[static::CUSTOM_GROUP_NAME . '.E_mail_address'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the title of the mailing list.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getTitle(): string {
|
||||
return $this->getEntity()['title'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the e-mail address of the mailing list.
|
||||
*
|
||||
* @param string $emailAddress
|
||||
*
|
||||
* @return void
|
||||
* @throws \Civi\Mailinglistsync\Exceptions\MailinglistException
|
||||
*/
|
||||
public function updateEmailAddress(string $emailAddress): void {
|
||||
// Validate email address
|
||||
if (ADGroupMailingList::validateEmailAddress($emailAddress)) {
|
||||
throw new MailinglistException(
|
||||
E::ts("Invalid e-mail address '%1'", [1 => $emailAddress]),
|
||||
MailinglistException::ERROR_CODE_INVALID_EMAIL_ADDRESS
|
||||
);
|
||||
}
|
||||
try {
|
||||
static::update([
|
||||
static::CUSTOM_GROUP_NAME . '.E_mail_address' => $emailAddress,
|
||||
]);
|
||||
}
|
||||
catch (MailinglistException) {
|
||||
$type = static::RELATED_TYPE;
|
||||
throw new MailinglistException(
|
||||
"Could not update e-mail address for $type with id '{$this->getEntity()['id']}'",
|
||||
MailinglistException::ERROR_CODE_UPDATE_EMAIL_ADDRESS_FAILED
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the location type name for the mailing list.
|
||||
*
|
||||
* Note: Use the getLocationTypes() from Utils which retrieves an array of
|
||||
* location type IDs and names from cache or database.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public static function getLocationTypeName(): string {
|
||||
return static::LOCATION_TYPE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a list of recipients.
|
||||
*
|
||||
* @return array E-mail addresses ['john.doe@example.org', ...]
|
||||
*/
|
||||
public abstract function getRecipients(): array;
|
||||
|
||||
/**
|
||||
* Returns this mailing lists id.
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function getId(): int {
|
||||
return (int) $this->getEntity()['id'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Try to find an existing contact by the given parameters.
|
||||
* First tries to find the contact by the SID, then by the e-mail address
|
||||
* and finally by the first and last name (if restricting tags are set).
|
||||
*
|
||||
* @param string|null $firstName
|
||||
* @param string|null $lastName
|
||||
* @param string|null $email
|
||||
* @param string|null $sid
|
||||
*
|
||||
* @return array|null ['contact' => $contact, 'found_by' => $found_by]
|
||||
* @throws \Civi\Mailinglistsync\Exceptions\MailinglistException
|
||||
*/
|
||||
protected function findExistingContact(
|
||||
string $firstName = NULL,
|
||||
string $lastName = NULL,
|
||||
string $email = NULL,
|
||||
string $sid = NULL,
|
||||
): ?array {
|
||||
|
||||
// Get the tags to restrict the search to.
|
||||
$tags = \Civi::settings()->get(E::SHORT_NAME . '_ad_contact_tags');
|
||||
|
||||
// Prepare the get call for reuse.
|
||||
$prepareGetEmail = function () use ($tags,) {
|
||||
$selectFields = [
|
||||
'id',
|
||||
'first_name',
|
||||
'last_name',
|
||||
'email.email',
|
||||
GroupMailingList::CUSTOM_GROUP_NAME . '.Active_Directory_SID'
|
||||
];
|
||||
$call = \Civi\Api4\Contact::get()
|
||||
->addSelect(...$selectFields)
|
||||
->addJoin('Email AS email', 'LEFT', ['id', '=', 'email.contact_id']);
|
||||
if ($tags) {
|
||||
$call->addJoin('EntityTag AS entity_tag', 'LEFT',
|
||||
['id', '=', 'entity_tag.entity_id'],
|
||||
['entity_tag.entity_table', '=', 'civicrm_contact'],
|
||||
['entity_tag.tag_id', 'IN', $tags]
|
||||
);
|
||||
}
|
||||
return $call;
|
||||
};
|
||||
|
||||
// Try to find the contact by the SID.
|
||||
try {
|
||||
$contact = $prepareGetEmail()
|
||||
->addWhere(GroupMailingList::CUSTOM_GROUP_NAME . '.Active_Directory_SID', '=', $sid)
|
||||
->execute()
|
||||
->getArrayCopy();
|
||||
}
|
||||
catch (\Exception $e) {
|
||||
throw new MailinglistException(
|
||||
"Could not get contact by SID '$sid': $e",
|
||||
MailinglistException::ERROR_CODE_GET_CONTACT_FAILED,
|
||||
);
|
||||
}
|
||||
if (count($contact) > 1) {
|
||||
throw new MailinglistException(
|
||||
"Multiple contacts with the same SID '$sid' found",
|
||||
MailinglistException::ERROR_CODE_MULTIPLE_CONTACTS_FOUND
|
||||
);
|
||||
}
|
||||
elseif (count($contact) === 1) {
|
||||
return ['contact' => array_pop($contact), 'found_by' => 'sid'];
|
||||
}
|
||||
|
||||
// Try fo find the contact by the e-mail address.
|
||||
try {
|
||||
$contact = $prepareGetEmail()
|
||||
->addWhere('email', '=', $email)
|
||||
->execute()
|
||||
->getArrayCopy();
|
||||
}
|
||||
catch (\Exception $e) {
|
||||
throw new MailinglistException(
|
||||
"Could not get contact by e-mail address '$email': $e",
|
||||
MailinglistException::ERROR_CODE_GET_CONTACT_FAILED,
|
||||
);
|
||||
}
|
||||
if (count($contact) > 1) {
|
||||
throw new MailinglistException(
|
||||
"Multiple contacts with the same e-mail address '$email' found",
|
||||
MailinglistException::ERROR_CODE_MULTIPLE_CONTACTS_FOUND
|
||||
);
|
||||
}
|
||||
elseif (count($contact) === 1) {
|
||||
return ['contact' => array_pop($contact), 'found_by' => 'email'];
|
||||
}
|
||||
|
||||
// Try to find the contact by the first and last name and only if the tags are set.
|
||||
if ($tags) {
|
||||
try {
|
||||
$contact = $prepareGetEmail()
|
||||
->addWhere('first_name', '=', $firstName)
|
||||
->addWhere('last_name', '=', $lastName)
|
||||
->execute()
|
||||
->getArrayCopy();
|
||||
}
|
||||
catch (\Exception $e) {
|
||||
throw new MailinglistException(
|
||||
"Could not get contact by first and last name '$firstName $lastName': $e",
|
||||
MailinglistException::ERROR_CODE_GET_CONTACT_FAILED,
|
||||
);
|
||||
}
|
||||
if (count($contact) > 1) {
|
||||
throw new MailinglistException(
|
||||
"Multiple contacts with the same first and last name found",
|
||||
MailinglistException::ERROR_CODE_MULTIPLE_CONTACTS_FOUND
|
||||
);
|
||||
}
|
||||
elseif (count($contact) === 1) {
|
||||
return ['contact' => array_pop($contact), 'found_by' => 'names'];
|
||||
}
|
||||
}
|
||||
|
||||
// If no contact was found, return NULL.
|
||||
return NULL;
|
||||
}
|
||||
}
|
56
Civi/Mailinglistsync/EventMailingList.php
Normal file
56
Civi/Mailinglistsync/EventMailingList.php
Normal file
|
@ -0,0 +1,56 @@
|
|||
<?php
|
||||
|
||||
namespace Civi\Mailinglistsync;
|
||||
|
||||
use CRM_Mailinglistsync_ExtensionUtil as E;
|
||||
use Civi\Api4\Event;
|
||||
|
||||
class EventMailingList extends BaseMailingList {
|
||||
|
||||
public const CUSTOM_GROUP_NAME = 'Event_Mailing_List';
|
||||
|
||||
public const LOCATION_TYPE = 'Event_Mailing_List_Address';
|
||||
|
||||
protected const RELATED_CLASS = Event::class;
|
||||
protected const RELATED_TYPE = 'event';
|
||||
|
||||
protected array $event;
|
||||
|
||||
/**
|
||||
* Returns the related event.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
protected function getEntity(): array {
|
||||
return $this->event;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the related event.
|
||||
*
|
||||
* @param array $value
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function setEntity(array $value): void {
|
||||
$this->event = $value;
|
||||
}
|
||||
|
||||
public function getRecipients(): array {
|
||||
// TODO: Implement getRecipients() method.
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a list of participants status that are enabled for the mailing list.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public static function getEnabledParticipantStatus(): array {
|
||||
return MailingListSettings::get(E::SHORT_NAME . '_participant_status');
|
||||
}
|
||||
|
||||
public static function create(array $values): BaseMailingList {
|
||||
// TODO: Implement create() method.
|
||||
}
|
||||
|
||||
}
|
53
Civi/Mailinglistsync/Exceptions/BaseException.php
Normal file
53
Civi/Mailinglistsync/Exceptions/BaseException.php
Normal file
|
@ -0,0 +1,53 @@
|
|||
<?php
|
||||
|
||||
namespace Civi\Mailinglistsync\Exceptions;
|
||||
|
||||
use CRM_Mailinglistsync_ExtensionUtil as E;
|
||||
|
||||
/**
|
||||
* A simple custom exception class that indicates a problem within a class
|
||||
* of the de.propeace.mailinglist extension.
|
||||
*/
|
||||
class BaseException extends \CRM_Core_Exception {
|
||||
|
||||
/**
|
||||
* @var int|string
|
||||
*/
|
||||
protected $code;
|
||||
|
||||
protected string $log_message;
|
||||
|
||||
/**
|
||||
* BaseException Constructor
|
||||
*
|
||||
* @param string $message
|
||||
* Error message
|
||||
* @param string $error_code
|
||||
* A meaningful error code
|
||||
*/
|
||||
public function __construct(string $message = '', string $error_code = '') {
|
||||
parent::__construct($message, 1);
|
||||
$this->log_message = !empty($message) ? E::LONG_NAME . ': ' . $message : '';
|
||||
$this->code = $error_code;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the error message, but with the extension name prefixed.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getLogMessage(): string {
|
||||
return $this->log_message;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the error code.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getErrorCode(): string {
|
||||
return $this->code;
|
||||
}
|
||||
|
||||
}
|
||||
|
32
Civi/Mailinglistsync/Exceptions/MailinglistException.php
Normal file
32
Civi/Mailinglistsync/Exceptions/MailinglistException.php
Normal file
|
@ -0,0 +1,32 @@
|
|||
<?php
|
||||
|
||||
namespace Civi\Mailinglistsync\Exceptions;
|
||||
|
||||
/**
|
||||
* A simple custom error indicating a problem with the validation of the
|
||||
* BaseMailingList and its subclasses.
|
||||
*/
|
||||
class MailinglistException extends BaseException {
|
||||
|
||||
public const ERROR_CODE_PERMISSION_DENIED = 'permission_denied';
|
||||
public const ERROR_CODE_UPDATE_EMAIL_ADDRESS_FAILED = 'update_email_address_failed';
|
||||
public const ERROR_CODE_DELETE_EMAIL_ADDRESS_FAILED = 'delete_email_address_failed';
|
||||
public const ERROR_CODE_GET_RECIPIENTS_FAILED = 'get_recipients_failed';
|
||||
public const ERROR_CODE_GET_LOCATION_TYPES_FAILED = 'get_location_types_failed';
|
||||
public const ERROR_CODE_INVALID_CLASS = 'invalid_class';
|
||||
public const ERROR_CODE_INVALID_EMAIL_ADDRESS = 'invalid_email_address';
|
||||
public const ERROR_CODE_GET_GROUP_MAILING_LISTS_FAILED = 'get_group_mailing_lists_failed';
|
||||
public const ERROR_CODE_GET_AD_GROUP_MAILING_LISTS_FAILED = 'get_group_mailing_lists_failed';
|
||||
public const ERROR_CODE_GET_EVENT_MAILING_LISTS_FAILED = 'get_event_mailing_lists_failed';
|
||||
public const ERROR_CODE_GET_CONTACT_FAILED = 'get_contact_failed';
|
||||
public const ERROR_CODE_CREATE_CONTACT_FAILED = 'create_contact_failed';
|
||||
public const ERROR_CODE_MULTIPLE_CONTACTS_FOUND = 'multiple_contacts_found';
|
||||
public const ERROR_CODE_INVALID_LOCATION_TYPE = 'invalid_location_type';
|
||||
public const ERROR_CODE_GROUP_CREATION_FAILED = 'group_creation_failed';
|
||||
public const ERROR_CODE_UPDATE_ENTITY_FAILED = 'update_entity_failed';
|
||||
public const ERROR_CODE_MULTIPLE_RECIPIENTS = 'multiple_recipients';
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
14
Civi/Mailinglistsync/Exceptions/MailinglistSyncException.php
Normal file
14
Civi/Mailinglistsync/Exceptions/MailinglistSyncException.php
Normal file
|
@ -0,0 +1,14 @@
|
|||
<?php
|
||||
|
||||
namespace Civi\Mailinglistsync\Exceptions;
|
||||
|
||||
/**
|
||||
* A simple custom error indicating a problem with the validation of the
|
||||
* synchronization of mailing lists.
|
||||
*/
|
||||
class MailinglistSyncException extends BaseException {
|
||||
|
||||
public const ERROR_CODE_UNSERIALIZE_SINGLETON = 'unserialize_singleton';
|
||||
|
||||
}
|
||||
|
157
Civi/Mailinglistsync/GroupMailingList.php
Normal file
157
Civi/Mailinglistsync/GroupMailingList.php
Normal file
|
@ -0,0 +1,157 @@
|
|||
<?php
|
||||
|
||||
namespace Civi\Mailinglistsync;
|
||||
|
||||
use Civi\Api4\Contact;
|
||||
use Civi\Api4\Group;
|
||||
use Civi\Mailinglistsync\Exceptions\MailinglistException;
|
||||
|
||||
class GroupMailingList extends BaseMailingList {
|
||||
|
||||
public const CUSTOM_GROUP_NAME = 'Group_Mailing_List';
|
||||
|
||||
public const LOCATION_TYPE = 'Mailing_List_Address';
|
||||
|
||||
protected const RELATED_CLASS = Group::class;
|
||||
protected const RELATED_TYPE = 'group';
|
||||
|
||||
protected array $group;
|
||||
|
||||
/**
|
||||
* Returns the related group.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
protected function getEntity(): array {
|
||||
return $this->group;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new GroupMailingList.
|
||||
*
|
||||
* @param string $title
|
||||
* @param string $description
|
||||
* @param string $email
|
||||
* @param string|null $sid
|
||||
*
|
||||
* @return \Civi\Mailinglistsync\GroupMailingList
|
||||
* @throws \Civi\Mailinglistsync\Exceptions\MailinglistException
|
||||
*/
|
||||
public static function createGroup(
|
||||
string $title,
|
||||
string $description,
|
||||
string $email,
|
||||
string $sid = NULL
|
||||
): self {
|
||||
try {
|
||||
$request = \Civi\Api4\Group::create()
|
||||
->addValue('title', $title)
|
||||
->addValue('description', $description)
|
||||
->addValue(static::CUSTOM_GROUP_NAME . '.Email', $email)
|
||||
->addValue('is_active', 1);
|
||||
|
||||
// If the group is an AD group, add the AD SID
|
||||
if (!empty($values['sid'])) {
|
||||
$request->addValue(static::CUSTOM_GROUP_NAME . '.SID', $values['sid']);
|
||||
}
|
||||
return new self($request->execute()->getArrayCopy()['id']);
|
||||
}
|
||||
catch (\Exception $e) {
|
||||
throw new MailinglistException(
|
||||
"Could not create group\n$e",
|
||||
MailinglistException::ERROR_CODE_GROUP_CREATION_FAILED
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the related group.
|
||||
*
|
||||
* @param array $value
|
||||
*/
|
||||
protected function setEntity(array $value): void {
|
||||
$this->group = $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the group is an AD mailing list.
|
||||
* @return bool
|
||||
*/
|
||||
public function isADGroup(): bool {
|
||||
return !empty($this->group[static::CUSTOM_GROUP_NAME . '.Active_Directory_UUID']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a list of recipients indexed by email address.
|
||||
*
|
||||
* @return array List of recipients (MailListRecipient)
|
||||
* @throws \Civi\Mailinglistsync\Exceptions\MailinglistException
|
||||
*/
|
||||
public function getRecipients(): array {
|
||||
try {
|
||||
$recipientData = Contact::get()
|
||||
->addSelect('id', 'first_name', 'last_name', 'email.email', 'Active_Directory.SID')
|
||||
->addJoin('Email AS email', 'INNER', ['id', '=', 'email.contact_id'])
|
||||
->addJoin('GroupContact AS group_contact', 'INNER', ['id', '=', 'group_contact.contact_id'])
|
||||
->addJoin('LocationType AS location_type', 'INNER', ['email.location_type_id', '=', 'location_type.id'])
|
||||
->addWhere('group_contact.group_id', '=', $this->group['id'])
|
||||
->addWhere('location_type.name', '=', static::LOCATION_TYPE)
|
||||
->addGroupBy('id')
|
||||
->execute()
|
||||
->getArrayCopy();
|
||||
}
|
||||
catch (\Exception $e) {
|
||||
throw new MailinglistException(
|
||||
"Could not get recipients for group with id '{$this->group['id']}'\n$e",
|
||||
MailinglistException::ERROR_CODE_GET_RECIPIENTS_FAILED
|
||||
);
|
||||
}
|
||||
|
||||
$recipients = [];
|
||||
foreach ($recipientData as $recipient) {
|
||||
$recipients[$recipient['email.email']] = new MailingListRecipient(
|
||||
contact_id: $recipient['id'],
|
||||
first_name: $recipient['first_name'],
|
||||
last_name: $recipient['last_name'],
|
||||
email: $recipient['email.email'],
|
||||
sid: $recipient['Active_Directory.SID'],
|
||||
);
|
||||
}
|
||||
|
||||
return $recipients;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the title of the group.
|
||||
*
|
||||
* @param string $title
|
||||
*
|
||||
* @return void
|
||||
* @throws \Civi\Mailinglistsync\Exceptions\MailinglistException
|
||||
*/
|
||||
public function updateGroupTitle(string $title): void {
|
||||
$this->update(['title' => $title]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the description of the group.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getGroupDescription(): string {
|
||||
return $this->group['description'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the description of the group.
|
||||
*
|
||||
* @param string $description
|
||||
*
|
||||
* @return void
|
||||
* @throws \Civi\Mailinglistsync\Exceptions\MailinglistException
|
||||
*/
|
||||
public function updateGroupDescription(string $description): void {
|
||||
$this->update(['description' => $description]);
|
||||
}
|
||||
|
||||
}
|
98
Civi/Mailinglistsync/MailingListManager.php
Normal file
98
Civi/Mailinglistsync/MailingListManager.php
Normal file
|
@ -0,0 +1,98 @@
|
|||
<?php
|
||||
|
||||
namespace Civi\Mailinglistsync;
|
||||
|
||||
use CRM_Mailinglistsync_ExtensionUtil as E;
|
||||
|
||||
class MailingListManager {
|
||||
|
||||
/**
|
||||
* Is the mailing list enabled?
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
private bool $enabled;
|
||||
|
||||
/**
|
||||
* Is logging enabled?
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
private mixed $logging;
|
||||
|
||||
/**
|
||||
* Host of the mlmmj server
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
private string $mlmmjHost;
|
||||
|
||||
/**
|
||||
* Token for the mlmmj server
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
private string $mlmmjToken;
|
||||
|
||||
/**
|
||||
* Port of the mlmmj server
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
private int $mlmmjPort;
|
||||
|
||||
/**
|
||||
* Host of the dovecot server
|
||||
*
|
||||
* @var string|mixed
|
||||
*/
|
||||
private string $dovecotHost;
|
||||
|
||||
/**
|
||||
* Token for the dovecot server
|
||||
*
|
||||
* @var string|mixed
|
||||
*/
|
||||
private string $dovecotToken;
|
||||
|
||||
/**
|
||||
* Port of the dovecot server
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
private int $dovecotPort;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @throws \Exception
|
||||
*/
|
||||
function __construct() {
|
||||
// Load settings
|
||||
$settings = MailingListSettings::get();
|
||||
$this->enabled = $settings[E::SHORT_NAME . '_enable'] ?? FALSE;
|
||||
$this->logging = $settings[E::SHORT_NAME . '_logging'] ?? FALSE;
|
||||
$this->mlmmjHost = $settings[E::SHORT_NAME . '_mlmmj_host'] ??
|
||||
throw new \Exception('No mlmmj host set');
|
||||
$this->mlmmjToken = $settings[E::SHORT_NAME . '_mlmmj_token'] ??
|
||||
throw new \Exception('No mlmmj token set');
|
||||
$this->mlmmjPort = $settings[E::SHORT_NAME . '_mlmmj_port'] ?? 443;
|
||||
$this->dovecotHost = $settings[E::SHORT_NAME . '_dovecot_host'] ??
|
||||
throw new \Exception('No dovecot host set');
|
||||
$this->dovecotToken = $settings[E::SHORT_NAME . '_dovecot_token'] ??
|
||||
throw new \Exception('No dovecot token set');
|
||||
$this->dovecotPort = $settings[E::SHORT_NAME . '_dovecot_port'] ?? 443;
|
||||
}
|
||||
|
||||
function createEmailAddress(string $emailAddress) {} // TODO
|
||||
|
||||
function deleteEmailAddress(string $emailAddress) {} // TODO
|
||||
|
||||
function createMailingList(BaseMailingList $mailingList) {} // TODO
|
||||
|
||||
function deleteMailingList(BaseMailingList $mailingList) {} // TODO
|
||||
|
||||
function updateMailingList(BaseMailingList $mailingList) {} // TODO
|
||||
|
||||
|
||||
}
|
335
Civi/Mailinglistsync/MailingListRecipient.php
Normal file
335
Civi/Mailinglistsync/MailingListRecipient.php
Normal file
|
@ -0,0 +1,335 @@
|
|||
<?php
|
||||
|
||||
namespace Civi\Mailinglistsync;
|
||||
|
||||
use Civi\Mailinglistsync\Exceptions\MailinglistException;
|
||||
use CRM_Mailinglistsync_ExtensionUtil as E;
|
||||
|
||||
class MailingListRecipient {
|
||||
|
||||
protected int $contactId;
|
||||
|
||||
protected string $firstName;
|
||||
|
||||
protected string $lastName;
|
||||
|
||||
protected string $email;
|
||||
|
||||
protected string $sid;
|
||||
|
||||
/**
|
||||
* Data to be updated. Use the `save()` method to apply the update.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
private $updateData;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param int $contact_id
|
||||
* @param string $first_name
|
||||
* @param string $last_name
|
||||
* @param string $email
|
||||
* @param string|null $sid
|
||||
*/
|
||||
public function __construct(
|
||||
int $contact_id,
|
||||
string $first_name,
|
||||
string $last_name,
|
||||
string $email,
|
||||
string $sid = NULL,
|
||||
) {
|
||||
$this->contactId = $contact_id;
|
||||
$this->firstName = $first_name;
|
||||
$this->lastName = $last_name;
|
||||
$this->email = $email;
|
||||
$this->sid = $sid;
|
||||
$this->updateData = [];
|
||||
}
|
||||
|
||||
// /**
|
||||
// * Get or create a contact.
|
||||
// *
|
||||
// * @param string $fistName
|
||||
// * @param string $lastName
|
||||
// * @param string $email
|
||||
// * @param string $locationType The location type of the email address
|
||||
// *
|
||||
// * @return \Civi\Mailinglistsync\MailingListRecipient
|
||||
// * @throws \Civi\Mailinglistsync\Exceptions\MailinglistException
|
||||
// */
|
||||
// public static function getOrCreate(
|
||||
// string $fistName,
|
||||
// string $lastName,
|
||||
// string $email,
|
||||
// string $locationType,
|
||||
// ): self {
|
||||
//
|
||||
// // Verify location type
|
||||
// $locationTypes = [
|
||||
// GroupMailingList::LOCATION_TYPE,
|
||||
// ADGroupMailingList::LOCATION_TYPE,
|
||||
// EventMailingList::LOCATION_TYPE,
|
||||
// ];
|
||||
// if (!in_array($locationType, $locationTypes)) {
|
||||
// throw new MailinglistException(
|
||||
// E::ts('Invalid location type'),
|
||||
// MailinglistException::ERROR_CODE_INVALID_LOCATION_TYPE,
|
||||
// );
|
||||
// }
|
||||
//
|
||||
// // Try to get contact
|
||||
// try {
|
||||
// $contact = \Civi\Api4\Contact::get()
|
||||
// ->addSelect('*', 'location_type.*')
|
||||
// ->addJoin('Email AS email', 'LEFT', ['id', '=', 'email.contact_id'])
|
||||
// ->addJoin('LocationType AS location_type', 'LEFT', ['email.location_type_id', '=', 'location_type.id'])
|
||||
// ->addWhere('email.email', '=', $email)
|
||||
// ->addWhere('location_type.name', '=', $locationType)
|
||||
// ->execute()
|
||||
// ->first();
|
||||
// }
|
||||
// catch (\Exception $e) {
|
||||
// throw new MailinglistException(
|
||||
// E::ts('Failed to get contact'),
|
||||
// MailinglistException::ERROR_CODE_GET_CONTACT_FAILED,
|
||||
// );
|
||||
// }
|
||||
//
|
||||
// // Create contact if it does not exist
|
||||
// if (empty($contact)) {
|
||||
// try {
|
||||
// $contact = \Civi\Api4\Contact::create(FALSE)
|
||||
// ->addValue('contact_type', 'Individual')
|
||||
// ->addValue('first_name', $fistName)
|
||||
// ->addValue('last_name', $lastName)
|
||||
// ->setChain([
|
||||
// 'Email.create',
|
||||
// \Civi\Api4\Email::create(FALSE)
|
||||
// ->addValue('contact_id', '$id')
|
||||
// ->addValue('email', $email)
|
||||
// ->addValue('location_type_id.name', $locationType),
|
||||
// ])
|
||||
// ->execute()
|
||||
// ->first();
|
||||
// array_pop($contact['Email.create']);
|
||||
// }
|
||||
// catch (\Exception $e) {
|
||||
// throw new MailinglistException(
|
||||
// E::ts('Failed to create contact'),
|
||||
// MailinglistException::ERROR_CODE_CREATE_CONTACT_FAILED,
|
||||
// );
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// return new static(contact: $contact, email: $email);
|
||||
// }
|
||||
|
||||
/**
|
||||
* Create a new contact and return the recipient.
|
||||
*
|
||||
* @param string $firstName
|
||||
* @param string $lastName
|
||||
* @param string $email
|
||||
* @param string $sid
|
||||
*
|
||||
* @return \Civi\Mailinglistsync\MailingListRecipient
|
||||
* @throws \Civi\Mailinglistsync\Exceptions\MailinglistException
|
||||
*/
|
||||
public static function createContact(
|
||||
string $firstName,
|
||||
string $lastName,
|
||||
string $email,
|
||||
string $sid,
|
||||
): self {
|
||||
|
||||
// Try to create a new contact
|
||||
try {
|
||||
$contact = \Civi\Api4\Contact::create(FALSE)
|
||||
->addValue('contact_type', 'Individual')
|
||||
->addValue('first_name', $firstName)
|
||||
->addValue('last_name', $lastName)
|
||||
->setChain([
|
||||
'Email.create',
|
||||
\Civi\Api4\Email::create(FALSE)
|
||||
->addValue('email', $email)
|
||||
->addValue('location_type_id.name', 'Main'),
|
||||
])
|
||||
->execute();
|
||||
}
|
||||
catch (\Exception $e) {
|
||||
throw new MailinglistException(
|
||||
E::ts("Failed to create contact: {$e->getMessage()}"),
|
||||
MailinglistException::ERROR_CODE_CREATE_CONTACT_FAILED,
|
||||
);
|
||||
}
|
||||
|
||||
return new static(
|
||||
contact_id: $contact['id'],
|
||||
first_name: $firstName,
|
||||
last_name: $lastName,
|
||||
email: $email,
|
||||
sid: $sid,
|
||||
);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a list of group mailing lists the contact is subscribed to.
|
||||
*
|
||||
* @return array
|
||||
* @throws \Civi\Mailinglistsync\Exceptions\MailinglistException
|
||||
*/
|
||||
public function getMailingLists(): array {
|
||||
$mailingLists = [];
|
||||
try {
|
||||
$groups = \Civi\Api4\GroupContact::get()
|
||||
->addSelect('group_id')
|
||||
->addWhere('contact_id', '=', $this->getContactId())
|
||||
->addWhere('status', '=', 'Added')
|
||||
->addWhere(GroupMailingList::CUSTOM_GROUP_NAME . '.Enable_mailing_list', '=', TRUE)
|
||||
->addWhere(GroupMailingList::CUSTOM_GROUP_NAME . '.Active_Directory_SID', 'IS EMPTY')
|
||||
->execute()
|
||||
->getArrayCopy();
|
||||
} catch (\Exception $e) {
|
||||
throw new MailinglistException(
|
||||
E::ts('Failed to get group mailing lists'),
|
||||
MailinglistException::ERROR_CODE_GET_GROUP_MAILING_LISTS_FAILED,
|
||||
);
|
||||
}
|
||||
|
||||
foreach ($groups as $group) {
|
||||
$mailingList = new GroupMailingList($group['group_id']);
|
||||
if ($mailingList->isADGroup()) {
|
||||
$mailingList = new ADGroupMailingList($group['group_id']); ;
|
||||
}
|
||||
$mailingLists[] = $mailingList;
|
||||
}
|
||||
|
||||
return $mailingLists;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a list of AD group mailing lists the contact is subscribed to.
|
||||
*
|
||||
* @return array
|
||||
* @throws \Civi\Mailinglistsync\Exceptions\MailinglistException
|
||||
*/
|
||||
public function getAdMailingLists(): array {
|
||||
$mailingLists = [];
|
||||
try {
|
||||
$groups = \Civi\Api4\GroupContact::get()
|
||||
->addSelect('group_id')
|
||||
->addWhere('contact_id', '=', $this->getContactId())
|
||||
->addWhere('status', '=', 'Added')
|
||||
->addWhere(GroupMailingList::CUSTOM_GROUP_NAME . '.Enable_mailing_list', '=', TRUE)
|
||||
->addWhere(GroupMailingList::CUSTOM_GROUP_NAME . '.Active_Directory_SID', 'IS NOT EMPTY')
|
||||
->execute()
|
||||
->getArrayCopy();
|
||||
} catch (\Exception $e) {
|
||||
throw new MailinglistException(
|
||||
E::ts('Failed to get AD group mailing lists'),
|
||||
MailinglistException::ERROR_CODE_GET_AD_GROUP_MAILING_LISTS_FAILED,
|
||||
);
|
||||
}
|
||||
|
||||
foreach ($groups as $group) {
|
||||
$mailingList = new GroupMailingList($group['group_id']);
|
||||
if ($mailingList->isADGroup()) {
|
||||
$mailingList = new ADGroupMailingList($group['group_id']); ;
|
||||
}
|
||||
$mailingLists[] = $mailingList;
|
||||
}
|
||||
|
||||
return $mailingLists;
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws \Civi\Mailinglistsync\Exceptions\MailinglistException
|
||||
*/
|
||||
public function getEventMailingLists(): array {
|
||||
$mailingLists = [];
|
||||
try {
|
||||
$groups = \Civi\Api4\Participant::get()
|
||||
->addSelect('event_id')
|
||||
->addWhere('contact_id', '=', $this->getContactId())
|
||||
->addWhere('status_id', 'IN', EventMailingList::getEnabledParticipantStatus())
|
||||
->addWhere(GroupMailingList::CUSTOM_GROUP_NAME . '.Enable_mailing_list', '=', TRUE)
|
||||
->execute()
|
||||
->getArrayCopy();
|
||||
}
|
||||
catch (\Exception $e) {
|
||||
throw new MailinglistException(
|
||||
E::ts('Failed to get event mailing lists'),
|
||||
MailinglistException::ERROR_CODE_GET_EVENT_MAILING_LISTS_FAILED,
|
||||
);
|
||||
}
|
||||
foreach ($groups as $group) {
|
||||
$mailingList = new EventMailingList($group['group_id']);
|
||||
$mailingLists[] = $mailingList;
|
||||
}
|
||||
|
||||
return $mailingLists;
|
||||
}
|
||||
|
||||
public function getContactId(): int {
|
||||
return $this->contactId;
|
||||
}
|
||||
|
||||
public function getFirstName(): string {
|
||||
return $this->firstName;
|
||||
}
|
||||
|
||||
public function getLastName(): string {
|
||||
return $this->lastName;
|
||||
}
|
||||
|
||||
public function getEmail(): string {
|
||||
return $this->email;
|
||||
}
|
||||
|
||||
public function getSid(): string {
|
||||
return $this->sid;
|
||||
}
|
||||
|
||||
public function setFirstName(string $firstName): void {
|
||||
$this->updateData += ['first_name' => $firstName];
|
||||
}
|
||||
|
||||
public function setLastName(string $lastName): void {
|
||||
$this->updateData += ['last_name' => $lastName];
|
||||
}
|
||||
|
||||
public function setEmail(string $email): void {
|
||||
$this->updateData += ['email' => $email];
|
||||
}
|
||||
|
||||
public function setSid(string $sid): void {
|
||||
$this->updateData += ['sid' => $sid];
|
||||
}
|
||||
|
||||
/**
|
||||
* Save the changes marked using the setter methods.
|
||||
*
|
||||
* @throws \Civi\Mailinglistsync\Exceptions\MailinglistException
|
||||
*/
|
||||
public function save(): void {
|
||||
if (empty($this->updateData)) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
\Civi\Api4\Contact::update()
|
||||
->setValues($this->updateData)
|
||||
->addWhere('id', '=', $this->getContactId())
|
||||
->execute();
|
||||
} catch (\Exception $e) {
|
||||
throw new MailinglistException(
|
||||
E::ts("Failed to update contact: {$e->getMessage()}"),
|
||||
MailinglistException::ERROR_CODE_UPDATE_ENTITY_FAILED,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
126
Civi/Mailinglistsync/MailingListSettings.php
Normal file
126
Civi/Mailinglistsync/MailingListSettings.php
Normal file
|
@ -0,0 +1,126 @@
|
|||
<?php
|
||||
|
||||
namespace Civi\Mailinglistsync;
|
||||
|
||||
use Civi\Authx\None;
|
||||
use CRM_Mailinglistsync_ExtensionUtil as E;
|
||||
|
||||
class MailingListSettings {
|
||||
|
||||
public const SETTINGS = [
|
||||
E::SHORT_NAME . '_enable' => [
|
||||
'data_type' => 'boolean',
|
||||
],
|
||||
E::SHORT_NAME . '_logging' => [
|
||||
'data_type' => 'boolean',
|
||||
],
|
||||
E::SHORT_NAME . '_mlmmj_host' => [
|
||||
'data_type' => 'string',
|
||||
],
|
||||
E::SHORT_NAME . '_mlmmj_token' => [
|
||||
'data_type' => 'string',
|
||||
],
|
||||
E::SHORT_NAME . '_mlmmj_port' => [
|
||||
'data_type' => 'integer',
|
||||
'default_value' => 443,
|
||||
],
|
||||
E::SHORT_NAME . '_dovecot_host' => [
|
||||
'data_type' => 'string',
|
||||
],
|
||||
E::SHORT_NAME . '_dovecot_token' => [
|
||||
'data_type' => 'string',
|
||||
],
|
||||
E::SHORT_NAME . '_dovecot_port' => [
|
||||
'data_type' => 'integer',
|
||||
'default_value' => 443,
|
||||
],
|
||||
E::SHORT_NAME . '_participant_status' => [
|
||||
'data_type' => 'array',
|
||||
],
|
||||
E::SHORT_NAME . '_ad_contact_tags' => [
|
||||
'data_type' => 'array',
|
||||
],
|
||||
];
|
||||
|
||||
/**
|
||||
* Stores a setting in Civi::settings
|
||||
*
|
||||
* @param array $settings
|
||||
* Expects an array with key => value for the setting
|
||||
*/
|
||||
public static function set(array $settings): void {
|
||||
// Remove possibly illegal data from settings
|
||||
$settings = array_intersect_key($settings, self::SETTINGS);
|
||||
|
||||
// Cast settings to the correct datatype
|
||||
foreach ($settings as $key => $value) {
|
||||
if ($value !== '') {
|
||||
settype($settings[$key], self::SETTINGS[$key]['data_type']);
|
||||
} else {
|
||||
$settings[$key] = NULL;
|
||||
}
|
||||
}
|
||||
|
||||
\Civi::settings()->add($settings);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a specific value of a setting if the key is passed as parameter.
|
||||
* Else all settings will be returned as associative array.
|
||||
*
|
||||
* @param null $key
|
||||
* The name of the setting or NULL
|
||||
*
|
||||
* @return array|mixed|null
|
||||
*/
|
||||
public static function get($key = NULL): mixed {
|
||||
if (!is_null($key)) {
|
||||
return \Civi::settings()->get($key);
|
||||
}
|
||||
else {
|
||||
$settings = [];
|
||||
foreach (array_keys(self::SETTINGS) as $key) {
|
||||
$settings[$key] = \Civi::settings()->get($key) ?? self::SETTINGS[$key]['default_value'] ?? NULL;
|
||||
}
|
||||
return $settings;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates the settings.
|
||||
*
|
||||
* @param array $values
|
||||
* @param array $errors
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function validate(array $values, array &$errors): void {
|
||||
// Validate url if synchronization is enabled
|
||||
$url = $values[E::SHORT_NAME . '_mailinglist_mlmmj_host'];
|
||||
if (!empty($values[E::SHORT_NAME . '_mailinglist_mlmmj_enable']) && !filter_var($url, FILTER_VALIDATE_URL)) {
|
||||
$errors[E::SHORT_NAME . '_mailinglist_mlmmj_host'] = E::ts('Invalid URL');
|
||||
}
|
||||
|
||||
// Validate port if synchronization is enabled and port is set
|
||||
$port = $values[E::SHORT_NAME . '_mailinglist_mlmmj_port'] ?? NULL;
|
||||
if (!empty($values[E::SHORT_NAME . '_mailinglist_mlmmj_enable']) && !empty($port)) {
|
||||
if (is_numeric($port)) {
|
||||
$errors[E::SHORT_NAME . '_mailinglist_mlmmj_port'] = E::ts('Port must be a number');
|
||||
}
|
||||
if ($port < 1 || $port > 65535) {
|
||||
$errors[E::SHORT_NAME . '_mailinglist_mlmmj_port'] = E::ts('Port must be between 1 and 65535');
|
||||
}
|
||||
}
|
||||
|
||||
// Require host and token if mlmmj is enabled
|
||||
if (!empty($values[E::SHORT_NAME . '_mailinglist_mlmmj_enable'])) {
|
||||
if (empty($values[E::SHORT_NAME . '_mailinglist_mlmmj_host'])) {
|
||||
$errors[E::SHORT_NAME . '_mailinglist_mlmmj_host'] = E::ts('Host is required');
|
||||
}
|
||||
if (empty($values[E::SHORT_NAME . '_mailinglist_mlmmj_token'])) {
|
||||
$errors[E::SHORT_NAME . '_mailinglist_mlmmj_token'] = E::ts('Token is required');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
177
Civi/Mailinglistsync/QueueHelper.php
Normal file
177
Civi/Mailinglistsync/QueueHelper.php
Normal file
|
@ -0,0 +1,177 @@
|
|||
<?php
|
||||
|
||||
namespace Civi\Mailinglistsync;
|
||||
|
||||
use CRM_Mailinglistsync_ExtensionUtil as E;
|
||||
use Civi\Mailinglistsync\Exceptions\MailinglistException;
|
||||
use Civi\Mailinglistsync\Exceptions\MailinglistSyncException;
|
||||
use CRM_Queue_Queue;
|
||||
|
||||
class QueueHelper {
|
||||
|
||||
/**
|
||||
* Singleton instances.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
private static array $instances = [];
|
||||
|
||||
private CRM_Queue_Queue $groupQueue;
|
||||
private CRM_Queue_Queue $eventQueue;
|
||||
private CRM_Queue_Queue $emailQueue;
|
||||
|
||||
private array $groups;
|
||||
|
||||
private array $events;
|
||||
|
||||
private array $emails;
|
||||
|
||||
/**
|
||||
* Protect singleton from being instantiated.
|
||||
*/
|
||||
protected function __construct() {
|
||||
// Get queues
|
||||
$this->groupQueue = \Civi::queue(
|
||||
'propeace-mailinglist-group-queue', [
|
||||
'type' => 'SqlParallel',
|
||||
'is_autorun' => FALSE,
|
||||
'reset' => FALSE,
|
||||
'error' => 'drop',
|
||||
]);
|
||||
$this->eventQueue = \Civi::queue(
|
||||
'propeace-mailinglist-group-queue', [
|
||||
'type' => 'SqlParallel',
|
||||
'is_autorun' => FALSE,
|
||||
'reset' => FALSE,
|
||||
'error' => 'drop',
|
||||
]);
|
||||
$this->emailQueue = \Civi::queue(
|
||||
'propeace-mailinglist-group-queue', [
|
||||
'type' => 'SqlParallel',
|
||||
'is_autorun' => FALSE,
|
||||
'reset' => FALSE,
|
||||
'error' => 'drop',
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Protect singleton from being cloned.
|
||||
*/
|
||||
protected function __clone() { }
|
||||
|
||||
/**
|
||||
* Protect unserialize method to prevent cloning of the instance.
|
||||
* @throws \Exception
|
||||
*/
|
||||
public function __wakeup()
|
||||
{
|
||||
throw new MailinglistSyncException(
|
||||
"Cannot unserialize a singleton.",
|
||||
MailinglistSyncException::ERROR_CODE_UNSERIALIZE_SINGLETON
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the singleton instance.
|
||||
*
|
||||
* @return \Civi\Mailinglistsync\QueueHelper
|
||||
*/
|
||||
public static function getInstance(): QueueHelper
|
||||
{
|
||||
$cls = static::class;
|
||||
if (!isset(self::$instances[$cls])) {
|
||||
self::$instances[$cls] = new static();
|
||||
\Civi::log()->debug(E::LONG_NAME . ": Created new instance of $cls");
|
||||
}
|
||||
|
||||
return self::$instances[$cls];
|
||||
}
|
||||
|
||||
/**
|
||||
* Getter for the group queue.
|
||||
*
|
||||
* @return \CRM_Queue_Queue
|
||||
*/
|
||||
public function getGroupQueue(): CRM_Queue_Queue {
|
||||
return $this->groupQueue;
|
||||
}
|
||||
|
||||
/**
|
||||
* Getter for the event queue.
|
||||
*
|
||||
* @return \CRM_Queue_Queue
|
||||
*/
|
||||
public function getEventQueue(): CRM_Queue_Queue {
|
||||
return $this->eventQueue;
|
||||
}
|
||||
|
||||
/**
|
||||
* Getter for the email queue.
|
||||
*
|
||||
* @return \CRM_Queue_Queue
|
||||
*/
|
||||
public function getEmailQueue(): CRM_Queue_Queue {
|
||||
return $this->emailQueue;
|
||||
}
|
||||
|
||||
public function getGroups(): array {
|
||||
return $this->groups;
|
||||
}
|
||||
|
||||
public function addToGroups(GroupMailingList $group): void {
|
||||
$this->groups[] = $group;
|
||||
}
|
||||
|
||||
public function getEvents(): array {
|
||||
return $this->events;
|
||||
}
|
||||
|
||||
public function addToEvents(EventMailingList $event): void {
|
||||
$this->events[] = $event;
|
||||
}
|
||||
|
||||
public function getEmails(): array {
|
||||
return $this->emails;
|
||||
}
|
||||
|
||||
public function addToEmails(string $email): void {
|
||||
$this->emails[] = $email;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stores an instance of the given class in the queue helper singleton.
|
||||
* Meant to be passed as callback to the queue.
|
||||
*
|
||||
* @param int $entityId
|
||||
* @param string $class
|
||||
*
|
||||
* @return void
|
||||
* @throws \Civi\Mailinglistsync\Exceptions\MailinglistException
|
||||
*/
|
||||
public static function storeInstance(int $entityId, string $class): void {
|
||||
|
||||
// Throw exception if class is invalid
|
||||
if ($class != GroupMailingList::class &&
|
||||
$class != ADGroupMailingList::class &&
|
||||
$class != EventMailingList::class) {
|
||||
throw new MailinglistException(
|
||||
"Invalid class '$class'",
|
||||
MailinglistException::ERROR_CODE_INVALID_CLASS
|
||||
);
|
||||
}
|
||||
|
||||
// Instantiate the mailing list object
|
||||
$instance = new $class();
|
||||
$instance->load($entityId);
|
||||
|
||||
// Store instance in the queue helper singleton
|
||||
match ($class) {
|
||||
GroupMailingList::class, ADGroupMailingList::class => self::getInstance()->addToGroups($instance),
|
||||
EventMailingList::class => self::getInstance()->addToEvents($instance),
|
||||
default => throw new MailinglistException(
|
||||
"Invalid class '$class'",
|
||||
MailinglistException::ERROR_CODE_INVALID_CLASS
|
||||
),
|
||||
};
|
||||
}
|
||||
}
|
49
Civi/Mailinglistsync/Utils.php
Normal file
49
Civi/Mailinglistsync/Utils.php
Normal file
|
@ -0,0 +1,49 @@
|
|||
<?php
|
||||
|
||||
namespace Civi\Mailinglistsync;
|
||||
|
||||
use Civi\Api4\LocationType;
|
||||
use Civi\Mailinglistsync\Exceptions\MailinglistException;
|
||||
use CRM_Mailinglistsync_ExtensionUtil as E;
|
||||
|
||||
/**
|
||||
* Gets the location type IDs for mailing list email-addresses either from
|
||||
* the database or from the cache.
|
||||
*
|
||||
* @return array
|
||||
* @throws \Civi\Mailinglistsync\Exceptions\MailinglistException
|
||||
*/
|
||||
function getLocationTypes(): array {
|
||||
// Try to get location types from cache
|
||||
$locationTypes = \Civi::cache()->get(E::SHORT_NAME . '_location_types');
|
||||
|
||||
// Get location types from database if not in cache
|
||||
if ($locationTypes === NULL) {
|
||||
$locationTypeNames = [
|
||||
GroupMailingList::getLocationTypeName(),
|
||||
ADGroupMailingList::getLocationTypeName(),
|
||||
EventMailingList::getLocationTypeName(),
|
||||
];
|
||||
try {
|
||||
$result = LocationType::get()
|
||||
->addSelect('id', 'name')
|
||||
->addWhere('name', 'IN', $locationTypeNames)
|
||||
->execute()
|
||||
->getArrayCopy();
|
||||
$locationTypes = [];
|
||||
foreach ($result as $locationType) {
|
||||
$locationTypes[$locationType['id']] = $locationType['name'];
|
||||
}
|
||||
}
|
||||
catch (\Exception $e) {
|
||||
throw new MailinglistException(
|
||||
E::ts('Could not get location types'),
|
||||
MailinglistException::ERROR_CODE_GET_LOCATION_TYPES_FAILED,
|
||||
);
|
||||
}
|
||||
// Cache location types
|
||||
\Civi::cache()->set(E::SHORT_NAME . '_location_types', $locationTypes);
|
||||
}
|
||||
|
||||
return $locationTypes;
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue