de.propeace.mailinglistsync/Civi/Mailinglistsync/MailingListRecipient.php
2025-03-04 11:15:09 +01:00

335 lines
9.2 KiB
PHP

<?php
namespace Civi\Mailinglistsync;
use Civi\Mailinglistsync\Exceptions\MailinglistException;
use CRM_Mailinglistsync_ExtensionUtil as E;
class MailingListRecipient {
protected int $contactId;
protected string $firstName;
protected string $lastName;
protected string $email;
protected string $sid;
/**
* Data to be updated. Use the `save()` method to apply the update.
*
* @var array
*/
private $updateData;
/**
* Constructor.
*
* @param int $contact_id
* @param string $first_name
* @param string $last_name
* @param string $email
* @param string|null $sid
*/
public function __construct(
int $contact_id,
string $first_name,
string $last_name,
string $email,
string $sid = NULL,
) {
$this->contactId = $contact_id;
$this->firstName = $first_name;
$this->lastName = $last_name;
$this->email = $email;
$this->sid = $sid;
$this->updateData = [];
}
// /**
// * Get or create a contact.
// *
// * @param string $fistName
// * @param string $lastName
// * @param string $email
// * @param string $locationType The location type of the email address
// *
// * @return \Civi\Mailinglistsync\MailingListRecipient
// * @throws \Civi\Mailinglistsync\Exceptions\MailinglistException
// */
// public static function getOrCreate(
// string $fistName,
// string $lastName,
// string $email,
// string $locationType,
// ): self {
//
// // Verify location type
// $locationTypes = [
// GroupMailingList::LOCATION_TYPE,
// ADGroupMailingList::LOCATION_TYPE,
// EventMailingList::LOCATION_TYPE,
// ];
// if (!in_array($locationType, $locationTypes)) {
// throw new MailinglistException(
// E::ts('Invalid location type'),
// MailinglistException::ERROR_CODE_INVALID_LOCATION_TYPE,
// );
// }
//
// // Try to get contact
// try {
// $contact = \Civi\Api4\Contact::get()
// ->addSelect('*', 'location_type.*')
// ->addJoin('Email AS email', 'LEFT', ['id', '=', 'email.contact_id'])
// ->addJoin('LocationType AS location_type', 'LEFT', ['email.location_type_id', '=', 'location_type.id'])
// ->addWhere('email.email', '=', $email)
// ->addWhere('location_type.name', '=', $locationType)
// ->execute()
// ->first();
// }
// catch (\Exception $e) {
// throw new MailinglistException(
// E::ts('Failed to get contact'),
// MailinglistException::ERROR_CODE_GET_CONTACT_FAILED,
// );
// }
//
// // Create contact if it does not exist
// if (empty($contact)) {
// try {
// $contact = \Civi\Api4\Contact::create(FALSE)
// ->addValue('contact_type', 'Individual')
// ->addValue('first_name', $fistName)
// ->addValue('last_name', $lastName)
// ->setChain([
// 'Email.create',
// \Civi\Api4\Email::create(FALSE)
// ->addValue('contact_id', '$id')
// ->addValue('email', $email)
// ->addValue('location_type_id.name', $locationType),
// ])
// ->execute()
// ->first();
// array_pop($contact['Email.create']);
// }
// catch (\Exception $e) {
// throw new MailinglistException(
// E::ts('Failed to create contact'),
// MailinglistException::ERROR_CODE_CREATE_CONTACT_FAILED,
// );
// }
// }
//
// return new static(contact: $contact, email: $email);
// }
/**
* Create a new contact and return the recipient.
*
* @param string $firstName
* @param string $lastName
* @param string $email
* @param string $sid
*
* @return \Civi\Mailinglistsync\MailingListRecipient
* @throws \Civi\Mailinglistsync\Exceptions\MailinglistException
*/
public static function createContact(
string $firstName,
string $lastName,
string $email,
string $sid,
): self {
// Try to create a new contact
try {
$contact = \Civi\Api4\Contact::create(FALSE)
->addValue('contact_type', 'Individual')
->addValue('first_name', $firstName)
->addValue('last_name', $lastName)
->setChain([
'Email.create',
\Civi\Api4\Email::create(FALSE)
->addValue('email', $email)
->addValue('location_type_id.name', 'Main'),
])
->execute();
}
catch (\Exception $e) {
throw new MailinglistException(
E::ts("Failed to create contact: {$e->getMessage()}"),
MailinglistException::ERROR_CODE_CREATE_CONTACT_FAILED,
);
}
return new static(
contact_id: $contact['id'],
first_name: $firstName,
last_name: $lastName,
email: $email,
sid: $sid,
);
}
/**
* Get a list of group mailing lists the contact is subscribed to.
*
* @return array
* @throws \Civi\Mailinglistsync\Exceptions\MailinglistException
*/
public function getMailingLists(): array {
$mailingLists = [];
try {
$groups = \Civi\Api4\GroupContact::get()
->addSelect('group_id')
->addWhere('contact_id', '=', $this->getContactId())
->addWhere('status', '=', 'Added')
->addWhere(GroupMailingList::CUSTOM_GROUP_NAME . '.Enable_mailing_list', '=', TRUE)
->addWhere(GroupMailingList::CUSTOM_GROUP_NAME . '.Active_Directory_SID', 'IS EMPTY')
->execute()
->getArrayCopy();
} catch (\Exception $e) {
throw new MailinglistException(
E::ts('Failed to get group mailing lists'),
MailinglistException::ERROR_CODE_GET_GROUP_MAILING_LISTS_FAILED,
);
}
foreach ($groups as $group) {
$mailingList = new GroupMailingList($group['group_id']);
if ($mailingList->isADGroup()) {
$mailingList = new ADGroupMailingList($group['group_id']); ;
}
$mailingLists[] = $mailingList;
}
return $mailingLists;
}
/**
* Get a list of AD group mailing lists the contact is subscribed to.
*
* @return array
* @throws \Civi\Mailinglistsync\Exceptions\MailinglistException
*/
public function getAdMailingLists(): array {
$mailingLists = [];
try {
$groups = \Civi\Api4\GroupContact::get()
->addSelect('group_id')
->addWhere('contact_id', '=', $this->getContactId())
->addWhere('status', '=', 'Added')
->addWhere(GroupMailingList::CUSTOM_GROUP_NAME . '.Enable_mailing_list', '=', TRUE)
->addWhere(GroupMailingList::CUSTOM_GROUP_NAME . '.Active_Directory_SID', 'IS NOT EMPTY')
->execute()
->getArrayCopy();
} catch (\Exception $e) {
throw new MailinglistException(
E::ts('Failed to get AD group mailing lists'),
MailinglistException::ERROR_CODE_GET_AD_GROUP_MAILING_LISTS_FAILED,
);
}
foreach ($groups as $group) {
$mailingList = new GroupMailingList($group['group_id']);
if ($mailingList->isADGroup()) {
$mailingList = new ADGroupMailingList($group['group_id']); ;
}
$mailingLists[] = $mailingList;
}
return $mailingLists;
}
/**
* @throws \Civi\Mailinglistsync\Exceptions\MailinglistException
*/
public function getEventMailingLists(): array {
$mailingLists = [];
try {
$groups = \Civi\Api4\Participant::get()
->addSelect('event_id')
->addWhere('contact_id', '=', $this->getContactId())
->addWhere('status_id', 'IN', EventMailingList::getEnabledParticipantStatus())
->addWhere(GroupMailingList::CUSTOM_GROUP_NAME . '.Enable_mailing_list', '=', TRUE)
->execute()
->getArrayCopy();
}
catch (\Exception $e) {
throw new MailinglistException(
E::ts('Failed to get event mailing lists'),
MailinglistException::ERROR_CODE_GET_EVENT_MAILING_LISTS_FAILED,
);
}
foreach ($groups as $group) {
$mailingList = new EventMailingList($group['group_id']);
$mailingLists[] = $mailingList;
}
return $mailingLists;
}
public function getContactId(): int {
return $this->contactId;
}
public function getFirstName(): string {
return $this->firstName;
}
public function getLastName(): string {
return $this->lastName;
}
public function getEmail(): string {
return $this->email;
}
public function getSid(): string {
return $this->sid;
}
public function setFirstName(string $firstName): void {
$this->updateData += ['first_name' => $firstName];
}
public function setLastName(string $lastName): void {
$this->updateData += ['last_name' => $lastName];
}
public function setEmail(string $email): void {
$this->updateData += ['email' => $email];
}
public function setSid(string $sid): void {
$this->updateData += ['sid' => $sid];
}
/**
* Save the changes marked using the setter methods.
*
* @throws \Civi\Mailinglistsync\Exceptions\MailinglistException
*/
public function save(): void {
if (empty($this->updateData)) {
return;
}
try {
\Civi\Api4\Contact::update()
->setValues($this->updateData)
->addWhere('id', '=', $this->getContactId())
->execute();
} catch (\Exception $e) {
throw new MailinglistException(
E::ts("Failed to update contact: {$e->getMessage()}"),
MailinglistException::ERROR_CODE_UPDATE_ENTITY_FAILED,
);
}
}
}