You are here

course_certificate.module in Course 3.x

File

modules/course_certificate/course_certificate.module
View source
<?php

use Drupal\Core\Link;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\course\Entity\Course;

/**
 * Implements hook_course_outline_completion_links_alter().
 *
 * Add a download certificate link.
 */
function course_certificate_course_outline_completion_links_alter(&$links, Course $course, AccountInterface $account) {
  if ($course
    ->access('certificate', $account)) {
    $links['certificate'] = Link::createFromRoute(t('Download certificate'), 'certificate.course', [
      'course' => $course
        ->id(),
    ], [
      'title' => t('Download a PDF of your certificate.'),
    ]);
  }
}

/**
 * Implements hook_entity_access().
 *
 * Control access to a certificate on this course.
 *
 * @param EntityInterface $entity
 * @param type $operation
 * @param AccountInterface $account
 *
 * @return type
 */
function course_certificate_entity_access(EntityInterface $entity, $operation, AccountInterface $user) {
  $currentUser = Drupal::currentUser();
  $requestedUser = $user ?? $currentUser;
  $admin = $currentUser
    ->hasPermission('administer certificates');
  $view_all = $currentUser
    ->hasPermission('view all user certificates');
  if ($entity
    ->getEntityTypeId() == 'course' && $operation == 'certificate') {
    $has_object = FALSE;
    $access_result = AccessResult::neutral();

    // Does the course have a certificate object?
    foreach ($entity
      ->getObjects() as $courseObject) {
      if ($courseObject
        ->getComponent() == 'certificate') {
        $has_object = TRUE;
        break;
      }
    }
    if (!$has_object) {
      $access_result = AccessResult::forbidden('No certificate object provided.');
    }

    // Are they enrolled?
    $enrollments = Drupal::entityTypeManager()
      ->getStorage('course_enrollment')
      ->loadByProperties([
      'uid' => $requestedUser
        ->id(),
      'cid' => $entity
        ->id(),
    ]);
    if (empty($enrollments)) {
      $access_result = AccessResult::forbidden('User is not enrolled');
    }
    else {
      $enrollment = reset($enrollments);

      // Are they an admin or have they completed the course?
      if ($admin || $view_all || $enrollment
        ->isComplete()) {
        $access_result = AccessResult::allowed();
      }
    }
    return $access_result;
  }
}