Newer
Older
<?php
require_once 'certificates.civix.php';
// phpcs:disable
use CRM_Certificates_ExtensionUtil as E;
Zilin Weng
committed
use Civi\Certificates\PDFCertificate;
use Civi\Token\TokenProcessor;
// phpcs:enable
/**
* Implements hook_civicrm_config().
*
* @link https://docs.civicrm.org/dev/en/latest/hooks/hook_civicrm_config/
*/
function certificates_civicrm_config(&$config): void {
_certificates_civix_civicrm_config($config);
}
/**
* Implements hook_civicrm_install().
*
* @link https://docs.civicrm.org/dev/en/latest/hooks/hook_civicrm_install
*/
function certificates_civicrm_install(): void {
_certificates_civix_civicrm_install();
}
/**
* Implements hook_civicrm_enable().
*
* @link https://docs.civicrm.org/dev/en/latest/hooks/hook_civicrm_enable
*/
function certificates_civicrm_enable(): void {
_certificates_civix_civicrm_enable();
}
/**
* Implements print certificate task.
*/
function certificates_civicrm_searchTasks($objectType, &$tasks) {
if ($objectType === 'event' && (CRM_Core_Permission::check('download participant certificates'))) {
$tasks[] = [
'title' => E::ts('Print Certificate'),
'class' => 'CRM_Certificates_Form_Task',
'result' => TRUE,
'is_single_mode' => TRUE,
'title_single_mode' => E::ts('Print Certificate'),
'name' => E::ts('Print Certificate'),
'key' => 'move',
'weight' => 130,
];
}
}
/**
* Define Certificates permissions
*/
function certificates_civicrm_permission(array &$permissions): void {
$prefix = 'Certificates: ';
$permissions['download participant certificates'] = [
'label' => $prefix . E::ts('Print all Participant Certificates'),
'description' => $prefix . E::ts('Allow user to print event attendance certificates for any event'),
];
$permissions['download activity certificates'] = [
'label' => $prefix . E::ts('Print all Activity Certificates'),
'description' => $prefix . E::ts('Allow user to print any "activity" certificate'),
];
$permissions['download membership certificates'] = [
'label' => $prefix . E::ts('Print all Membership Certificates'),
'description' => $prefix . E::ts('Allow user to print membership certificates for any contact'),
];
$permissions['download own certificate'] = [
'label' => E::ts('Print own Certificate'),
'description' => $prefix . E::ts('Allow user to print their own certificate'),
];
}
Zilin Weng
committed
function certificates_civicrm_pre($op, $objectName, $id, &$params) {
if ($op == 'edit' && $objectName == 'Participant') {
Zilin Weng
committed
try {
$statusId = CRM_Core_PseudoConstant::getKey('CRM_Event_BAO_Participant', 'status_id', 'Attended');
//get current participant status before data is changed
Zilin Weng
committed
$participant = \Civi\Api4\Participant::get(FALSE)
->addSelect('contact_id', 'status_id', 'id', 'event.Event_Certificate.event_certificate', 'event.id', 'event.title')
Zilin Weng
committed
->addJoin('Event AS event', 'LEFT', ['event_id', '=', 'event.id'])
->addWhere('id', '=', $id)
Zilin Weng
committed
->execute()->first();
$contactID = $participant['contact_id'];
Zilin Weng
committed
// checks if participant status_id is now status id for Attended --> then send email
if ($participant['status_id'] !== $statusId && $params['status_id'] == $statusId) {
[$toDisplayName, $toEmail] = CRM_Contact_BAO_Contact_Location::getEmailDetails($contactID);
Zilin Weng
committed
$participantInfo = [
'id' => $participant['id'],
'contact_id' => $contactID,
'name' => $toDisplayName,
'email' => $toEmail,
'event_id' => $participant['event.id'],
'event_title' => $participant['event.title'],
'certificate_id' => $participant['event.Event_Certificate.event_certificate']
Zilin Weng
committed
];
getEmailContent($participantInfo);
}
} catch (Exception $e) {
echo 'Message: ' . $e->getMessage();
}
}
}
Zilin Weng
committed
* Sends an email with a certificate attachment.
Zilin Weng
committed
function getEmailContent($participant) {
$mailAttachments = [];
try {
// searches for the certificate, if none found will fallback to default
$messageTemplateID = $participant['certificate_id'] ?? \Civi::settings()->get('certificates_event_defaultmessagetemplateid');
Zilin Weng
committed
if (empty($messageTemplateID)) {
\Civi::log()->error('Event attendance certificate has no message template ID set!');
return;
}
Zilin Weng
committed
// query to get the html of the message template given the message template id
->addSelect('msg_html')
->addWhere('id', '=', $messageTemplateID)
->addSelect('msg_subject', 'msg_html')
->addWhere('msg_title', '=', 'Certificate Email')
if (empty($emailTemplate)) {
// fallback to default email message template if 'Certificate Email' is not found
$defaultEmailTemplateID = \Civi::settings()->get('certificates_event_emailmessagetemplateid');
if (empty($defaultEmailTemplateID)) {
\Civi::log()->error('Default email template ID is not configured.');
return;
}
->addSelect('msg_subject', 'msg_html')
->addWhere('id', '=', $defaultEmailTemplateID)
->setLimit(1)
->execute()
->first();
if (!$emailTemplate) {
\Civi::log()->error("Fallback email message template ID $defaultEmailTemplateID not found.");
return;
}
$tokenProcessor = new TokenProcessor(\Civi::dispatcher(), [
'controller' => __CLASS__,
'smarty' => FALSE,
'schema' => ['contactId', 'participantId'] // change depending on what other fields are present in template
$tokenProcessor->addMessage('body_html', $messageTemplate['msg_html'], 'text/html');
$tokenProcessor->addRow(['contactId' => $participant['contact_id'], 'participantId' => $participant['id']]);
$tokenProcessor->evaluate();
$tokenProcessorEmail = new TokenProcessor(\Civi::dispatcher(), [
'controller' => __CLASS__,
'smarty' => FALSE,
'schema' => ['contactId', 'participantId', 'eventId'] // change depending on what other fields are present in template
$tokenProcessorEmail->addMessage('body_html', $emailTemplate['msg_html'], 'text/html');
$tokenProcessorEmail->addRow(['contactId' => $participant['contact_id'], 'participantId' => $participant['id'], 'eventId' => $participant['event_id']]);
$tokenProcessorEmail->evaluate();
} catch (TypeError $e) {
\Civi::log()->error('certificates: TypeError parsing tokens. Error: ' . $e->getMessage());
return;
}
$rows = $tokenProcessor->getRows();
$html = [];
foreach ($rows as $row) {
$html[] = $row->render('body_html');
}
$html = $html[0];
$rowsEmail = $tokenProcessorEmail->getRows();
$htmlEmail = [];
foreach ($rowsEmail as $rowEmail) {
$htmlEmail[] = $rowEmail->render('body_html');
}
$htmlEmail = $htmlEmail[0];
$filename = $participant['name'] . '_' . $participant['event_id'] . '_attendance_certificate_' . $participant['event_title'];
$filename = \CRM_Utils_File::makeFilenameWithUnicode($filename, '_', 200) . '.pdf';
$fromEmail = current(CRM_Core_BAO_Domain::getNameAndEmail(FALSE, TRUE)); // takes the first set email in CiviMail
array_push($mailAttachments, CRM_Utils_Mail::appendPDF($filename, $html));
$certificateEmail = [
'from' => $fromEmail,
'toName' => $participant['name'],
'toEmail' => $participant['email'],
'html' => $htmlEmail,
];
$certificateEmail['attachments'] = $mailAttachments;
$act = \Civi\Api4\Activity::create(FALSE)
->addValue('source_record_id', $participant['id'])
->addValue('source_contact_id', $participant['contact_id'])
->addValue('subject', 'Attendance Certificate Issued')
->addValue('activity_date_time', date('Y-m-d H:i:s'))
->addValue('status_id', 2)
->addValue('activity_type_id:name', 'Certificate Issued')
->execute();
Zilin Weng
committed
} catch (Exception $e) {
echo 'Message: ' . $e->getMessage();
}