Skip to content
Snippets Groups Projects
certificates.php 8.26 KiB
Newer Older
  • Learn to ignore specific revisions
  • mattwire's avatar
    mattwire committed
    <?php
    
    require_once 'certificates.civix.php';
    // phpcs:disable
    use CRM_Certificates_ExtensionUtil as E;
    
    use Civi\Token\TokenProcessor;
    
    
    mattwire's avatar
    mattwire committed
    // 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'),
      ];
    }
    
    
    function certificates_civicrm_pre($op, $objectName, $id, &$params) {
    
      if ($op == 'edit' && $objectName == 'Participant') {
    
    Edselopez's avatar
    Edselopez committed
          $statusId = CRM_Core_PseudoConstant::getKey('CRM_Event_BAO_Participant', 'status_id', 'Attended');
    
          //get current participant status before data is changed
    
            ->addSelect('contact_id', 'status_id', 'id', 'event.Event_Certificate.event_certificate', 'event.id', 'event.title')
    
            ->addJoin('Event AS event', 'LEFT', ['event_id', '=', 'event.id'])
    
            ->addWhere('id', '=', $id)
    
          $contactID = $participant['contact_id'];
    
    Edselopez's avatar
    Edselopez committed
    
    
          // checks if participant status_id is now status id for Attended --> then send email
    
    Edselopez's avatar
    Edselopez committed
          if ($participant['status_id'] !== $statusId && $params['status_id'] == $statusId) {
    
    Monish Deb's avatar
    Monish Deb committed
            [$toDisplayName, $toEmail] = CRM_Contact_BAO_Contact_Location::getEmailDetails($contactID);
    
    Monish Deb's avatar
    Monish Deb committed
              'id' => $participant['id'],
              'contact_id' => $contactID,
              'name' => $toDisplayName,
              'email' => $toEmail,
    
    Edselopez's avatar
    Edselopez committed
              'event_id' => $participant['event.id'],
              'event_title' => $participant['event.title'],
              'certificate_id' => $participant['event.Event_Certificate.event_certificate']
    
            ];
    
            getEmailContent($participantInfo);
          }
    
        } catch (Exception $e) {
          echo 'Message: ' . $e->getMessage();
        }
      }
    }
    
    
    function getEmailContent($participant) {
      $mailAttachments = [];
    
      try {
        // searches for the certificate, if none found will fallback to default
    
    Monish Deb's avatar
    Monish Deb committed
        $messageTemplateID = $participant['certificate_id'] ?? \Civi::settings()->get('certificates_event_defaultmessagetemplateid');
    
        if (empty($messageTemplateID)) {
          \Civi::log()->error('Event attendance certificate has no message template ID set!');
          return;
        }
    
        // query to get the html of the message template given the message template id
    
    Monish Deb's avatar
    Monish Deb committed
        $messageTemplate = \Civi\Api4\MessageTemplate::get(FALSE)
    
          ->addSelect('msg_html')
          ->addWhere('id', '=', $messageTemplateID)
    
    Monish Deb's avatar
    Monish Deb committed
          ->execute()
          ->first();
    
        // add default for here
    
    Monish Deb's avatar
    Monish Deb committed
        $emailTemplate = \Civi\Api4\MessageTemplate::get(FALSE)
    
          ->addSelect('msg_subject', 'msg_html')
    
          ->addWhere('msg_title', '=', 'Certificate Email')
    
    Monish Deb's avatar
    Monish Deb committed
          ->execute()
          ->first();
    
    
        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;
          }
    
    
    Monish Deb's avatar
    Monish Deb committed
          $emailTemplate = \Civi\Api4\MessageTemplate::get(FALSE)
    
            ->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;
          }
    
    Monish Deb's avatar
    Monish Deb committed
        try {
    
          $tokenProcessor = new TokenProcessor(\Civi::dispatcher(), [
            'controller' => __CLASS__,
            'smarty' => FALSE,
    
            'schema' => ['contactId', 'participantId'] // change depending on what other fields are present in template
    
    Monish Deb's avatar
    Monish Deb committed
          $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
    
    Monish Deb's avatar
    Monish Deb committed
          $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];
    
    
    Edselopez's avatar
    Edselopez committed
        $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'],
    
    Monish Deb's avatar
    Monish Deb committed
          'subject' => $emailTemplate['msg_subject'],
    
    Monish Deb's avatar
    Monish Deb committed
          'contactId' => $participant['contact_id'],
    
        ];
    
        $certificateEmail['attachments'] = $mailAttachments;
    
    Monish Deb's avatar
    Monish Deb committed
        
        $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's avatar
    Zilin Weng committed
        CRM_Utils_Mail::send($certificateEmail);
    
    Monish Deb's avatar
    Monish Deb committed
        
    
      } catch (Exception $e) {
        echo 'Message: ' . $e->getMessage();
      }