commit c93a06972b2b414387d4f426f69e3e21cfa5e5e4 Author: Marc Koch Date: Tue Mar 4 10:36:47 2025 +0100 🎉 initial commit diff --git a/CRM/Mailinglistsync/Form/MailingListSettings.php b/CRM/Mailinglistsync/Form/MailingListSettings.php new file mode 100644 index 0000000..feb30c6 --- /dev/null +++ b/CRM/Mailinglistsync/Form/MailingListSettings.php @@ -0,0 +1,146 @@ +add( + 'checkbox', + E::SHORT_NAME . '_enable', + label: E::ts('Enable synchronization of mailing lists groups and events'), + extra: ['class' => 'huge'], + ); + $this->add( + 'checkbox', + E::SHORT_NAME . '_logging', + label: E::ts('Enable logging of synchronization'), + extra: ['class' => 'huge'], + ); + $this->add( + 'text', + E::SHORT_NAME . '_mlmmj_host', + label: E::ts('mlmmj Host'), + extra: ['class' => 'huge'], + ); + $this->add( + 'password', + E::SHORT_NAME . '_mlmmj_token', + label: E::ts('mlmmj Token'), + extra: ['class' => 'huge'], + ); + $this->add( + 'text', + E::SHORT_NAME . '_mlmmj_port', + label: E::ts('mlmmj Port
(default: 443)'), + extra: ['class' => 'huge'], + ); + $this->add( + 'text', + E::SHORT_NAME . '_dovecot_host', + label: E::ts('Dovecot Host'), + extra: ['class' => 'huge'], + ); + $this->add( + 'password', + E::SHORT_NAME . '_dovecot_token', + label: E::ts('Dovecot Token'), + extra: ['class' => 'huge'], + ); + $this->add( + 'text', + E::SHORT_NAME . '_dovecot_port', + label: E::ts('Dovecot Port
(default: 443)'), + extra: ['class' => 'huge'], + ); + $this->add( + 'select', + E::SHORT_NAME . '_participant_status', + label: E::ts('Participant status'), + attributes: static::getParticipantStatusOptions(), + extra: ['class' => 'crm-select2 huge', 'multiple' => 'multiple'] + ); + $this->add( + 'select', + E::SHORT_NAME . '_ad_contact_tags', + label: E::ts('Tags to restrict contact matching for AD groups'), + attributes: static::getContactTags(), + extra: ['class' => 'crm-select2 huge', 'multiple' => 'multiple'] + ); + $this->addButtons([ + [ + 'type' => 'submit', + 'name' => E::ts('Submit'), + 'isDefault' => TRUE, + ], + ]); + + $this->assign('EXTENSION_SHORT_NAME', E::SHORT_NAME); + + parent::buildQuickForm(); + } + + public function setDefaultValues() { + return Settings::get(); + } + + public function postProcess(): void { + // Set configuration values + Settings::set($this->exportValues()); + + parent::postProcess(); + + // Display message + CRM_Utils_System::setUFMessage(E::ts('Settings saved')); + } + + public function validate(): bool { + parent::validate(); + Settings::validate($this->exportValues(), $this->_errors); + return (0 == count($this->_errors)); + } + + /** + * Get the participant status options. + * + * @return array + * + * @throws \Civi\API\Exception\UnauthorizedException + * @throws \CRM_Core_Exception + */ + protected static function getParticipantStatusOptions(): array { + $result = \Civi\Api4\ParticipantStatusType::get() + ->addSelect('id', 'label') + ->addWhere('is_active', '=', TRUE) + ->execute() + ->getArrayCopy(); + return array_column($result, 'label', 'id'); + } + + /** + * Get available contact tags. + * + * @return array + * + * @throws \CRM_Core_Exception + * @throws \Civi\API\Exception\UnauthorizedException + */ + protected static function getContactTags(): array { + $result = \Civi\Api4\Tag::get() + ->addSelect('id', 'label') + ->addWhere('used_for', '=', 'civicrm_contact') + ->addWhere('is_selectable', '=', TRUE) + ->addWhere('is_tagset', '=', FALSE) + ->execute() + ->getArrayCopy(); + return array_column($result, 'label', 'id'); + } +} diff --git a/CRM/Mailinglistsync/Upgrader.php b/CRM/Mailinglistsync/Upgrader.php new file mode 100644 index 0000000..41e1a78 --- /dev/null +++ b/CRM/Mailinglistsync/Upgrader.php @@ -0,0 +1,180 @@ +addValue('name', $location['name']) + ->addValue('display_name', $location['display_name']) + ->addValue('description', $location['description']) + ->addValue('is_default', $location['is_default']) + ->execute(); +// $this->ctx->log->info(E::ts('Created %1 LocationType', [1 => $location['name']])); + } + catch (\CRM_Core_Exception $e) { + if ($e->getMessage() == 'DB Error: already exists') { +// $this->ctx->log->info(E::ts('LocationType %1 already exists', [1 => $location['name']])); + continue; + } +// $this->ctx->log->err(E::ts('Failed to create %1 LocationType', [1 => $location['name']])); + throw $e; + } + } + } + + /** + * Example: Work with entities usually not available during the install step. + * + * This method can be used for any post-install tasks. For example, if a step + * of your installation depends on accessing an entity that is itself + * created during the installation (e.g., a setting or a managed entity), do + * so here to avoid order of operation problems. + */ + // public function postInstall(): void { + // $customFieldId = civicrm_api3('CustomField', 'getvalue', array( + // 'return' => array("id"), + // 'name' => "customFieldCreatedViaManagedHook", + // )); + // civicrm_api3('Setting', 'create', array( + // 'myWeirdFieldSetting' => array('id' => $customFieldId, 'weirdness' => 1), + // )); + // } + + /** + * Example: Run an external SQL script when the module is uninstalled. + * + * Note that if a file is present sql\auto_uninstall that will run regardless + * of this hook. + */ + // public function uninstall(): void { + // $this->executeSqlFile('sql/my_uninstall.sql'); + // } + + /** + * Runs when enabling the extension. + * + * @throws \CRM_Core_Exception + */ + public function enable(): void { + // Enable CustomGroups + foreach (MAILINGLISTSYNC_CUSTOM_GROUPS as $customGroup) { + CustomGroup::update(FALSE) + ->addWhere('name', '=', $customGroup) + ->addValue('is_active', 1) + ->execute(); +// $this->ctx->log->info(E::ts('Enabled %1 CustomGroup', [1 => $customGroup])); + } + } + + /** + * Runs when disabling the extension. + * + * @throws \CRM_Core_Exception + */ + public function disable(): void { + // Disable CustomGroups + foreach (MAILINGLISTSYNC_CUSTOM_GROUPS as $customGroup) { + CustomGroup::update(FALSE) + ->addWhere('name', '=', $customGroup) + ->addValue('is_active', 0) + ->execute(); +// $this->ctx->log->info(E::ts('Disabled %1 CustomGroup', [1 => $customGroup])); + } + } + + /** + * Example: Run a couple simple queries. + * + * @return TRUE on success + * @throws CRM_Core_Exception + */ + // public function upgrade_4200(): bool { + // $this->ctx->log->info('Applying update 4200'); + // CRM_Core_DAO::executeQuery('UPDATE foo SET bar = "whiz"'); + // CRM_Core_DAO::executeQuery('DELETE FROM bang WHERE willy = wonka(2)'); + // return TRUE; + // } + + /** + * Example: Run an external SQL script. + * + * @return TRUE on success + * @throws CRM_Core_Exception + */ + // public function upgrade_4201(): bool { + // $this->ctx->log->info('Applying update 4201'); + // // this path is relative to the extension base dir + // $this->executeSqlFile('sql/upgrade_4201.sql'); + // return TRUE; + // } + + /** + * Example: Run a slow upgrade process by breaking it up into smaller chunk. + * + * @return TRUE on success + * @throws CRM_Core_Exception + */ + // public function upgrade_4202(): bool { + // $this->ctx->log->info('Planning update 4202'); // PEAR Log interface + + // $this->addTask(E::ts('Process first step'), 'processPart1', $arg1, $arg2); + // $this->addTask(E::ts('Process second step'), 'processPart2', $arg3, $arg4); + // $this->addTask(E::ts('Process second step'), 'processPart3', $arg5); + // return TRUE; + // } + // public function processPart1($arg1, $arg2) { sleep(10); return TRUE; } + // public function processPart2($arg3, $arg4) { sleep(10); return TRUE; } + // public function processPart3($arg5) { sleep(10); return TRUE; } + + /** + * Example: Run an upgrade with a query that touches many (potentially + * millions) of records by breaking it up into smaller chunks. + * + * @return TRUE on success + * @throws CRM_Core_Exception + */ + // public function upgrade_4203(): bool { + // $this->ctx->log->info('Planning update 4203'); // PEAR Log interface + + // $minId = CRM_Core_DAO::singleValueQuery('SELECT coalesce(min(id),0) FROM civicrm_contribution'); + // $maxId = CRM_Core_DAO::singleValueQuery('SELECT coalesce(max(id),0) FROM civicrm_contribution'); + // for ($startId = $minId; $startId <= $maxId; $startId += self::BATCH_SIZE) { + // $endId = $startId + self::BATCH_SIZE - 1; + // $title = E::ts('Upgrade Batch (%1 => %2)', array( + // 1 => $startId, + // 2 => $endId, + // )); + // $sql = ' + // UPDATE civicrm_contribution SET foobar = apple(banana()+durian) + // WHERE id BETWEEN %1 and %2 + // '; + // $params = array( + // 1 => array($startId, 'Integer'), + // 2 => array($endId, 'Integer'), + // ); + // $this->addTask($title, 'executeSql', $sql, $params); + // } + // return TRUE; + // } + +} diff --git a/Civi/Mailinglistsync/ADGroupMailingList.php b/Civi/Mailinglistsync/ADGroupMailingList.php new file mode 100644 index 0000000..4912e0b --- /dev/null +++ b/Civi/Mailinglistsync/ADGroupMailingList.php @@ -0,0 +1,237 @@ +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; + } +} diff --git a/Civi/Mailinglistsync/BaseMailingList.php b/Civi/Mailinglistsync/BaseMailingList.php new file mode 100644 index 0000000..bbd3f91 --- /dev/null +++ b/Civi/Mailinglistsync/BaseMailingList.php @@ -0,0 +1,486 @@ +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; + } +} diff --git a/Civi/Mailinglistsync/EventMailingList.php b/Civi/Mailinglistsync/EventMailingList.php new file mode 100644 index 0000000..9ac3d62 --- /dev/null +++ b/Civi/Mailinglistsync/EventMailingList.php @@ -0,0 +1,56 @@ +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. + } + +} diff --git a/Civi/Mailinglistsync/Exceptions/BaseException.php b/Civi/Mailinglistsync/Exceptions/BaseException.php new file mode 100644 index 0000000..e203602 --- /dev/null +++ b/Civi/Mailinglistsync/Exceptions/BaseException.php @@ -0,0 +1,53 @@ +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; + } + +} + diff --git a/Civi/Mailinglistsync/Exceptions/MailinglistException.php b/Civi/Mailinglistsync/Exceptions/MailinglistException.php new file mode 100644 index 0000000..9da7d2e --- /dev/null +++ b/Civi/Mailinglistsync/Exceptions/MailinglistException.php @@ -0,0 +1,32 @@ +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]); + } + +} diff --git a/Civi/Mailinglistsync/MailingListManager.php b/Civi/Mailinglistsync/MailingListManager.php new file mode 100644 index 0000000..e52b749 --- /dev/null +++ b/Civi/Mailinglistsync/MailingListManager.php @@ -0,0 +1,98 @@ +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 + + +} diff --git a/Civi/Mailinglistsync/MailingListRecipient.php b/Civi/Mailinglistsync/MailingListRecipient.php new file mode 100644 index 0000000..dbd28b8 --- /dev/null +++ b/Civi/Mailinglistsync/MailingListRecipient.php @@ -0,0 +1,335 @@ +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, + ); + } + } + +} diff --git a/Civi/Mailinglistsync/MailingListSettings.php b/Civi/Mailinglistsync/MailingListSettings.php new file mode 100644 index 0000000..be2a8eb --- /dev/null +++ b/Civi/Mailinglistsync/MailingListSettings.php @@ -0,0 +1,126 @@ + [ + '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'); + } + } + } + +} diff --git a/Civi/Mailinglistsync/QueueHelper.php b/Civi/Mailinglistsync/QueueHelper.php new file mode 100644 index 0000000..89692e4 --- /dev/null +++ b/Civi/Mailinglistsync/QueueHelper.php @@ -0,0 +1,177 @@ +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 + ), + }; + } +} diff --git a/Civi/Mailinglistsync/Utils.php b/Civi/Mailinglistsync/Utils.php new file mode 100644 index 0000000..a0c0a12 --- /dev/null +++ b/Civi/Mailinglistsync/Utils.php @@ -0,0 +1,49 @@ +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; +} diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..41c2284 --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,667 @@ +Package: de.propeace.mailinglistsync +Copyright (C) 2025, FIXME +Licensed under the GNU Affero Public License 3.0 (below). + +------------------------------------------------------------------------------- + + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/README.md b/README.md new file mode 100644 index 0000000..6a9b86e --- /dev/null +++ b/README.md @@ -0,0 +1,12 @@ +# de.propeace.mailinglistsync +(*FIXME: In one or two paragraphs, describe what the extension does and why one would download it. *) + +This is an [extension for CiviCRM](https://docs.civicrm.org/sysadmin/en/latest/customize/extensions/), licensed under [AGPL-3.0](LICENSE.txt). + +## Getting Started + +(* FIXME: Where would a new user navigate to get started? What changes would they see? *) + +## Known Issues + +(* FIXME *) diff --git a/api/v3/Mailinglistsync/Adgroupsync.php b/api/v3/Mailinglistsync/Adgroupsync.php new file mode 100644 index 0000000..09442af --- /dev/null +++ b/api/v3/Mailinglistsync/Adgroupsync.php @@ -0,0 +1,203 @@ + 1, + 'type' => CRM_Utils_Type::T_STRING, + 'title' => E::ts('Active Directory SID'), + 'description' => E::ts('The Active Directory SID of the group'), + ]; + $spec['email'] = [ + 'api.required' => 1, + 'type' => CRM_Utils_Type::T_EMAIL, + 'title' => 'Email Address', + 'description' => 'Email address of the mailing list', + ]; + $spec['recipients'] = [ + 'api.required' => 1, + 'type' => CRM_Utils_Type::T_STRING, + 'title' => E::ts('Recipients'), + 'description' => E::ts('Array of email addresses and SIDs'), + ]; + $spec['name'] = [ + 'api.required' => 1, + 'type' => CRM_Utils_Type::T_STRING, + 'title' => E::ts('Mail List Name'), + 'description' => E::ts('Name of the mailing list'), + ]; + $spec['description'] = [ + 'api.required' => 1, + 'type' => CRM_Utils_Type::T_LONGTEXT, + 'title' => E::ts('Mail List Description'), + 'description' => E::ts('Description of the mailing list'), + ]; +} + +/** + * Mailinglistsync.Adgroupsync API + * + * @param array $params + * + * @return array + * API result descriptor + * + * @throws \Civi\Mailinglistsync\Exceptions\MailinglistException + * @throws CRM_Core_Exception + * @see civicrm_api3_create_success + */ +function civicrm_api3_mailinglistsync_Adgroupsync($params) { + + // Filter illegal params + $allowed_params = []; + _civicrm_api3_mailinglistsync_Adgroupsync_spec($allowed_params); + $params = array_intersect_key($params, $allowed_params); + + // Prepare result array + $result = [ + 'sid' => $params['sid'], + 'email' => $params['email'], + 'name' => $params['name'], + 'description' => $params['description'], + 'group_created' => FALSE, + 'group_updated' => FALSE, + ]; + + try { + // Try to get mailing list by SID + $adGroupMailingList = ADGroupMailingList::getBySID($params['sid']); + + // If no AD group mailing list found, create new + if (!$adGroupMailingList) { + try { + $adGroupMailingList = ADGroupMailingList::createGroup( + title: $params['name'], + description: $params['description'], + email: $params['email'], + sid: $params['sid'], + ); + $result['group_created']['group_id'] = $adGroupMailingList->getId(); + $result['group_created']['is_error'] = FALSE; + } + catch (MailinglistException $e) { + \Civi::log(E::LONG_NAME)->error($e->getLogMessage()); + $result['group_created']['is_error'] = TRUE; + } + } + + // Sync AD group mailing list values + else { + if ($adGroupMailingList->getTitle() !== $params['name']) { + try { + $adGroupMailingList->updateGroupTitle($params['name']); + \Civi::log(E::LONG_NAME)->info( + "Updated group '{$adGroupMailingList->getId()}' title from '{$adGroupMailingList->getTitle()}' to '{$params['name']}'" + ); + $result['group_updated']['title'] = [ + 'is_error' => FALSE, + 'old' => $adGroupMailingList->getTitle(), + 'new' => $params['name'], + ]; + } + catch (MailinglistException $e) { + \Civi::log(E::LONG_NAME)->error($e->getLogMessage()); + $result['group_updated']['title'] = [ + 'is_error' => TRUE, + 'error' => $e->getLogMessage(), + ]; + } + } + if ($adGroupMailingList->getGroupDescription() !== $params['description']) { + try { + $adGroupMailingList->updateGroupDescription($params['description']); + \Civi::log(E::LONG_NAME)->info( + "Updated group '{$adGroupMailingList->getId()}' description.'" + ); + $result['group_updated']['description'] = [ + 'is_error' => FALSE, + 'old' => $adGroupMailingList->getGroupDescription(), + 'new' => $params['description'], + ]; + } + catch (MailinglistException $e) { + \Civi::log(E::LONG_NAME)->error($e->getLogMessage()); + $result['group_updated']['description'] = [ + 'is_error' => TRUE, + 'error' => $e->getLogMessage(), + ]; + } + } + if ($adGroupMailingList->getEmailAddress() !== $params['email']) { + try { + $adGroupMailingList->updateEmailAddress($params['email']); + \Civi::log(E::LONG_NAME)->info( + "Updated group '{$adGroupMailingList->getId()}' email address from '{$adGroupMailingList->getEmailAddress()}' to '{$params['email']}'" + ); + $result['group_updated']['email'] = [ + 'is_error' => FALSE, + 'old' => $adGroupMailingList->getEmailAddress(), + 'new' => $params['email'], + ]; + } + catch (MailinglistException $e) { + \Civi::log(E::LONG_NAME)->error($e->getLogMessage()); + $result['group_updated']['email'] = [ + 'is_error' => TRUE, + 'error' => $e->getLogMessage(), + ]; + } + } + $adGroupMailingList->save(); + + if ($result['group_updated'] ?? FALSE) { + $result['group_updated']['error_count'] = count(array_filter($result['group_updated'], fn($v) => $v['is_error'])); + $result['group_updated']['is_error'] = $result['group_updated']['error_count'] > 0; + $result['group_updated']['group_id'] = $adGroupMailingList->getId(); + } + } + + // Sync group mailing list members + $result['recipients_updated'] = $adGroupMailingList->syncRecipients($params['recipients']); + + // Return error response if any errors occurred + $totalErrors = (int) ($result['group_created']['is_error'] ?? 0) + + ($result['group_updated']['error_count'] ?? 0) + + ($result['recipients_updated']['error_count'] ?? 0); + $result['is_error'] = $totalErrors > 0; + $result['error_count'] = $totalErrors; + if ($totalErrors > 0) { + return civicrm_api3_create_error( + "Failed to sync recipients. $totalErrors errors occurred.", + [ + 'values' => $result, + 'params' => $params, + 'entity' => 'Mailinglistsync', + 'action' => 'Adgroupsync', + ]); + + } + + // Else return success response + return civicrm_api3_create_success($result, $params, 'Mailinglistsync', 'Adgroupsync'); + } + catch (MailinglistException $me) { + \Civi::log(E::LONG_NAME)->error($me->getLogMessage()); + return civicrm_api3_create_error($me->getLogMessage(), + [ + 'params' => $params, + 'entity' => 'Mailinglistsync', + 'action' => 'Adgroupsync', + ]); + } +} diff --git a/api/v3/Mailinglistsync/Mlmmjsync.php b/api/v3/Mailinglistsync/Mlmmjsync.php new file mode 100644 index 0000000..808b9d7 --- /dev/null +++ b/api/v3/Mailinglistsync/Mlmmjsync.php @@ -0,0 +1,97 @@ +getGroupQueue(); + $eventQueue = $qh->getEventQueue(); + $emailQueue = $qh->getEmailQueue(); + + // Create runners + $groupRunner = new CRM_Queue_Runner([ + 'title' => ts('ProPeace GroupMailinglist Runner'), + 'queue' => $groupQueue, + 'errorMode' => CRM_Queue_Runner::ERROR_CONTINUE, + ]); + $eventRunner = new CRM_Queue_Runner([ + 'title' => ts('ProPeace EventMailinglist Runner'), + 'queue' => $eventQueue, + 'errorMode' => CRM_Queue_Runner::ERROR_CONTINUE, + ]); + $emailRunner = new CRM_Queue_Runner([ + 'title' => ts('ProPeace EmailMailinglist Runner'), + 'queue' => $emailQueue, + 'errorMode' => CRM_Queue_Runner::ERROR_CONTINUE, + ]); + + // Run runners + $results = []; + $continue = TRUE; + while($continue) { + $result = $groupRunner->runNext(false); + if (!$result['is_continue']) { + $continue = false; + } + $results['runners'][] = $result; + } + + $groups = $qh->getGroups(); + $events = $qh->getEvents(); + $emails = $qh->getEmails(); + + // TODO: Sync groups and events just once and invoke syncing + + $mailingListsToSync = []; + foreach ($groups as $group) { + $mailingListsToSync[$group->getId()] = $group; + } + foreach ($events as $event) { + $mailingListsToSync[$event->getId()] = $event; + } + foreach ($emails as $email) { + $emailGroups = $email->getGroups(); + $emailEvents = $email->getEvents(); + foreach ($emailGroups as $group) { + $mailingListsToSync[$group->getId()] = $group; + } + foreach ($emailEvents as $event) { + $mailingListsToSync[$event->getId()] = $event; + } + } + + foreach ($mailingListsToSync as $mailingList) { + $results['mailing_lists'][] = $mailingList->sync(); + } + + return civicrm_api3_create_success($results, [], 'Mailinglist', 'Mlmmjsync'); + + /* + throw new CRM_Core_Exception('Everyone knows that the magicword is "sesame"', 'magicword_incorrect'); + */ +} diff --git a/info.xml b/info.xml new file mode 100644 index 0000000..eb2d7b2 --- /dev/null +++ b/info.xml @@ -0,0 +1,44 @@ + + + mailinglistsync + Mailinglistsync + This extension allows you to create mailing lists for groups and events using an external mlmmj instance. It also offers the option of obtaining groups from an Active Directory. + AGPL-3.0 + + + Marc Koch + koch@forumZFD.de + Maintainer + + + + + + + https://www.gnu.org/licenses/agpl-3.0.html + + 2025-03-04 + 1.0.0 + alpha + + 5.80 + + This is a new, undeveloped module + + + + + + CRM/Mailinglistsync + 24.09.1 + + + menu-xml@1.0.0 + mgd-php@1.0.0 + smarty@1.0.3 + entity-types-php@2.0.0 + setting-php@1.0.0 + + + CRM_Mailinglistsync_Upgrader + diff --git a/mailinglistsync.civix.php b/mailinglistsync.civix.php new file mode 100644 index 0000000..8dcc2b5 --- /dev/null +++ b/mailinglistsync.civix.php @@ -0,0 +1,210 @@ +getUrl(self::LONG_NAME), '/'); + } + return CRM_Core_Resources::singleton()->getUrl(self::LONG_NAME, $file); + } + + /** + * Get the path of a resource file (in this extension). + * + * @param string|NULL $file + * Ex: NULL. + * Ex: 'css/foo.css'. + * @return string + * Ex: '/var/www/example.org/sites/default/ext/org.example.foo'. + * Ex: '/var/www/example.org/sites/default/ext/org.example.foo/css/foo.css'. + */ + public static function path($file = NULL) { + // return CRM_Core_Resources::singleton()->getPath(self::LONG_NAME, $file); + return __DIR__ . ($file === NULL ? '' : (DIRECTORY_SEPARATOR . $file)); + } + + /** + * Get the name of a class within this extension. + * + * @param string $suffix + * Ex: 'Page_HelloWorld' or 'Page\\HelloWorld'. + * @return string + * Ex: 'CRM_Foo_Page_HelloWorld'. + */ + public static function findClass($suffix) { + return self::CLASS_PREFIX . '_' . str_replace('\\', '_', $suffix); + } + + /** + * @return \CiviMix\Schema\SchemaHelperInterface + */ + public static function schema() { + if (!isset($GLOBALS['CiviMixSchema'])) { + pathload()->loadPackage('civimix-schema@5', TRUE); + } + return $GLOBALS['CiviMixSchema']->getHelper(static::LONG_NAME); + } + +} + +use CRM_Mailinglistsync_ExtensionUtil as E; + +/** + * (Delegated) Implements hook_civicrm_config(). + * + * @link https://docs.civicrm.org/dev/en/latest/hooks/hook_civicrm_config + */ +function _mailinglistsync_civix_civicrm_config($config = NULL) { + static $configured = FALSE; + if ($configured) { + return; + } + $configured = TRUE; + + $extRoot = __DIR__ . DIRECTORY_SEPARATOR; + $include_path = $extRoot . PATH_SEPARATOR . get_include_path(); + set_include_path($include_path); + // Based on , this does not currently require mixin/polyfill.php. +} + +/** + * Implements hook_civicrm_install(). + * + * @link https://docs.civicrm.org/dev/en/latest/hooks/hook_civicrm_install + */ +function _mailinglistsync_civix_civicrm_install() { + _mailinglistsync_civix_civicrm_config(); + // Based on , this does not currently require mixin/polyfill.php. +} + +/** + * (Delegated) Implements hook_civicrm_enable(). + * + * @link https://docs.civicrm.org/dev/en/latest/hooks/hook_civicrm_enable + */ +function _mailinglistsync_civix_civicrm_enable(): void { + _mailinglistsync_civix_civicrm_config(); + // Based on , this does not currently require mixin/polyfill.php. +} + +/** + * Inserts a navigation menu item at a given place in the hierarchy. + * + * @param array $menu - menu hierarchy + * @param string $path - path to parent of this item, e.g. 'my_extension/submenu' + * 'Mailing', or 'Administer/System Settings' + * @param array $item - the item to insert (parent/child attributes will be + * filled for you) + * + * @return bool + */ +function _mailinglistsync_civix_insert_navigation_menu(&$menu, $path, $item) { + // If we are done going down the path, insert menu + if (empty($path)) { + $menu[] = [ + 'attributes' => array_merge([ + 'label' => $item['name'] ?? NULL, + 'active' => 1, + ], $item), + ]; + return TRUE; + } + else { + // Find an recurse into the next level down + $found = FALSE; + $path = explode('/', $path); + $first = array_shift($path); + foreach ($menu as $key => &$entry) { + if ($entry['attributes']['name'] == $first) { + if (!isset($entry['child'])) { + $entry['child'] = []; + } + $found = _mailinglistsync_civix_insert_navigation_menu($entry['child'], implode('/', $path), $item); + } + } + return $found; + } +} + +/** + * (Delegated) Implements hook_civicrm_navigationMenu(). + */ +function _mailinglistsync_civix_navigationMenu(&$nodes) { + if (!is_callable(['CRM_Core_BAO_Navigation', 'fixNavigationMenu'])) { + _mailinglistsync_civix_fixNavigationMenu($nodes); + } +} + +/** + * Given a navigation menu, generate navIDs for any items which are + * missing them. + */ +function _mailinglistsync_civix_fixNavigationMenu(&$nodes) { + $maxNavID = 1; + array_walk_recursive($nodes, function($item, $key) use (&$maxNavID) { + if ($key === 'navID') { + $maxNavID = max($maxNavID, $item); + } + }); + _mailinglistsync_civix_fixNavigationMenuItems($nodes, $maxNavID, NULL); +} + +function _mailinglistsync_civix_fixNavigationMenuItems(&$nodes, &$maxNavID, $parentID) { + $origKeys = array_keys($nodes); + foreach ($origKeys as $origKey) { + if (!isset($nodes[$origKey]['attributes']['parentID']) && $parentID !== NULL) { + $nodes[$origKey]['attributes']['parentID'] = $parentID; + } + // If no navID, then assign navID and fix key. + if (!isset($nodes[$origKey]['attributes']['navID'])) { + $newKey = ++$maxNavID; + $nodes[$origKey]['attributes']['navID'] = $newKey; + $nodes[$newKey] = $nodes[$origKey]; + unset($nodes[$origKey]); + $origKey = $newKey; + } + if (isset($nodes[$origKey]['child']) && is_array($nodes[$origKey]['child'])) { + _mailinglistsync_civix_fixNavigationMenuItems($nodes[$origKey]['child'], $maxNavID, $nodes[$origKey]['attributes']['navID']); + } + } +} diff --git a/mailinglistsync.php b/mailinglistsync.php new file mode 100644 index 0000000..605c139 --- /dev/null +++ b/mailinglistsync.php @@ -0,0 +1,368 @@ +isMailingList() && !CRM_Core_Permission::check('manage_group_mailinglists')) { + CRM_Core_Session::setStatus( + E::ts('You do not have permission to manage memberships of mailing list groups.'), + E::ts('Permission Denied'), + 'alert', + ); + throw new MailinglistException( + 'Permission to manage group membership denied', + MailinglistException::ERROR_CODE_PERMISSION_DENIED + ); + } + + // Check permission to alter AD group membership + if ($mailingList->isADGroup() && !CRM_Core_Permission::check('manage_ad_mailinglists')) { + CRM_Core_Session::setStatus( + E::ts('You do not have permission to manage memberships of AD mailing list groups.'), + E::ts('Permission Denied'), + 'alert', + ); + throw new MailinglistException( + 'Permission to manage AD group membership denied', + MailinglistException::ERROR_CODE_PERMISSION_DENIED + ); + } + } + + // Check on event mailing lists + elseif ($objectName == 'Participant') { + $eventId = $objectRef->event_id ?? Event::get() + ->addSelect('event_id') + ->addWhere('id', '=', $objectId) + ->execute() + ->first()['event_id']; + $mailingList = new GroupMailingList($eventId); + + // Check permission to alter event mailing list + if ($mailingList->isMailingList() && !CRM_Core_Permission::check('manage_event_mailinglists')) { + CRM_Core_Session::setStatus( + E::ts('You do not have permission to manage event mailing lists.'), + E::ts('Permission Denied'), + 'alert', + ); + throw new MailinglistException( + 'Permission to manage event mailing list denied', + MailinglistException::ERROR_CODE_PERMISSION_DENIED + ); + } + } + + // Delete mlmmj mailing list + if ( + $op == 'delete' && + !empty($mailingList) && + ($mailingList->isMailingList() || $mailingList->isADGroup()) + ) { + $mailingList->deleteMailingList(); // TODO + } + + // If this is an e-mail address of a location type used for mailing lists + if ($objectName == 'Email' && in_array((int) $objectRef->location_type_id, array_keys(getLocationTypes()))) { + + // Ensure that only one e-mail address of this location type is set for this contact + $result = Email::get() + ->addSelect('contact_id', 'contact.display_name') + ->addJoin('LocationType AS location_type', 'INNER', + ['location_type_id', '=', 'location_type.id']) + ->addWhere('location_type_id', '=', $objectRef->location_type_id) + ->addWhere('contact_id', '=', $objectRef->contact_id) + ->addWhere('id', '!=', $objectRef->id) + ->execute() + ->first(); + + if (!empty($result) && $op != 'delete') { + throw new MailinglistException( + E::ts("An e-mail address of a mailing list type is already used for this contact"), + MailinglistException::ERROR_CODE_UPDATE_EMAIL_ADDRESS_FAILED + ); + } + + // Ensure that this email address is only used for one contact + $results = Email::get() + ->addSelect('contact.id', 'contact.display_name') + ->addJoin('Contact AS contact', 'LEFT', ['contact_id', '=', 'contact.id']) + ->addWhere('contact_id', '!=', $objectRef->contact_id) + ->addWhere('email', '=', $objectRef->email) + ->addWhere('location_type_id', '=', $objectRef->location_type_id) + ->execute() + ->getArrayCopy(); + + if (!empty($results) && $op != 'delete') { + + // Delete e-mail address if it is not allowed + // TODO: This is a workaround. We should prevent the creation of the e-mail address in the first place. + _mailinglistsync_delete_email_address((int) $objectRef->id); + + $contacts = []; + foreach ($results as $result) { + $contactId = $result['contact.id']; + $contactName = $result['contact.display_name']; + $contactUrl = CRM_Utils_System::url('civicrm/contact/view', 'reset=1&cid=' . $contactId, TRUE); + $contacts[] = "$contactName (id: $contactId)"; + } + $message = count($contacts) > 1 + ? E::ts( + "This e-mail address is already used for other contacts: %1", + [1 => implode(', ', $contacts)] + ) + : E::ts( + "This e-mail address is already used for another contact: %1", + [1 => array_pop($contacts)] + ); + CRM_Core_Session::setStatus( + E::ts($message), + E::ts('E-Mail Address Already Used'), + 'error', + ['unique' => TRUE] + ); + } + } + } +} + +/** + * Synchronize group and event mailing lists whenever they change by adding + * them to the queue which will be processed by the cron job. + * + * @throws \Civi\API\Exception\UnauthorizedException + * @throws \Civi\Mailinglistsync\Exceptions\MailinglistException + * @throws \CRM_Core_Exception + */ +function mailinglistsync_civicrm_postCommit(string $op, string $objectName, int $objectId, &$objectRef) { + // Sync groups mailing list + // Note: I wonder why $objectId refers to the group instead of the group contact here. + if ($objectName == 'GroupContact') { + $mailingList = new GroupMailingList($objectId); + if ($mailingList->isMailingList() || $mailingList->isADGroup()) { + // Queue group for synchronization with mlmmj + $queue = \Civi::queue('propeace-mailinglist-group-queue', [ + 'type' => 'SqlParallel', + 'is_autorun' => FALSE, + 'reset' => FALSE, + 'error' => 'drop', + ]); + $queue->createItem(new CRM_Queue_Task( + // callback + ['Civi\Mailinglistsync\QueueHelper', 'storeInstance'], + // arguments + [$mailingList->getId(), $mailingList::class], + // title + "Sync Group ID '$objectId'" + )); + } + } + + // Sync event mailing lists + elseif ($objectName == 'Participant') { + $eventId = $objectRef->event_id ?? Participant::get() + ->addSelect('event_id') + ->addWhere('id', '=', $objectId) + ->execute() + ->first()['event_id']; + $mailingList = new EventMailingList($eventId); + if ($mailingList->isMailingList()) { + // Queue event for synchronization with mlmmj + $queue = \Civi::queue('propeace-mailinglist-event-queue', [ + 'type' => 'SqlParallel', + 'is_autorun' => FALSE, + 'reset' => FALSE, + 'error' => 'drop', + ]); + $queue->createItem(new CRM_Queue_Task( + // callback + ['Civi\Mailinglistsync\QueueHelper', 'storeInstance'], + // arguments + [$mailingList->getId(), $mailingList::class], + // title + "Sync Event ID '$objectId'" + )); + } + } + + // Sync e-mail addresses + elseif ($objectName == 'Email' && in_array((int) $objectRef->location_type_id, array_keys(getLocationTypes()))) { + + // Only sync e-mail addresses of mailing list types + $locationType = \Civi\Api4\LocationType::get() + ->addSelect('name') + ->addWhere('id', '=', $objectRef->location_type_id) + ->execute() + ->first()['name']; + if (!in_array($locationType, [ + GroupMailingList::LOCATION_TYPE, + ADGroupMailingList::LOCATION_TYPE, + EventMailingList::LOCATION_TYPE, + ])) { + return; + } + + // Queue email address for synchronization with mlmmj + $queue = \Civi::queue('propeace-mailinglist-email-queue', [ + 'type' => 'SqlParallel', + 'is_autorun' => FALSE, + 'reset' => FALSE, + 'error' => 'drop', + ]); + $queue->createItem(new CRM_Queue_Task( + // callback + ['Civi\Mailinglistsync\QueueHelper', 'addToEmails'], + // arguments + [$objectRef->email], + // title + "Sync E-Mail '$objectRef->email'" + )); + } +} + +/** + * Implementation of hook_civicrm_permission + * + * @link https://docs.civicrm.org/dev/en/latest/hooks/hook_civicrm_permission/ + */ +function mailinglistsync_civicrm_permission(&$permissions) { + $permissions['manage_ad_mailinglists'] = [ + 'label' => E::SHORT_NAME . ': ' . E::ts('Manage AD Mailing Lists'), + 'description' => E::ts('Manage mailing list groups originating from Active Directory'), + 'disabled' => FALSE, + ]; + $permissions['manage_ad_address_type'] = [ + 'label' => E::SHORT_NAME . ': ' . E::ts('Manage AD Addresses'), + 'description' => E::ts('Manage addresses reserved for data originating from Active Directory'), + 'disabled' => FALSE, + ]; + $permissions['manage_group_mailinglists'] = [ + 'label' => E::SHORT_NAME . ': ' . E::ts('Manage Group Mailing Lists'), + 'description' => E::ts('Manage groups used as mailing lists'), + 'disabled' => FALSE, + ]; + $permissions['manage_event_mailinglists'] = [ + 'label' => E::SHORT_NAME . ': ' . E::ts('Manage Event Mailing Lists'), + 'description' => E::ts('Manage events used as mailing lists'), + 'disabled' => FALSE, + ]; +} + +/** + * Check permissions to alter event membership. + * + * @param \Civi\Mailinglistsync\EventMailingList $mailingList + * @param $errors + * + * @return void + */ +function _mailinglistsync_check_event_membership_permissions(EventMailingList $mailingList, &$errors): void { + if ($mailingList->isMailingList() && !CRM_Core_Permission::check('manage_event_mailinglists')) { + $errors['event_id'] = E::ts('You do not have permission to manage event membership.'); + } +} + +/** + * Unfortunately, we cannot prevent the creation of a new e-mail address within + * the post hook, so we have to delete it again if it is not allowed. + * + * @param int $emailId + * + * @return void + * @throws \Civi\Mailinglistsync\Exceptions\MailinglistException + */ +function _mailinglistsync_delete_email_address(int $emailId): void { + try { + $email = Email::delete() + ->addWhere('id', '=', $emailId) + ->execute(); + } + catch (\Exception $e) { + throw new MailinglistException( + E::ts('Failed to delete e-mail address'), + MailinglistException::ERROR_CODE_DELETE_EMAIL_ADDRESS_FAILED + ); + } +} diff --git a/managed/CustomGroup_Active_Directory.mgd.php b/managed/CustomGroup_Active_Directory.mgd.php new file mode 100644 index 0000000..90662b4 --- /dev/null +++ b/managed/CustomGroup_Active_Directory.mgd.php @@ -0,0 +1,53 @@ + 'CustomGroup_Active_Directory', + 'entity' => 'CustomGroup', + 'cleanup' => 'unused', + 'update' => 'unmodified', + 'params' => [ + 'version' => 4, + 'values' => [ + 'name' => 'Active_Directory', + 'title' => E::ts('Active Directory'), + 'style' => 'Inline', + 'collapse_display' => TRUE, + 'help_pre' => E::ts(''), + 'help_post' => E::ts(''), + 'weight' => 6, + 'collapse_adv_display' => TRUE, + 'created_date' => '2025-02-26 16:23:27', + 'is_public' => FALSE, + 'icon' => '', + ], + 'match' => ['name'], + ], + ], + [ + 'name' => 'CustomGroup_Active_Directory_CustomField_SID', + 'entity' => 'CustomField', + 'cleanup' => 'unused', + 'update' => 'unmodified', + 'params' => [ + 'version' => 4, + 'values' => [ + 'custom_group_id.name' => 'Active_Directory', + 'name' => 'SID', + 'label' => E::ts('Active Directory SID'), + 'html_type' => 'Text', + 'is_searchable' => TRUE, + 'help_post' => E::ts('The SID of this contact in the Active Directory.'), + 'is_view' => TRUE, + 'text_length' => 36, + 'note_columns' => 60, + 'note_rows' => 4, + 'column_name' => 'sid_42', + ], + 'match' => [ + 'name', + 'custom_group_id', + ], + ], + ], +]; diff --git a/managed/CustomGroup_Event_Mailing_List.mgd.php b/managed/CustomGroup_Event_Mailing_List.mgd.php new file mode 100644 index 0000000..21b80c5 --- /dev/null +++ b/managed/CustomGroup_Event_Mailing_List.mgd.php @@ -0,0 +1,128 @@ + 'CustomGroup_Event_Mailing_List', + 'entity' => 'CustomGroup', + 'cleanup' => 'unused', + 'update' => 'unmodified', + 'params' => [ + 'version' => 4, + 'values' => [ + 'name' => 'Event_Mailing_List', + 'title' => E::ts('Event Mailing List'), + 'extends' => 'Event', + 'style' => 'Inline', + 'collapse_display' => TRUE, + 'help_pre' => E::ts('These fields can be used to set up the events\'s behaviour as a mailing list.'), + 'help_post' => E::ts(''), + 'weight' => 4, + 'collapse_adv_display' => TRUE, + 'created_date' => '2025-02-10 12:56:55', + 'icon' => '', + ], + 'match' => ['name'], + ], + ], + [ + 'name' => 'CustomGroup_Event_Mailing_List_CustomField_Enable_mailing_list', + 'entity' => 'CustomField', + 'cleanup' => 'unused', + 'update' => 'unmodified', + 'params' => [ + 'version' => 4, + 'values' => [ + 'custom_group_id.name' => 'Event_Mailing_List', + 'name' => 'Enable_mailing_list', + 'label' => E::ts('Enable mailing list'), + 'data_type' => 'Boolean', + 'html_type' => 'Radio', + 'default_value' => '0', + 'is_searchable' => TRUE, + 'help_post' => E::ts('Enable the creation of a mailing list for this event.'), + 'text_length' => 255, + 'note_columns' => 60, + 'note_rows' => 4, + 'column_name' => 'enable_mailing_list_30', + ], + 'match' => [ + 'name', + 'custom_group_id', + ], + ], + ], + [ + 'name' => 'CustomGroup_Event_Mailing_List_CustomField_E_mail_address', + 'entity' => 'CustomField', + 'cleanup' => 'unused', + 'update' => 'unmodified', + 'params' => [ + 'version' => 4, + 'values' => [ + 'custom_group_id.name' => 'Event_Mailing_List', + 'name' => 'E_mail_address', + 'label' => E::ts('E-mail address'), + 'html_type' => 'Text', + 'help_post' => E::ts('The complete e-mail address of the mailing list.'), + 'text_length' => 255, + 'note_columns' => 60, + 'note_rows' => 4, + 'column_name' => 'e_mail_address_10', + ], + 'match' => [ + 'name', + 'custom_group_id', + ], + ], + ], + [ + 'name' => 'CustomGroup_Event_Mailing_List_CustomField_Subject_prefix', + 'entity' => 'CustomField', + 'cleanup' => 'unused', + 'update' => 'unmodified', + 'params' => [ + 'version' => 4, + 'values' => [ + 'custom_group_id.name' => 'Event_Mailing_List', + 'name' => 'Subject_prefix', + 'label' => E::ts('Subject prefix'), + 'html_type' => 'Text', + 'help_post' => E::ts('The subject of every email sent to this mailing list is prefixed with this.'), + 'text_length' => 255, + 'note_columns' => 60, + 'note_rows' => 4, + 'column_name' => 'subject_prefix_11', + ], + 'match' => [ + 'name', + 'custom_group_id', + ], + ], + ], + [ + 'name' => 'CustomGroup_Event_Mailing_List_CustomField_Can_be_reached_externally', + 'entity' => 'CustomField', + 'cleanup' => 'unused', + 'update' => 'unmodified', + 'params' => [ + 'version' => 4, + 'values' => [ + 'custom_group_id.name' => 'Event_Mailing_List', + 'name' => 'Can_be_reached_externally', + 'label' => E::ts('Can be reached externally'), + 'data_type' => 'Boolean', + 'html_type' => 'Radio', + 'default_value' => '0', + 'help_post' => E::ts('Should this mailing list also be open to senders who are not included in it?'), + 'text_length' => 255, + 'note_columns' => 60, + 'note_rows' => 4, + 'column_name' => 'can_be_reached_externally_12', + ], + 'match' => [ + 'name', + 'custom_group_id', + ], + ], + ], +]; diff --git a/managed/CustomGroup_Group_Mailing_List.mgd.php b/managed/CustomGroup_Group_Mailing_List.mgd.php new file mode 100644 index 0000000..b46be0d --- /dev/null +++ b/managed/CustomGroup_Group_Mailing_List.mgd.php @@ -0,0 +1,153 @@ + 'CustomGroup_Group_Mailing_List', + 'entity' => 'CustomGroup', + 'cleanup' => 'unused', + 'update' => 'unmodified', + 'params' => [ + 'version' => 4, + 'values' => [ + 'name' => 'Group_Mailing_List', + 'title' => E::ts('Group Mailing List'), + 'extends' => 'Group', + 'style' => 'Inline', + 'collapse_display' => TRUE, + 'help_pre' => E::ts('These fields can be used to set up the group\'s behaviour as a mailing list.'), + 'help_post' => E::ts(''), + 'weight' => 5, + 'collapse_adv_display' => TRUE, + 'created_date' => '2025-02-10 12:56:55', + 'icon' => '', + ], + 'match' => ['name'], + ], + ], + [ + 'name' => 'CustomGroup_Group_Mailing_List_CustomField_Enable_mailing_list', + 'entity' => 'CustomField', + 'cleanup' => 'unused', + 'update' => 'unmodified', + 'params' => [ + 'version' => 4, + 'values' => [ + 'custom_group_id.name' => 'Group_Mailing_List', + 'name' => 'Enable_mailing_list', + 'label' => E::ts('Enable mailing list'), + 'data_type' => 'Boolean', + 'html_type' => 'Radio', + 'default_value' => '0', + 'is_searchable' => TRUE, + 'help_post' => E::ts('Enable the creation of a mailing list for this group.'), + 'text_length' => 255, + 'note_columns' => 60, + 'note_rows' => 4, + 'column_name' => 'enable_mailing_list_31', + ], + 'match' => [ + 'name', + 'custom_group_id', + ], + ], + ], + [ + 'name' => 'CustomGroup_Group_Mailing_List_CustomField_E_mail_address', + 'entity' => 'CustomField', + 'cleanup' => 'unused', + 'update' => 'unmodified', + 'params' => [ + 'version' => 4, + 'values' => [ + 'custom_group_id.name' => 'Group_Mailing_List', + 'name' => 'E_mail_address', + 'label' => E::ts('E-mail address'), + 'html_type' => 'Text', + 'help_post' => E::ts('The complete e-mail address of the mailing list.'), + 'text_length' => 255, + 'note_columns' => 60, + 'note_rows' => 4, + 'column_name' => 'e_mail_address_10', + ], + 'match' => [ + 'name', + 'custom_group_id', + ], + ], + ], + [ + 'name' => 'CustomGroup_Group_Mailing_List_CustomField_Active_Directory_SID', + 'entity' => 'CustomField', + 'cleanup' => 'unused', + 'update' => 'unmodified', + 'params' => [ + 'version' => 4, + 'values' => [ + 'custom_group_id.name' => 'Group_Mailing_List', + 'name' => 'Active_Directory_SID', + 'label' => E::ts('Active Directory SID'), + 'html_type' => 'Text', + 'help_post' => E::ts('The SID of the group in the Active Directory.'), + 'is_view' => TRUE, + 'text_length' => 36, + 'note_columns' => 60, + 'note_rows' => 4, + 'column_name' => 'active_directory_SID_11', + ], + 'match' => [ + 'name', + 'custom_group_id', + ], + ], + ], + [ + 'name' => 'CustomGroup_Group_Mailing_List_CustomField_Can_be_reached_externally', + 'entity' => 'CustomField', + 'cleanup' => 'unused', + 'update' => 'unmodified', + 'params' => [ + 'version' => 4, + 'values' => [ + 'custom_group_id.name' => 'Group_Mailing_List', + 'name' => 'Can_be_reached_externally', + 'label' => E::ts('Can be reached externally'), + 'data_type' => 'Boolean', + 'html_type' => 'Radio', + 'default_value' => '0', + 'help_post' => E::ts('Should this mailing list also be open to senders who are not included in it?'), + 'text_length' => 255, + 'note_columns' => 60, + 'note_rows' => 4, + 'column_name' => 'can_be_reached_externally_12', + ], + 'match' => [ + 'name', + 'custom_group_id', + ], + ], + ], + [ + 'name' => 'CustomGroup_Group_Mailing_List_CustomField_Subject_prefix', + 'entity' => 'CustomField', + 'cleanup' => 'unused', + 'update' => 'unmodified', + 'params' => [ + 'version' => 4, + 'values' => [ + 'custom_group_id.name' => 'Group_Mailing_List', + 'name' => 'Subject_prefix', + 'label' => E::ts('Subject prefix'), + 'html_type' => 'Text', + 'help_post' => E::ts('The subject of every email sent to this mailing list is prefixed with this.'), + 'text_length' => 255, + 'note_columns' => 60, + 'note_rows' => 4, + 'column_name' => 'subject_prefix_13', + ], + 'match' => [ + 'name', + 'custom_group_id', + ], + ], + ], +]; diff --git a/resources/location_types.php b/resources/location_types.php new file mode 100644 index 0000000..14bfac1 --- /dev/null +++ b/resources/location_types.php @@ -0,0 +1,24 @@ + 'Mailing_List_Address', + 'display_name' => E::ts('Mailing List Address'), + 'description' => E::ts('E-Mail address for mailing lists'), + 'is_default' => FALSE, + ], + [ + 'name' => 'AD_Mailing_List_Address', + 'display_name' => E::ts('AD Mailing List Address'), + 'description' => E::ts('E-Mail address for Active Directory mailing lists'), + 'is_default' => FALSE, + ], + [ + 'name' => 'Event_Mailing_List_Address', + 'display_name' => E::ts('Event Mailing List Address'), + 'description' => E::ts('E-Mail address for event mailing lists'), + 'is_default' => FALSE, + ], +]; diff --git a/templates/CRM/Mailinglistsync/Form/MailingListSettings.tpl b/templates/CRM/Mailinglistsync/Form/MailingListSettings.tpl new file mode 100644 index 0000000..06ccaa3 --- /dev/null +++ b/templates/CRM/Mailinglistsync/Form/MailingListSettings.tpl @@ -0,0 +1,66 @@ +
+
{$form[$EXTENSION_SHORT_NAME|cat:'_enable'].label}
+
{$form[$EXTENSION_SHORT_NAME|cat:'_enable'].html}
+
+
+
+
{$form[$EXTENSION_SHORT_NAME|cat:'_logging'].label}
+
{$form[$EXTENSION_SHORT_NAME|cat:'_logging'].html}
+
+
+ +

{ts}AD Mailing List Settings{/ts}

+ +
+
{$form[$EXTENSION_SHORT_NAME|cat:'_ad_contact_tags'].label}
+
{$form[$EXTENSION_SHORT_NAME|cat:'_ad_contact_tags'].html}
+
+
+ +

{ts}Event Mailing List Settings{/ts}

+ +
+
{$form[$EXTENSION_SHORT_NAME|cat:'_participant_status'].label}
+
{$form[$EXTENSION_SHORT_NAME|cat:'_participant_status'].html}
+
+
+ +

{ts}mlmmj Settings{/ts}

+ +
+
{$form[$EXTENSION_SHORT_NAME|cat:'_mlmmj_host'].label}
+
{$form[$EXTENSION_SHORT_NAME|cat:'_mlmmj_host'].html}
+
+
+
+
{$form[$EXTENSION_SHORT_NAME|cat:'_mlmmj_token'].label}
+
{$form[$EXTENSION_SHORT_NAME|cat:'_mlmmj_token'].html}
+
+
+
+
{$form[$EXTENSION_SHORT_NAME|cat:'_mlmmj_port'].label}
+
{$form[$EXTENSION_SHORT_NAME|cat:'_mlmmj_port'].html}
+
+
+ +

{ts}Dovecot Settings{/ts}

+ +
+
{$form[$EXTENSION_SHORT_NAME|cat:'_dovecot_host'].label}
+
{$form[$EXTENSION_SHORT_NAME|cat:'_dovecot_host'].html}
+
+
+
+
{$form[$EXTENSION_SHORT_NAME|cat:'_dovecot_token'].label}
+
{$form[$EXTENSION_SHORT_NAME|cat:'_dovecot_token'].html}
+
+
+
+
{$form[$EXTENSION_SHORT_NAME|cat:'_dovecot_port'].label}
+
{$form[$EXTENSION_SHORT_NAME|cat:'_dovecot_port'].html}
+
+
+ +
+ {include file="CRM/common/formButtons.tpl" location="bottom"} +
diff --git a/xml/Menu/mailinglist.xml b/xml/Menu/mailinglist.xml new file mode 100644 index 0000000..a5e3244 --- /dev/null +++ b/xml/Menu/mailinglist.xml @@ -0,0 +1,18 @@ + + + + civicrm/admin/settings/mailinglistsync-settings + CRM_Mailinglistsync_Form_MailingListSettings + Mailing List Synchronization Settings + Configure the Mailing List extension (de.propeace.mailinglistsync) + administer CiviCRM + System Settings + admin/option.png + + + civicrm/admin/settings/test + CRM_Mailinglistsync_Form_MailingListSettings + MailingListSettings + access CiviCRM + +