SkillingAccessChecker.php 118 KB
Newer Older
mathieso's avatar
mathieso committed
1
<?php
2

mathieso's avatar
mathieso committed
3 4
namespace Drupal\skilling\Access;

5
use Drupal\block\BlockInterface;
6
use Drupal\Component\Utility\Html;
mathieso's avatar
mathieso committed
7 8
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Config\ConfigFactory;
9
use Drupal\Core\Database\Query\AlterableInterface;
10
use Drupal\Core\Entity\EntityInterface;
mathieso's avatar
mathieso committed
11 12
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
13
use Drupal\Core\Field\FieldItemListInterface;
mathieso's avatar
mathieso committed
14 15
use Drupal\Core\Messenger\MessengerInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
16
use Drupal\file\Entity\File;
mathieso's avatar
mathieso committed
17
use Drupal\node\NodeInterface;
18
use Drupal\paragraphs\ParagraphInterface;
19
use Drupal\skilling\Exception\SkillingException;
20
use Drupal\skilling\Exception\SkillingInvalidValueException;
mathieso's avatar
mathieso committed
21 22 23
use Drupal\skilling\Exception\SkillingValueMissingException;
use Drupal\skilling\SkillingConstants;
use Drupal\skilling\SkillingCurrentUser;
24
use Drupal\skilling\SkillingParser\SkillingParser;
mathieso's avatar
mathieso committed
25 26 27
use Drupal\skilling\SkillingUser;
use Drupal\skilling\SkillingUserFactory;
use Drupal\skilling\Utilities as SkillingUtilities;
mathieso's avatar
mathieso committed
28
use Drupal\skilling\SkillingClass\SkillingCurrentClass;
mathieso's avatar
mathieso committed
29
use Drupal\taxonomy\Entity\Term;
mathieso's avatar
mathieso committed
30 31

/**
32
 * A service to check the current user's access to entities, blocks, and fields.
mathieso's avatar
mathieso committed
33
 *
34 35 36
 * Access checks are sent through this class, so it's important to get it right.
 *
 * @package Drupal\skilling
mathieso's avatar
mathieso committed
37
 */
38
class SkillingAccessChecker {
mathieso's avatar
mathieso committed
39
  use StringTranslationTrait;
mathieso's avatar
mathieso committed
40
  /**
mathieso's avatar
mathieso committed
41 42
   * The entity type manager service.
   *
mathieso's avatar
mathieso committed
43 44 45 46
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

mathieso's avatar
mathieso committed
47 48 49 50 51
  /**
   * The current user service.
   *
   * @var \Drupal\skilling\SkillingCurrentUser
   */
mathieso's avatar
mathieso committed
52 53
  protected $currentUser;

mathieso's avatar
mathieso committed
54 55 56
  /**
   * The current class service.
   *
57 58 59
   * If the current user is enrolled in more than one class, s/he chooses
   * one of them to be the context for the site.
   *
mathieso's avatar
mathieso committed
60
   * @var SkillingCurrentClass
mathieso's avatar
mathieso committed
61
   */
mathieso's avatar
mathieso committed
62 63
  protected $currentClass;

mathieso's avatar
mathieso committed
64 65 66
  /**
   * Service to check relationships between users.
   *
67
   * @var \Drupal\skilling\Access\SkillingCheckUserRelationships
mathieso's avatar
mathieso committed
68
   */
mathieso's avatar
mathieso committed
69 70
  protected $checkUserRelationshipsService;

mathieso's avatar
mathieso committed
71 72 73 74 75
  /**
   * Configuration factory service.
   *
   * @var \Drupal\Core\Config\ConfigFactory
   */
mathieso's avatar
mathieso committed
76 77
  protected $configFactory;

mathieso's avatar
mathieso committed
78 79 80 81 82
  /**
   * Class to make Skilling user objects.
   *
   * @var \Drupal\skilling\SkillingUserFactory
   */
mathieso's avatar
mathieso committed
83 84
  protected $skillingUserFactory;

mathieso's avatar
mathieso committed
85 86 87 88 89
  /**
   * The Skilling utilities service.
   *
   * @var \Drupal\skilling\Utilities
   */
mathieso's avatar
mathieso committed
90 91
  protected $skillingUtilities;

mathieso's avatar
mathieso committed
92 93 94
  /**
   * The Skilling parser service.
   *
95
   * @var \Drupal\skilling\SkillingParser\SkillingParser
mathieso's avatar
mathieso committed
96 97 98
   */
  protected $parser;

mathieso's avatar
mathieso committed
99
  /**
mathieso's avatar
mathieso committed
100
   * Messenger service.
mathieso's avatar
mathieso committed
101 102 103 104 105
   *
   * @var \Drupal\Core\Messenger\MessengerInterface
   */
  protected $messenger;

106 107 108 109 110 111 112
  /**
   * The field access special case checker service.
   *
   * @var \Drupal\skilling\Access\FieldAccessSpecialCaseChecker
   */
  protected $fieldAccessSpecialCaseChecker;

mathieso's avatar
mathieso committed
113 114 115 116 117 118 119
  /**
   * Make a SkillingAccessChecker object.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeTanager
   *   The entity type manager service.
   * @param \Drupal\skilling\SkillingCurrentUser $currentUser
   *   The current user service.
mathieso's avatar
mathieso committed
120
   * @param SkillingCurrentClass $currentClass
mathieso's avatar
mathieso committed
121 122 123 124 125 126 127 128 129
   *   The current class service.
   * @param \Drupal\skilling\Access\SkillingCheckUserRelationships $checkUserRelationshipsService
   *   Service to check relationships between users.
   * @param \Drupal\Core\Config\ConfigFactory $configFactory
   *   Configuration factory service.
   * @param \Drupal\skilling\SkillingUserFactory $skillingUserFactory
   *   Class to make Skilling user objects.
   * @param \Drupal\skilling\Utilities $utilities
   *   The Skilling utilities service.
130
   * @param \Drupal\skilling\SkillingParser\SkillingParser $parser
131
   *   The Skilling parser service.
mathieso's avatar
mathieso committed
132 133
   * @param \Drupal\Core\Messenger\MessengerInterface $messenger
   *   The messenger service.
134 135 136 137 138
   * @param \Drupal\skilling\Access\FieldAccessSpecialCaseChecker $fieldAccessSpecialCaseChecker
   *   The field access special case checker service.
   *
   * @throws \Drupal\skilling\Exception\SkillingInvalidValueException
   * @throws \Drupal\skilling\Exception\SkillingValueMissingException
mathieso's avatar
mathieso committed
139
   */
140 141 142
  public function __construct(
    EntityTypeManagerInterface $entityTypeTanager,
    SkillingCurrentUser $currentUser,
mathieso's avatar
mathieso committed
143
    SkillingCurrentClass $currentClass,
144 145 146 147 148 149 150 151
    SkillingCheckUserRelationships $checkUserRelationshipsService,
    ConfigFactory $configFactory,
    SkillingUserFactory $skillingUserFactory,
    SkillingUtilities $utilities,
    SkillingParser $parser,
    MessengerInterface $messenger,
    FieldAccessSpecialCaseChecker $fieldAccessSpecialCaseChecker
  ) {
mathieso's avatar
mathieso committed
152 153 154 155 156 157 158
    $this->entityTypeManager = $entityTypeTanager;
    $this->currentUser = $currentUser;
    $this->currentClass = $currentClass;
    $this->checkUserRelationshipsService = $checkUserRelationshipsService;
    $this->configFactory = $configFactory;
    $this->skillingUserFactory = $skillingUserFactory;
    $this->skillingUtilities = $utilities;
mathieso's avatar
mathieso committed
159
    $this->parser = $parser;
mathieso's avatar
mathieso committed
160
    $this->messenger = $messenger;
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
    $this->fieldAccessSpecialCaseChecker = $fieldAccessSpecialCaseChecker;
    $this->defineSpecialFieldAccess();
  }

  /**
   * Define special cases for field access.
   *
   * @throws \Drupal\skilling\Exception\SkillingInvalidValueException
   * @throws \Drupal\skilling\Exception\SkillingValueMissingException
   */
  protected function defineSpecialFieldAccess() {
    $specialCases = [
      [
        'field_name' => SkillingConstants::FIELD_WHERE_REFERENCED,
        'operation' => SkillingConstants::VIEW_OPERATION,
        'path' => '/exercises',
        'role' => SkillingConstants::SITE_ROLE_STUDENT,
        'http_method' => 'get',
        'allowed' => TRUE,
      ],
181 182 183 184

      [
        'field_name' => SkillingConstants::FIELD_ORDER_IN_BOOK,
        'operation' => SkillingConstants::VIEW_OPERATION,
185 186 187 188 189 190 191 192 193 194 195 196
        'paths' => [
          '/exercises',
          '/lessons',
        ],
        'roles' => [
          SkillingConstants::SITE_ROLE_ANONYMOUS,
          SkillingConstants::SITE_ROLE_STUDENT,
          SkillingConstants::SITE_ROLE_AUTHOR,
          SkillingConstants::SITE_ROLE_INSTRUCTOR,
          SkillingConstants::SITE_ROLE_REVIEWER,
          SkillingConstants::SITE_ROLE_GRADER,
        ],
197 198 199
        'http_method' => 'get',
        'allowed' => TRUE,
      ],
mathieso's avatar
mathieso committed
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215

      [
        'field_name' => SkillingConstants::FIELD_ORDER_IN_BOOK,
        'operation' => SkillingConstants::VIEW_OPERATION,
        'paths' => [
          '/admin/skilling/reflection-notes',
        ],
        'roles' => [
          SkillingConstants::SITE_ROLE_AUTHOR,
          SkillingConstants::SITE_ROLE_INSTRUCTOR,
          SkillingConstants::SITE_ROLE_REVIEWER,
        ],
        'http_method' => 'get',
        'allowed' => TRUE,
      ],

mathieso's avatar
mathieso committed
216 217 218
      [
        'field_name' => SkillingConstants::FIELD_ORDER_IN_BOOK,
        'operation' => SkillingConstants::VIEW_OPERATION,
mathieso's avatar
mathieso committed
219
        'path' => '/skilling/reflect-notes',
mathieso's avatar
mathieso committed
220 221 222 223
        'role' => SkillingConstants::SITE_ROLE_STUDENT,
        'http_method' => 'get',
        'allowed' => TRUE,
      ],
224 225
    ];
    $this->fieldAccessSpecialCaseChecker->defineAllowedSpecialCases($specialCases);
mathieso's avatar
mathieso committed
226 227
  }

228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
  /**
   * Check user access to an entity.
   *
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   The entity.
   * @param string $operation
   *   Operation on the entity.
   *
   * @return \Drupal\Core\Access\AccessResultAllowed|\Drupal\Core\Access\AccessResultForbidden|\Drupal\Core\Access\AccessResultNeutral
   *   Result of check
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   * @throws \Drupal\skilling\Exception\SkillingException
   * @throws \Drupal\skilling\Exception\SkillingInvalidValueException
   */
  public function getEntityAccess(EntityInterface $entity, $operation) {
    $entityType = $entity->getEntityTypeId();
    if ($entityType === 'user') {
      // Make a Skilling User to pass to the access checking service.
      $userBeingAccessed = $this->skillingUserFactory->makeSkillingUser($entity->id());
      // Get the AccessResult for the user entity.
      $result = $this->getUserEntityAccess($userBeingAccessed, $operation);
      return $result;
    }
    elseif ($entityType === 'node') {
      // Make a new var of the right type.
      /** @var \Drupal\node\NodeInterface $node */
      $node = $entity;
      $result = $this->getNodeAccess($node, $operation);
      return $result;
    }
    elseif ($entityType === 'paragraph') {
      // Make a new var of the right type.
      /** @var \Drupal\paragraphs\ParagraphInterface $paragraph */
      $paragraph = $entity;
      $result = $this->getParagraphAccess($paragraph, $operation);
      return $result;
    }
267
    elseif ($entityType == 'file') {
mathieso's avatar
mathieso committed
268
      /** @var File $file */
269 270 271 272
      $file = $entity;
      $result = $this->getFileAccess($file, $operation);
      return $result;
    }
mathieso's avatar
mathieso committed
273 274 275 276 277 278
    elseif ($entityType == 'taxonomy_term') {
      /** @var Term $term */
      $term = $entity;
      $result = $this->getTaxonomyTermAccess($term, $operation);
      return $result;
    }
mathieso's avatar
mathieso committed
279 280 281
    $result = AccessResult::neutral();
    $result->setCacheMaxAge(0);
    return $result;
282 283
  }

mathieso's avatar
mathieso committed
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323

  public function getTaxonomyTermAccess(Term $term, $operation) {
    $allow = $this->isTaxonomyTermAccess($term, $operation);
    if ($allow) {
      $result = AccessResult::neutral();
    }
    else {
      $result = AccessResult::forbidden();
    }
    $result->setCacheMaxAge(0);
    return $result;
  }

  public function isTaxonomyTermAccess(Term $term, $operation) {
    $taxonomyName = $term->bundle();
    if ($taxonomyName != SkillingConstants::TAXONOMY_RUBRIC_ITEM_CATEGORIES) {
      return TRUE;
    }
    $allow = FALSE;
    // Normalize operation name.
    $operation = $this->normalizeOperation($operation);
    // Some flag to make code more readable.
    $viewOperation = $operation === SkillingConstants::VIEW_OPERATION;
    $editOperation = $operation === SkillingConstants::EDIT_OPERATION;
    // Make role flags in local vars to make code easier to read.
    $admin = $this->currentUser->isAdministrator();
    $author = $this->currentUser->isAuthor();
    $reviewer = $this->currentUser->isReviewer();
    $instructor = $this->currentUser->isInstructor();
    $grader = $this->currentUser->isGrader();
    // Start checking access.
    if ($viewOperation) {
      $allow = $admin || $author || $instructor || $grader || $reviewer;
    }
    if ($editOperation) {
      $allow = $admin || $author;
    }
    return $allow;
  }

324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
  /**
   * Is an entity one that Skilling's access check cares about?
   *
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   The entity.
   *
   * @return bool
   *   True if Skilling should check access, false if not.
   */
  public function isRelevantEntity(EntityInterface $entity) {
    $relevantEntity = FALSE;
    $entityType = $entity->getEntityTypeId();
    if ($entityType === 'user') {
      $relevantEntity = TRUE;
    }
    elseif ($entityType === 'node') {
      $contentType = $entity->bundle();
      $relevantEntity = in_array($contentType, SkillingConstants::SKILLING_CONTENT_TYPES);
    }
    elseif ($entityType === 'paragraph') {
      $paragraphType = $entity->bundle();
      $relevantEntity = in_array($paragraphType, SkillingConstants::SKILLING_PARAGRAPH_TYPES);
    }
    return $relevantEntity;
  }

mathieso's avatar
mathieso committed
350
  /**
351 352 353
   * Does the current user have access to a node?
   *
   * Returns an AccessResult, based on call to isNodeAccess().
mathieso's avatar
mathieso committed
354
   *
355 356
   * Field access is checked separately, in getFieldAccess()
   *
mathieso's avatar
mathieso committed
357
   * @param \Drupal\node\NodeInterface $node
mathieso's avatar
mathieso committed
358
   *   The node.
359 360
   * @param string $operation
   *   Operation to check - view, edit, update.
mathieso's avatar
mathieso committed
361 362
   *
   * @return \Drupal\Core\Access\AccessResultForbidden|\Drupal\Core\Access\AccessResultNeutral
mathieso's avatar
mathieso committed
363 364
   *   The result.
   *
mathieso's avatar
mathieso committed
365
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
mathieso's avatar
mathieso committed
366
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
mathieso's avatar
mathieso committed
367 368
   * @throws \Drupal\skilling\Exception\SkillingException
   */
369 370
  public function getNodeAccess(NodeInterface $node, $operation) {
    $allow = $this->isNodeAccess($node, $operation);
371 372 373 374 375 376 377 378 379 380 381 382 383
    if ($allow) {
      $result = AccessResult::neutral();
    }
    else {
      $result = AccessResult::forbidden();
    }
    $result->setCacheMaxAge(0);
    return $result;
  }

  /**
   * Does the current user have access to a node?
   *
384 385
   * Field access is checked separately, in isFieldAccess()
   *
386 387
   * @param \Drupal\node\NodeInterface $node
   *   The node.
388 389
   * @param string $operation
   *   Operation to check - view, edit, update.
390 391 392 393 394 395 396 397
   *
   * @return bool
   *   True if has access, false if not.
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   * @throws \Drupal\skilling\Exception\SkillingException
   */
398 399 400 401 402 403 404
  public function isNodeAccess(NodeInterface $node, $operation) {
    // Only check content types that are controlled by Skilling.
    $contentType = $node->bundle();
    if (!in_array($contentType, SkillingConstants::SKILLING_CONTENT_TYPES)) {
      // Not a Skilling content type. Other code determines its fate.
      return TRUE;
    }
405
    // Default to not allowing access.
mathieso's avatar
mathieso committed
406
    $allow = FALSE;
407 408 409 410
    // Normalize operation name.
    $operation = $this->normalizeOperation($operation);
    // Make operation flags to make code easier to read.
    $viewOperation = $operation === SkillingConstants::VIEW_OPERATION;
411 412 413 414 415 416 417 418 419
    $editOperation = $operation === SkillingConstants::EDIT_OPERATION;
    // Error if unknown operation.
    if (!$viewOperation && !$editOperation) {
      throw new SkillingInvalidValueException(
        Html::escape('Operation: ' . $operation . ', expected view or edit.'),
        __FILE__, __LINE__
      );
    }
    // Make role flags in local vars to make code easier to read.
420 421 422 423 424
    $admin = $this->currentUser->isAdministrator();
    $author = $this->currentUser->isAuthor();
    $reviewer = $this->currentUser->isReviewer();
    $instructor = $this->currentUser->isInstructor();
    $grader = $this->currentUser->isGrader();
425
    $student = $this->currentUser->isStudent();
426
    $anonymous = $this->currentUser->isAnonymous();
mathieso's avatar
mathieso committed
427
    $authenticated = $this->currentUser->isAuthenticated();
428
    // Start checking node access.
mathieso's avatar
mathieso committed
429 430 431 432 433
    switch ($contentType) {
      case SkillingConstants::LESSON_CONTENT_TYPE:
      case SkillingConstants::EXERCISE_CONTENT_TYPE:
      case SkillingConstants::PATTERN_CONTENT_TYPE:
      case SkillingConstants::PRINCIPLE_CONTENT_TYPE:
mathieso's avatar
mathieso committed
434
      case SkillingConstants::MODEL_CONTENT_TYPE:
mathieso's avatar
mathieso committed
435
      case SkillingConstants::BADGE_CONTENT_TYPE:
436 437 438 439 440 441 442 443 444 445 446 447 448 449 450
        if ($viewOperation) {
          // Everyone can see these nodes.
          $allow = TRUE;
        }
        elseif ($editOperation) {
          // Only admins and authors can edit.
          $allow = $admin || $author;
        }
        else {
          // Already checked above. Should never get here.
          throw new SkillingInvalidValueException(
            Html::escape('ARGH! Operation: ' . $operation . ', expected view or edit.'),
            __FILE__, __LINE__
          );
        }
mathieso's avatar
mathieso committed
451
        break;
mathieso's avatar
mathieso committed
452

mathieso's avatar
mathieso committed
453
      case SkillingConstants::DESIGN_PAGE_CONTENT_TYPE:
454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
        // Design page.
        if ($viewOperation) {
          // Admins, authors, reviewers, instructors and graders have access.
          // Anons and students don't have access, unless site admin
          // has set a config setting.
          if ($admin || $author || $reviewer || $instructor || $grader) {
            $allow = TRUE;
            break;
          }
          elseif ($student || $anonymous) {
            // Check config setting to see if allowed.
            $settings = $this->configFactory->get(SkillingConstants::SETTINGS_MAIN_KEY);
            $allow = $settings->get(SkillingConstants::SETTING_KEY_STUDENTS_ANON_SEE_DESIGN_PAGES);
            break;
          }
          // If user does not have a known Skilling role, use
          // default access: false.
        }
        elseif ($editOperation) {
          // Only admins and authors can edit.
          $allow = $admin || $author;
        }
        else {
          // Already checked above. Should never get there.
          throw new SkillingInvalidValueException(
            Html::escape('ARGH! Operation: ' . $operation . ', expected view or edit.'),
            __FILE__, __LINE__
          );
mathieso's avatar
mathieso committed
482 483
        }
        break;
mathieso's avatar
mathieso committed
484

mathieso's avatar
mathieso committed
485
      case SkillingConstants::RUBRIC_ITEM_CONTENT_TYPE:
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
        if ($viewOperation) {
          // Admins, authors, reviewers, instructors, and graders can see these
          // content types.
          if ($admin || $author || $reviewer || $instructor || $grader) {
            $allow = TRUE;
          }
          break;
        }
        elseif ($editOperation) {
          // Only admins and authors can edit.
          $allow = $admin || $author;
        }
        else {
          // Should never get here.
          throw new SkillingInvalidValueException(
            Html::escape('ARGH! Operation: ' . $operation . ', expected view or edit.'),
            __FILE__, __LINE__
          );
mathieso's avatar
mathieso committed
504 505
        }
        break;
mathieso's avatar
mathieso committed
506

mathieso's avatar
mathieso committed
507
      case SkillingConstants::EXERCISE_SUBMISSION_CONTENT_TYPE:
508
        // Submission.
509 510 511 512 513
        // Only a few cases permitted:
        // - Admins see and edit all.
        // - Students see and edit their own.
        // - Instructors see and edit submissions from students in
        //   their classes.
514
        // Graders can't access.
515 516
        // Rules apply for view and edit operations.
        // Admins can view submissions.
517 518 519 520
        if ($admin) {
          $allow = TRUE;
          break;
        }
521
        // Students can see their own their submissions.
522 523 524 525 526
        $nodeOwnerUid = $node->getOwnerId();
        if ($nodeOwnerUid === $this->currentUser->id()) {
          $allow = TRUE;
          break;
        }
527 528 529
        // Instructors can access submissions from students who are in
        // their own classes.
        if ($this->isCurrentUserInstructorOfSubmissionStudent($node)) {
530 531 532 533 534
          $allow = TRUE;
          break;
        }
        break;

535
      case SkillingConstants::CLASS_CONTENT_TYPE:
536 537 538 539 540 541 542 543 544 545 546 547
        // Classes.
        if ($viewOperation) {
          // Instructors and admins can see classes.
          if ($admin || $instructor) {
            $allow = TRUE;
            break;
          }
          // Others only see classes they are in.
          if ($this->currentUser->isInClass($node)) {
            $allow = TRUE;
            break;
          }
548 549
          break;
        }
550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569
        elseif ($editOperation) {
          if ($admin) {
            // Admins can edit.
            $allow = TRUE;
            break;
          }
          if ($instructor) {
            // Instructors can only edit classes they own.
            if ($this->isCurrentUserOwnsNode($node)) {
              $allow = TRUE;
              break;
            }
          }
        }
        else {
          // Should never get here.
          throw new SkillingInvalidValueException(
            Html::escape('ARGH! Operation: ' . $operation . ', expected view or edit.'),
            __FILE__, __LINE__
          );
570 571 572
        }
        break;

mathieso's avatar
mathieso committed
573
      case SkillingConstants::ENROLLMENT_CONTENT_TYPE:
574 575 576 577 578 579 580 581 582 583 584 585
        // Enrollment nodes.
        if ($viewOperation) {
          // Admins can see all enrollments.
          // Users can see their own enrollments.
          // Instructors can see enrollments of students who are
          // in their own classes.
          if ($admin) {
            $allow = TRUE;
            break;
          }
          // Instructors see enrollments in their classes.
          if ($instructor) {
mathieso's avatar
mathieso committed
586
            /* @noinspection PhpUndefinedFieldInspection */
587 588 589 590 591 592 593 594 595 596 597 598
            $classId = $node->get(SkillingConstants::FIELD_CLASS)->target_id;
            if ($this->currentUser->isInstructorOfClassNid($classId)) {
              $allow = TRUE;
              break;
            }
          }
          // Other users only see their own records. Enrolled users own their
          // own enrollment records.
          if ($this->isCurrentUserOwnsNode($node)) {
            $allow = TRUE;
            break;
          }
599
        }
600 601 602 603 604 605 606 607
        elseif ($editOperation) {
          // Admins can edit any enrollments.
          if ($admin) {
            $allow = TRUE;
            break;
          }
          // Instructors can edit enrollments in their classes.
          if ($instructor) {
mathieso's avatar
mathieso committed
608
            /* @noinspection PhpUndefinedFieldInspection */
609
            $classId = $node->get(SkillingConstants::FIELD_CLASS)->target_id;
610 611
            // No class id when this is a new record.
            if (is_null($classId) || $this->currentUser->isInstructorOfClassNid($classId)) {
612 613 614 615
              $allow = TRUE;
              break;
            }
          }
mathieso's avatar
mathieso committed
616
        }
mathieso's avatar
mathieso committed
617 618
        break;

mathieso's avatar
mathieso committed
619 620
      case SkillingConstants::NOTICE_CONTENT_TYPE:
        if ($viewOperation) {
mathieso's avatar
mathieso committed
621 622 623 624 625 626 627 628 629 630 631 632
          if ($authenticated) {
            if ($admin) {
              $allow = TRUE;
              break;
            }
            // People can see their own notices.
            $nodeOwnerUid = $node->getOwnerId();
            if ($nodeOwnerUid === $this->currentUser->id()) {
              $allow = TRUE;
              break;
            }
          }
mathieso's avatar
mathieso committed
633 634 635 636 637 638
        }
        elseif ($editOperation) {
          // Only admins and authors can edit.
          $allow = $admin;
          break;
        }
639
        else {
mathieso's avatar
mathieso committed
640
          // Already checked above. Should never get here.
641 642 643 644
          throw new SkillingInvalidValueException(
            Html::escape('ARGH! Operation: ' . $operation . ', expected view or edit.'),
            __FILE__, __LINE__
          );
mathieso's avatar
mathieso committed
645 646 647
        }
        break;

648 649 650 651 652 653 654 655
      case SkillingConstants::CHARACTER_CONTENT_TYPE:
        // Character content type.
        if ($viewOperation) {
          // Only authors, admins, and reviewers see these node types directly.
          if ($admin || $author || $reviewer) {
            $allow = TRUE;
            break;
          }
656 657
          break;
        }
658 659 660
        elseif ($editOperation) {
          // Only admins and authors can edit.
          if ($admin || $author) {
661 662 663 664
            $allow = TRUE;
            break;
          }
        }
665 666 667 668 669
        else {
          // Should never get here.
          throw new SkillingInvalidValueException(
            Html::escape('ARGH! Operation: ' . $operation . ', expected view or edit.'),
            __FILE__, __LINE__
670
          );
671 672 673
        }
        break;

mathieso's avatar
mathieso committed
674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715
//      case SkillingConstants::HISTORY_CONTENT_TYPE:
//        if ($viewOperation) {
//          // Admins can see.
//          if ($admin) {
//            $allow = TRUE;
//            break;
//          }
//          // Students can see their own. Students own history records
//          // about them.
//          if ($student) {
//            if ($this->isCurrentUserOwnsNode($node)) {
//              $allow = TRUE;
//              break;
//            }
//          }
//          // Instructors should have access to their own students.
//          if ($instructor) {
//            // Owner of the history node is the student whom the event is about.
//            $studentUid = $node->getOwnerId();
//            $possibleInstructorId = $this->currentUser->id();
//            $currentUserIsInstructorOfNodeOwner =
//              $this->checkUserRelationshipsService->isUserUidInstructorOfUserUid(
//                $possibleInstructorId, $studentUid
//            );
//            if ($currentUserIsInstructorOfNodeOwner) {
//              $allow = TRUE;
//              break;
//            }
//          }
//        }
//        elseif ($editOperation) {
//          // Only admins can edit history records.
//          $allow = $admin;
//        }
//        else {
//          // Should never get here.
//          throw new SkillingInvalidValueException(
//            Html::escape('ARGH! Operation: ' . $operation . ', expected view or edit.'),
//            __FILE__, __LINE__
//          );
//        }
//        break;
mathieso's avatar
mathieso committed
716

mathieso's avatar
mathieso committed
717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747
//      case SkillingConstants::CALENDAR_CONTENT_TYPE:
//        // Calendar nodes. Events are separate nodes.
//        if ($viewOperation) {
//          // Admins, authors, reviewers, and instructors can see
//          // all calendars.
//          if ($admin || $author || $reviewer || $instructor) {
//            $allow = TRUE;
//            break;
//          }
//        }
//        elseif ($editOperation) {
//          if ($admin || $author) {
//            $allow = TRUE;
//            break;
//          }
//          if ($instructor) {
//            // Instructors can only edit calendars they own.
//            if ($this->isCurrentUserOwnsNode($node)) {
//              $allow = TRUE;
//              break;
//            }
//          }
//        }
//        else {
//          // Should never get here.
//          throw new SkillingInvalidValueException(
//            Html::escape('ARGH! Operation: ' . $operation . ', expected view or edit.'),
//            __FILE__, __LINE__
//          );
//        }
//        break;
748

mathieso's avatar
mathieso committed
749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781
//      case SkillingConstants::EVENT_CONTENT_TYPE:
//        // Events on calendars.
//        if ($viewOperation) {
//          // Admins, authors, reviewers, and instructors can see
//          // all calendar events.
//          if ($admin || $author || $reviewer || $instructor) {
//            $allow = TRUE;
//            break;
//          }
//          // Students and graders can see events for calendars for classes
//          // they are in.
//          if ($student || $grader) {
//            if ($this->isCurrentUserInClassWithEvent($node)) {
//              $allow = TRUE;
//              break;
//            }
//          }
//        }
//        elseif ($editOperation) {
//          // Admins and authors can edit calendar records.
//          if ($admin || $author) {
//            $allow = TRUE;
//            break;
//          }
//        }
//        else {
//          // Should never get here.
//          throw new SkillingInvalidValueException(
//            Html::escape('ARGH! Operation: ' . $operation . ', expected view or edit.'),
//            __FILE__, __LINE__
//          );
//        }
//        break;
782

mathieso's avatar
mathieso committed
783
      case SkillingConstants::FILL_IN_THE_BLANK_CONTENT_TYPE:
784
      case SkillingConstants::MCQ_CONTENT_TYPE:
mathieso's avatar
mathieso committed
785
      case SkillingConstants::SUGGESTION_CONTENT_TYPE:
mathieso's avatar
mathieso committed
786 787
        // Only admins, authors, reviewers, and instructors can see FIB nodes.
        if ($admin || $author || $reviewer || $instructor) {
mathieso's avatar
mathieso committed
788 789 790
          $allow = TRUE;
        }
        break;
mathieso's avatar
mathieso committed
791

mathieso's avatar
mathieso committed
792
      case SkillingConstants::REFLECT_NOTE_CONTENT_TYPE:
793
        if ($viewOperation) {
mathieso's avatar
mathieso committed
794
          // Admins can see all reflect notes.
mathieso's avatar
mathieso committed
795 796 797
          // Authors can see them in a view, but restrictions are added on
          // individual nodes.
          if ($admin || $author) {
798 799 800
            $allow = TRUE;
            break;
          }
mathieso's avatar
mathieso committed
801
          // Instructors can see the reflect notes of their students.
802 803 804 805 806 807
          if ($instructor) {
            if ($this->isCurrentUserInstructorOfNodeOwner($node)) {
              $allow = TRUE;
              break;
            }
          }
mathieso's avatar
mathieso committed
808
          // Students can see their own reflect notes.
809 810 811 812 813 814 815 816
          if ($student) {
            if ($this->isCurrentUserOwnsNode($node)) {
              $allow = TRUE;
              break;
            }
          }
        }
        elseif ($editOperation) {
mathieso's avatar
mathieso committed
817
          // Admins can edit reflect notes.
818 819 820 821
          if ($admin) {
            $allow = TRUE;
            break;
          }
mathieso's avatar
mathieso committed
822
          // Students can edit their own reflect notes.
823 824 825 826 827 828 829 830 831 832 833 834 835 836
          if ($student) {
            if ($this->isCurrentUserOwnsNode($node)) {
              $allow = TRUE;
              break;
            }
          }
        }
        else {
          // Should never get here.
          throw new SkillingInvalidValueException(
            Html::escape('ARGH! Operation: ' . $operation . ', expected view or edit.'),
            __FILE__, __LINE__
          );
        }
mathieso's avatar
mathieso committed
837
        break;
838 839 840 841 842 843 844

      default:
        // Should never get here.
        throw new SkillingInvalidValueException(
          Html::escape('ARGH! Unknown content type: ' . $contentType),
          __FILE__, __LINE__
        );
mathieso's avatar
mathieso committed
845
    }
846
    return $allow;
mathieso's avatar
mathieso committed
847 848
  }

mathieso's avatar
mathieso committed
849
  /**
850 851
   * Check whether the current user has access to a field.
   *
mathieso's avatar
mathieso committed
852
   * @param \Drupal\Core\Field\FieldDefinitionInterface $fieldDefinition
853
   *   The field to check.
mathieso's avatar
mathieso committed
854 855
   * @param string $operation
   *   Operation, view or edit.
mathieso's avatar
mathieso committed
856 857
   * @param \Drupal\Core\Field\FieldItemListInterface $items
   *   Items affected.
mathieso's avatar
mathieso committed
858 859
   *
   * @return \Drupal\Core\Access\AccessResultForbidden|\Drupal\Core\Access\AccessResultNeutral
860
   *   The result of the access check.
mathieso's avatar
mathieso committed
861
   *
862
   * @throws \Drupal\skilling\Exception\SkillingInvalidValueException
863
   * @throws \Drupal\skilling\Exception\SkillingException
mathieso's avatar
mathieso committed
864
   */
mathieso's avatar
mathieso committed
865
  public function getFieldAccess(FieldDefinitionInterface $fieldDefinition, $operation, FieldItemListInterface $items = NULL) {
866
    // If $items is set, we know what entity the user is trying to access.
867
    // See the field permissions example in examples module.
868
    if ($items) {
869
      /** @var \Drupal\Core\Entity\EntityInterface $entity */
870 871 872 873 874 875 876 877 878
      $entity = $items->getEntity();
      // Is this entity one that Skilling should access check?
      $relevant = $this->isRelevantEntity($entity);
      if (!$relevant) {
        // No.
        $result = AccessResult::neutral()->setCacheMaxAge(0);
        return $result;
      }
    }
879 880
    // Normalize the operation.
    $operation = $this->normalizeOperation($operation);
881
    // Sanity check on operation.
882
    if ($operation !== SkillingConstants::VIEW_OPERATION && $operation !== SkillingConstants::EDIT_OPERATION) {
883 884 885 886 887
      throw new SkillingInvalidValueException(
        Html::escape('Operation: ' . $operation . ', expected view or edit.'),
        __FILE__, __LINE__
      );
    }
888 889
    // Get the field name.
    $fieldName = $fieldDefinition->getName();
890 891 892 893 894 895 896 897 898
    // Check whether this is a special case.
    $access = $this->fieldAccessSpecialCaseChecker->checkForSpecialCase($fieldName, $operation);
    if ($access !== NULL) {
      $result = $access ? AccessResult::allowed() : AccessResult::forbidden();
      $result->setCacheMaxAge(0);
      return $result;
    }
    // Access is not allowed by default.
    $allow = FALSE;
mathieso's avatar
mathieso committed
899 900 901 902
    // Promote is strange case. Base field, with get.
    $isFieldPromote = $fieldName === 'promote';
    $isGetExists = method_exists($fieldDefinition, 'get');
    if (!$isGetExists || $isFieldPromote) {
903
      // Handle entity base fields differently.
mathieso's avatar
mathieso committed
904 905
      $result = AccessResult::neutral()->setCacheMaxAge(0);
      return $result;
906
      // Check base fields.txt in old code for almost-there solution.
mathieso's avatar
mathieso committed
907 908 909
    }
    $entityType = $fieldDefinition->get('entity_type');
    $bundle = $fieldDefinition->get('bundle');
910
    // Differentiate between entity types: node or user.
mathieso's avatar
mathieso committed
911 912
    switch ($entityType) {
      case 'node':
913
        // What content type?
mathieso's avatar
mathieso committed
914 915
        switch ($bundle) {
          case SkillingConstants::LESSON_CONTENT_TYPE:
mathieso's avatar
mathieso committed
916
            // Fields for lessons.
917
            $allow = $this->isLessonFieldAccess($operation, $fieldName);
918
            break;
mathieso's avatar
mathieso committed
919

920 921 922
          case SkillingConstants::DESIGN_PAGE_CONTENT_TYPE:
            // Fields for design pages.
            $allow = $this->isDesignPageFieldAccess($operation, $fieldName);
923
            break;
mathieso's avatar
mathieso committed
924

925 926 927
          case SkillingConstants::EXERCISE_CONTENT_TYPE:
            // Fields for exercises.
            $allow = $this->isExerciseFieldAccess($operation, $fieldName);
928 929
            break;

930
          case SkillingConstants::EXERCISE_SUBMISSION_CONTENT_TYPE:
931
            // Fields for exercise submissions.
932
            $allow = $this->isExerciseSubmissionFieldAccess($operation, $fieldName);
mathieso's avatar
mathieso committed
933
            break;
mathieso's avatar
mathieso committed
934

935 936 937
          case SkillingConstants::ENROLLMENT_CONTENT_TYPE:
            // Fields for enrollments.
            $allow = $this->isEnrollmentFieldAccess($operation, $fieldName);
938 939
            break;

940 941 942
          case SkillingConstants::CLASS_CONTENT_TYPE:
            // Fields for .
            $allow = $this->isClassFieldAccess($operation, $fieldName);
943 944
            break;

mathieso's avatar
mathieso committed
945 946 947 948
//          case SkillingConstants::CALENDAR_CONTENT_TYPE:
//            // Fields for .
//            $allow = $this->isCalendarFieldAccess($operation, $fieldName);
//            break;
949

mathieso's avatar
mathieso committed
950 951 952 953 954
//          case SkillingConstants::EVENT_CONTENT_TYPE:
//            // Fields for .
//            $allow = $this->isEventFieldAccess($operation, $fieldName);
//            break;
//
955 956
          case SkillingConstants::RUBRIC_ITEM_CONTENT_TYPE:
            // Fields for .
957
            $allow = $this->isRubricItemFieldAccess($operation, $fieldName);
958 959
            break;

mathieso's avatar
mathieso committed
960
          case SkillingConstants::PATTERN_CONTENT_TYPE:
961 962 963 964
            // Fields for patterns.
            $allow = $this->isPatternFieldAccess($operation, $fieldName);
            break;

mathieso's avatar
mathieso committed
965
          case SkillingConstants::PRINCIPLE_CONTENT_TYPE:
966 967
            // Fields for principles.
            $allow = $this->isPrincipleFieldAccess($operation, $fieldName);
968
            break;
mathieso's avatar
mathieso committed
969

mathieso's avatar
mathieso committed
970 971 972 973 974
          case SkillingConstants::MODEL_CONTENT_TYPE:
            // Fields for models.
            $allow = $this->isModelFieldAccess($operation, $fieldName);
            break;

975 976 977
          case SkillingConstants::CHARACTER_CONTENT_TYPE:
            // Fields for characters.
            $allow = $this->isCharacterFieldAccess($operation, $fieldName);
978
            break;
mathieso's avatar
mathieso committed
979

980 981
          case SkillingConstants::FILL_IN_THE_BLANK_CONTENT_TYPE:
            // Fields for design pages.
982
            $allow = $this->isFibFieldAccess($operation, $fieldName);
983
            break;
mathieso's avatar
mathieso committed
984

mathieso's avatar
mathieso committed
985 986 987 988
//          case SkillingConstants::HISTORY_CONTENT_TYPE:
//            // Fields for .
//            $allow = $this->isHistoryFieldAccess($operation, $fieldName);
//            break;
989

mathieso's avatar
mathieso committed
990
          case SkillingConstants::REFLECT_NOTE_CONTENT_TYPE:
991
            // Fields for .
mathieso's avatar
mathieso committed
992
            $allow = $this->isReflectNoteFieldAccess($operation, $fieldName);
993 994 995 996 997
            break;

          case SkillingConstants::MCQ_CONTENT_TYPE:
            // Fields for .
            $allow = $this->isMcqFieldAccess($operation, $fieldName);
mathieso's avatar
mathieso committed
998
            break;
mathieso's avatar
mathieso committed
999 1000 1001 1002 1003

          case SkillingConstants::SUGGESTION_CONTENT_TYPE:
            // Fields for suggestions.
            $allow = $this->isSuggestionFieldAccess($operation, $fieldName);
            break;
mathieso's avatar
mathieso committed
1004 1005 1006 1007 1008

          case SkillingConstants::NOTICE_CONTENT_TYPE:
            // Fields for suggestions.
            $allow = $this->isNoticeFieldAccess($operation, $fieldName);
            break;
mathieso's avatar
mathieso committed
1009 1010 1011 1012 1013 1014

          case SkillingConstants::BADGE_CONTENT_TYPE:
            // Fields for badges.
            $allow = $this->isBadgeFieldAccess($operation, $fieldName);
            break;

mathieso's avatar
mathieso committed
1015
        } //End nodes entity type.
1016
        break;
mathieso's avatar
mathieso committed
1017

1018 1019 1020
      case 'paragraph':
        // What paragraph type?
        switch ($bundle) {
mathieso's avatar
mathieso committed
1021 1022 1023
          case SkillingConstants::EXERCISE_DUE_PARAGRAPH_TYPE:
            // Fields for exercises due events.
            $allow = $this->isExerciseDueFieldAccess($operation, $fieldName);
1024 1025 1026 1027 1028 1029 1030
            break;

          case SkillingConstants::MCQ_RESPONSE_PARAGRAPH_TYPE:
            // Fields for MCQ responses.
            $allow = $this->isMcqResponseFieldAccess($operation, $fieldName);
            break;

1031 1032 1033 1034 1035
          case SkillingConstants::FIB_RESPONSE_PARAGRAPH_TYPE:
            // Fields for FiB responses.
            $allow = $this->isFibResponseFieldAccess($operation, $fieldName);
            break;

1036 1037
          case SkillingConstants::RUBRIC_ITEM_RESPONSE_PARAGRAPH_TYPE:
            // Fields for .
1038
            $allow = $this->isRubricItemResponseFieldAccess($operation, $fieldName);
1039 1040
            break;

1041 1042 1043
        }
        break;

1044
      case 'user':
1045
        // Check visibility of fields for user entities.
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082
        $allow = $this->isUserFieldAccess($operation, $fieldName);
        break;
    }
    $result = $allow ? AccessResult::neutral() : AccessResult::forbidden();
    $result->setCacheMaxAge(0);
    return $result;
  }

  /**
   * Check access to a field of the user entity for the current user.
   *
   * @param string $operation
   *   Operation, view or edit.
   * @param string $fieldName
   *   Name of field.
   *
   * @return bool
   *   True if access is allowed.
   *
   * @throws \Drupal\skilling\Exception\SkillingInvalidValueException
   */
  public function isUserFieldAccess($operation, $fieldName) {
    // Is this a user field that Skilling knows about?
    if (!in_array($fieldName, SkillingConstants::SKILLING_USER_FIELDS)) {
      return TRUE;
    }
    // Default to not allowing access.
    $allow = FALSE;
    // Flags to make code below easier to read.
    $viewOperation = $operation === SkillingConstants::VIEW_OPERATION;
    $editOperation = $operation === SkillingConstants::EDIT_OPERATION;
    $admin = $this->currentUser->isAdministrator();
    $instructor = $this->currentUser->isInstructor();
    $author = $this->currentUser->isAuthor();
    $reviewer = $this->currentUser->isReviewer();
    $grader = $this->currentUser->isGrader();
    $student = $this->currentUser->isStudent();
mathieso's avatar
mathieso committed
1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127
//    if ($viewOperation) {
//      if ($student) {
//        switch ($fieldName) {
//          case SkillingConstants::FIELD_FIRST_NAME:
//          case SkillingConstants::FIELD_LAST_NAME:
//          case SkillingConstants::FIELD_INITIALS:
//          case SkillingConstants::FIELD_ABOUT:
//          case SkillingConstants::FIELD_PICTURE:
//          case SkillingConstants::FIELD_BADGES_AWARDED:
//          case SkillingConstants::FIELD_SHOW_PORTFOLIO:
//          $allow = TRUE;
//          break;
//        }
//      }
//      elseif ($admin || $instructor) {
//        $allow = TRUE;
//      }
//
//    }
//    elseif ($editOperation) {
//      if ($admin || $instructor) {
//        $allow = TRUE;
//      }
//      if ($student) {
//        // Can't change badges awarded.
//        switch ($fieldName) {
//          case SkillingConstants::FIELD_FIRST_NAME:
//          case SkillingConstants::FIELD_LAST_NAME:
//          case SkillingConstants::FIELD_INITIALS:
//          case SkillingConstants::FIELD_ABOUT:
//          case SkillingConstants::FIELD_PICTURE:
//          case SkillingConstants::FIELD_SHOW_PORTFOLIO:
//            $allow = TRUE;
//            break;
//        }
//      }
//
//    }
//    else {
//      throw new SkillingInvalidValueException(
//        Html::escape('Operation: ' . $operation . ', expected view or edit.'),
//        __FILE__, __LINE__
//      );
//    }

1128 1129 1130 1131 1132 1133 1134 1135
    if ($viewOperation || $editOperation) {
      if ($admin ||  $instructor || $author || $reviewer) {
        // See all fields of accounts they have access to.
        // This may just be their own accounts.
        // Instructor, authors, and reviewers have access to all fields,
        // even though will never use them all. This will help instructors
        // and authors keep the entire feedback cycle in mind, and help
        // reviewers understand the system.
1136 1137 1138
        if ($fieldName != SkillingConstants::FIELD_SHOW_PORTFOLIO) {
          $allow = TRUE;
        }
1139 1140
      }
      elseif ($grader) {
1141
        switch ($fieldName) {
mathieso's avatar
mathieso committed
1142 1143
          case SkillingConstants::FIELD_FIRST_NAME:
          case SkillingConstants::FIELD_LAST_NAME:
1144
          case SkillingConstants::FIELD_INITIALS:
mathieso's avatar
mathieso committed
1145
          case SkillingConstants::FIELD_ABOUT:
1146
          case SkillingConstants::FIELD_PICTURE:
1147 1148 1149 1150 1151
          case SkillingConstants::FIELD_FEEDBACK_GREETINGS:
          case SkillingConstants::FIELD_FEEDBACK_SIGNATURES:
          case SkillingConstants::FIELD_FEEDBACK_SUMMARY_GOOD:
          case SkillingConstants::FIELD_FEEDBACK_SUMMARY_NEEDS_WORK:
          case SkillingConstants::FIELD_FEEDBACK_SUMMARY_POOR:
1152
//          case SkillingConstants::FIELD_SHOW_PORTFOLIO:
1153
            $allow = TRUE;
mathieso's avatar
mathieso committed
1154
            break;
1155 1156 1157
        }
      }
      elseif ($student) {
1158 1159 1160 1161
        if ($fieldName == SkillingConstants::FIELD_SHOW_PORTFOLIO) {
          $allow = FALSE;
        }
        elseif ($editOperation && $fieldName === SkillingConstants::FIELD_BADGES_AWARDED) {
mathieso's avatar
mathieso committed
1162 1163 1164 1165 1166 1167 1168 1169 1170 1171
          $allow = FALSE;
        }
        else {
          switch ($fieldName) {
            case SkillingConstants::FIELD_FIRST_NAME:
            case SkillingConstants::FIELD_LAST_NAME:
            case SkillingConstants::FIELD_INITIALS:
            case SkillingConstants::FIELD_ABOUT:
            case SkillingConstants::FIELD_PICTURE:
            case SkillingConstants::FIELD_SHOW_PORTFOLIO:
mathieso's avatar
mathieso committed
1172
            case SkillingConstants::FIELD_BADGES_AWARDED:
mathieso's avatar
mathieso committed
1173 1174 1175
              $allow = TRUE;
              break;
          }
1176
        }
1177
      }
mathieso's avatar
mathieso committed
1178
    }
1179 1180 1181 1182 1183 1184 1185 1186
    else {
      // Already checked above. Should never get here.
      throw new SkillingInvalidValueException(
        Html::escape('ARGH! Operation: ' . $operation . ', expected view or edit.'),
        __FILE__, __LINE__
      );
    }
    return $allow;
mathieso's avatar
mathieso committed
1187 1188
  }

1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212
  /**
   * Check field access for the lesson content type for the current user.
   *
   * @param string $operation
   *   Operation, view or edit.
   * @param string $fieldName
   *   Name of the field to check access to.
   *
   * @return bool
   *   True means access is not blocked. False means it is blocked.
   *
   * @throws \Drupal\skilling\Exception\SkillingInvalidValueException
   */
  protected function isLessonFieldAccess($operation, $fieldName) {
    // Deny access by default.
    $allow = FALSE;
    $admin = $this->currentUser->isAdministrator();
    $author = $this->currentUser->isAuthor();
    $reviewer = $this->currentUser->isReviewer();
    $instructor = $this->currentUser->isInstructor();
    $grader = $this->currentUser->isGrader();
    if ($operation === SkillingConstants::VIEW_OPERATION) {
      switch ($fieldName) {
        // Viewing a lesson.
1213
        case SkillingConstants::FIELD_TITLE:
1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242
        case SkillingConstants::FIELD_BODY:
        case SkillingConstants::FIELD_TAGS:
        case SkillingConstants::FIELD_ATTACHMENTS:
          // Everyone can see body, tags, and attachments fields of
          // the lesson content type.
          $allow = TRUE;
          break;

        case SkillingConstants::FIELD_NOTES:
        case SkillingConstants::FIELD_HIDDEN_ATTACHMENTS:
          // Admins, authors, reviewers, instructors, and graders
          // can see notes, and hidden attachments fields
          // of the lesson content type.
          $allow = $admin || $author || $reviewer || $instructor || $grader;
          break;

        case SkillingConstants::FIELD_SHOW_TOC:
          // Admins and authors can see the show-toc
          // field of the lesson content type.
          $allow = $admin || $author;
          break;

        case SkillingConstants::FIELD_ORDER_IN_BOOK:
          // Only admins can see the order-in-book field of
          // the lesson content type.
          $allow = $admin;
          break;

        default:
mathieso's avatar
mathieso committed
1243
          $this->makeUnknownFieldErrorReportForUser($fieldName);
1244 1245 1246 1247 1248
      }
    }
    elseif ($operation === SkillingConstants::EDIT_OPERATION) {
      switch ($fieldName) {
        // Editing a lesson.
1249
        case SkillingConstants::FIELD_TITLE:
1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267
        case SkillingConstants::FIELD_BODY:
        case SkillingConstants::FIELD_TAGS:
        case SkillingConstants::FIELD_SHOW_TOC:
        case SkillingConstants::FIELD_ATTACHMENTS:
        case SkillingConstants::FIELD_HIDDEN_ATTACHMENTS:
        case SkillingConstants::FIELD_NOTES:
          // Admins and authors can edit the body, tags, show-toc, attachments,
          // hidden attachments, and notes fields of the lesson content type.
          $allow = $admin || $author;
          break;

        case SkillingConstants::FIELD_ORDER_IN_BOOK:
          // Only admins can edit the order-in-book field of
          // the lesson content type.
          $allow = $admin;
          break;

        default:
mathieso's avatar
mathieso committed
1268
          $this->makeUnknownFieldErrorReportForUser($fieldName);
1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279
      }
    }
    else {
      throw new SkillingInvalidValueException(
        Html::escape('Operation not supported: ' . $operation),
        __FILE__, __LINE__
      );
    }
    return $allow;
  }

1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306
  /**
   * Check field access for the design page content type for the current user.
   *
   * @param string $operation
   *   Operation, view or edit.
   * @param string $fieldName
   *   Name of the field to check access to.
   *
   * @return bool
   *   True means access is not blocked. False means it is blocked.
   *
   * @throws \Drupal\skilling\Exception\SkillingInvalidValueException
   * @throws \Drupal\skilling\Exception\SkillingException
   */
  protected function isDesignPageFieldAccess($operation, $fieldName) {
    // Deny access by default.
    $allow = FALSE;
    $admin = $this->currentUser->isAdministrator();
    $author = $this->currentUser->isAuthor();
    $reviewer = $this->currentUser->isReviewer();
    $instructor = $this->currentUser->isInstructor();
    $grader = $this->currentUser->isGrader();
    $student = $this->currentUser->isStudent();
    $anonymous = $this->currentUser->isAnonymous();
    if ($operation === SkillingConstants::VIEW_OPERATION) {
      switch ($fieldName) {
        // Viewing a design page.
1307
        case SkillingConstants::FIELD_TITLE:
1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329
        case SkillingConstants::FIELD_BODY:
        case SkillingConstants::FIELD_TAGS:
        case SkillingConstants::FIELD_ATTACHMENTS:
          if ($admin || $author || $instructor || $grader || $reviewer) {
            $allow = TRUE;
            break;
          }
          elseif ($student || $anonymous) {
            // Get setting value for whether students and anons are allowed
            // to see design pages.
            $settings = $this->configFactory->get(SkillingConstants::SETTINGS_MAIN_KEY);
            $allowStudentsAnons = $settings->get(SkillingConstants::SETTING_KEY_STUDENTS_ANON_SEE_DESIGN_PAGES);
            $allow = $allowStudentsAnons;
            break;
          }
          else {
            throw new SkillingException(
              Html::escape('Role checking problem.'),
              __FILE__, __LINE__
            );
          }

1330 1331 1332 1333
        case SkillingConstants::FIELD_ORDER_IN_BOOK:
          $allow = $admin;
          break;

1334
        default: