You are here

protected function ImportTrainingForm::importActivity in Opigno module 8

Same name and namespace in other branches
  1. 3.x src/Form/ImportTrainingForm.php \Drupal\opigno_module\Form\ImportTrainingForm::importActivity()

Create Opigno Activity entity.

Parameters

array $activity_content: List of settings from imported file.

Return value

OpignoActivity

Throws

\Exception

1 call to ImportTrainingForm::importActivity()
ImportTrainingForm::submitForm in src/Form/ImportTrainingForm.php
Form submission handler.

File

src/Form/ImportTrainingForm.php, line 676

Class

ImportTrainingForm
Import Course form.

Namespace

Drupal\opigno_module\Form

Code

protected function importActivity($activity_content) {
  $new_activity = OpignoActivity::create([
    'type' => $activity_content['type'][0]['target_id'],
  ]);
  $new_activity
    ->setName($activity_content['name'][0]['value']);
  $new_activity
    ->set('langcode', $activity_content['langcode'][0]['value']);
  $new_activity
    ->set('status', $activity_content['status'][0]['value']);
  prepare_directory_structure_for_import();
  switch ($activity_content['type'][0]['target_id']) {
    case 'opigno_long_answer':
      if (!empty($activity_content['opigno_body'][0])) {
        $new_activity->opigno_body->value = $activity_content['opigno_body'][0]['value'];
        $new_activity->opigno_body->format = $activity_content['opigno_body'][0]['format'];
      }
      if (!empty($activity_content['opigno_evaluation_method'][0])) {
        $new_activity->opigno_evaluation_method->value = $activity_content['opigno_evaluation_method'][0]['value'];
      }
      break;
    case 'opigno_file_upload':
      $new_activity->opigno_body->value = $activity_content['opigno_body'][0]['value'];
      $new_activity->opigno_body->format = $activity_content['opigno_body'][0]['format'];
      $new_activity->opigno_evaluation_method->value = $activity_content['opigno_evaluation_method'][0]['value'];
      $new_activity->opigno_allowed_extension->value = $activity_content['opigno_allowed_extension'][0]['value'];
      break;
    case 'opigno_scorm':
      foreach ($activity_content['files'] as $file_key => $file_content) {
        $scorm_file_path = $this->tmp . '/' . $file_key;
        $uri = $this
          ->copyFile($scorm_file_path, 'public://opigno_scorm/' . $file_content['file_name'], 'public://opigno_scorm');
        if (!empty($uri)) {
          $file = File::Create([
            'uri' => $uri,
            'uid' => $this
              ->currentUser()
              ->id(),
            'status' => $file_content['status'][0]['value'],
          ]);
          $file
            ->save();
          $fid = $file
            ->id();
          $new_activity->opigno_scorm_package->target_id = $fid;
          $new_activity->opigno_scorm_package->display = 1;
        }
      }
      break;
    case 'opigno_tincan':
      foreach ($activity_content['files'] as $file_key => $file_content) {
        $tincan_file_path = $this->tmp . '/' . $file_key;
        $uri = $this
          ->copyFile($tincan_file_path, 'public://opigno_tincan/' . $file_content['file_name'], 'public://opigno_tincan');
        if (!empty($uri)) {
          $file = File::Create([
            'uri' => $uri,
            'uid' => $this
              ->currentUser()
              ->id(),
            'status' => $file_content['status'][0]['value'],
          ]);
          $file
            ->save();
          $fid = $file
            ->id();
          $new_activity->opigno_tincan_package->target_id = $fid;
          $new_activity->opigno_tincan_package->display = 1;
        }
      }
      break;
    case 'opigno_slide':
      foreach ($activity_content['files'] as $file_key => $file_content) {
        $slide_file_path = $this->tmp . '/' . $file_key;
        $current_timestamp = \Drupal::time()
          ->getCurrentTime();
        $date = date('Y-m', $current_timestamp);
        $uri = $this
          ->copyFile($slide_file_path, 'public://' . $date . '/' . $file_content['file_name'], 'public://' . $date);
        if (!empty($uri)) {
          $file = File::Create([
            'uri' => $uri,
            'uid' => $this
              ->currentUser()
              ->id(),
            'status' => $file_content['status'][0]['value'],
          ]);
          $file
            ->save();
          $media = Media::create([
            'bundle' => $file_content['bundle'],
            'name' => $file_content['file_name'],
            'field_media_file' => [
              'target_id' => $file
                ->id(),
            ],
          ]);
          $media
            ->save();
          $new_activity->opigno_slide_pdf->target_id = $media
            ->id();
          $new_activity->opigno_slide_pdf->display = 1;
        }
      }
      break;
    case 'opigno_video':
      foreach ($activity_content['files'] as $file_key => $file_content) {
        $video_file_path = $this->tmp . '/' . $file_key;
        $current_timestamp = \Drupal::time()
          ->getCurrentTime();
        $date = date('Y-m', $current_timestamp);
        $uri = $this
          ->copyFile($video_file_path, 'public://video-thumbnails/' . $date . '/' . $file_content['file_name'], 'public://video-thumbnails/' . $date);
        if (!empty($uri)) {
          $file = File::Create([
            'uri' => $uri,
            'uid' => $this
              ->currentUser()
              ->id(),
            'status' => $file_content['status'],
          ]);
          $file
            ->save();
          $new_activity->field_video->target_id = $file
            ->id();
        }
      }
      break;
    case 'opigno_h5p':
      $h5p_content_id = $activity_content['opigno_h5p'][0]['h5p_content_id'];
      $file = $this->folder . "/interactive-content-{$h5p_content_id}.h5p";
      $interface = H5PDrupal::getInstance();
      if (file_exists($file)) {
        $dir = $this->fileSystem
          ->realpath($this->tmp . '/h5p');
        $interface
          ->getUploadedH5pFolderPath($dir);
        $interface
          ->getUploadedH5pPath($file);
        $editor = H5PEditorUtilities::getInstance();
        $h5pEditorAjax = new H5PEditorAjaxImport($editor->ajax->core, $editor, $editor->ajax->storage);
        if ($h5pEditorAjax
          ->isValidPackage(TRUE)) {

          // Add new libraries from file package.
          $storage = new H5PStorageImport($h5pEditorAjax->core->h5pF, $h5pEditorAjax->core);

          // Serialize metadata array in libraries.
          if (!empty($storage->h5pC->librariesJsonData)) {
            foreach ($storage->h5pC->librariesJsonData as &$library) {
              if (array_key_exists('metadataSettings', $library) && is_array($library['metadataSettings'])) {
                $metadataSettings = serialize($library['metadataSettings']);
                $library['metadataSettings'] = $metadataSettings;
              }
            }
          }
          $storage
            ->saveLibraries();
          $h5p_json = $dir . '/h5p.json';
          $real_path = $this->fileSystem
            ->realpath($h5p_json);
          $h5p_json = file_get_contents($real_path);
          $format = 'json';
          $serializer = \Drupal::service('serializer');
          $h5p_json = $serializer
            ->decode($h5p_json, $format);
          $dependencies = $h5p_json['preloadedDependencies'];

          // Get ID of main library.
          foreach ($h5p_json['preloadedDependencies'] as $dependency) {
            if ($dependency['machineName'] == $h5p_json['mainLibrary']) {
              $h5p_json['majorVersion'] = $dependency['majorVersion'];
              $h5p_json['minorVersion'] = $dependency['minorVersion'];
            }
          }
          $query = $this->database
            ->select('h5p_libraries', 'h_l');
          $query
            ->condition('machine_name', $h5p_json['mainLibrary'], '=');
          $query
            ->condition('major_version', $h5p_json['majorVersion'], '=');
          $query
            ->condition('minor_version', $h5p_json['minorVersion'], '=');
          $query
            ->fields('h_l', [
            'library_id',
          ]);
          $query
            ->orderBy('patch_version', 'DESC');
          $main_library_id = $query
            ->execute()
            ->fetchField();
          if (!$main_library_id) {
            $query = $this->database
              ->select('h5p_libraries', 'h_l');
            $query
              ->condition('machine_name', $h5p_json['mainLibrary'], '=');
            $query
              ->fields('h_l', [
              'library_id',
            ]);
            $query
              ->orderBy('major_version', 'DESC');
            $query
              ->orderBy('minor_version', 'DESC');
            $query
              ->orderBy('patch_version', 'DESC');
            $main_library_id = $query
              ->execute()
              ->fetchField();
          }
          $content_json = $dir . '/content/content.json';
          $real_path = $this->fileSystem
            ->realpath($content_json);
          $content_json = file_get_contents($real_path);
          $fields = [
            'library_id' => $main_library_id,
            'title' => $h5p_json['title'],
            'parameters' => $content_json,
            'filtered_parameters' => $content_json,
            'disabled_features' => 0,
            'authors' => '[]',
            'changes' => '[]',
            'license' => 'U',
          ];
          $h5p_content = H5PContent::create($fields);
          $h5p_content
            ->save();
          $new_activity
            ->set('opigno_h5p', $h5p_content
            ->id());
          $h5p_dest_path = \Drupal::config('h5p.settings')
            ->get('h5p_default_path');
          $h5p_dest_path = !empty($h5p_dest_path) ? $h5p_dest_path : 'h5p';
          $dest_folder = DRUPAL_ROOT . '/sites/default/files/' . $h5p_dest_path . '/content/' . $h5p_content
            ->id();
          $source_folder = DRUPAL_ROOT . '/sites/default/files/opigno-import/h5p/content/*';
          $this->fileSystem
            ->prepareDirectory($dest_folder, FileSystemInterface::MODIFY_PERMISSIONS | FileSystemInterface::CREATE_DIRECTORY);
          shell_exec('rm ' . $dest_folder . '/content.json');
          shell_exec('cp -r ' . $source_folder . ' ' . $dest_folder);

          // Clean up.
          $h5_file = $h5pEditorAjax->core->h5pF
            ->getUploadedH5pFolderPath();
          if (file_exists($h5_file)) {
            $h5pEditorAjax->storage
              ->removeTemporarilySavedFiles($h5_file);
          }
          foreach ($dependencies as $dependency_key => $dependency) {
            $query = $this->database
              ->select('h5p_libraries', 'h_l');
            $query
              ->condition('machine_name', $dependency['machineName'], '=');
            $query
              ->condition('major_version', $dependency['majorVersion'], '=');
            $query
              ->condition('minor_version', $dependency['minorVersion'], '=');
            $query
              ->fields('h_l', [
              'library_id',
            ]);
            $query
              ->orderBy('patch_version', 'DESC');
            $library_id = $query
              ->execute()
              ->fetchField();
            if (!$library_id) {
              $query = $this->database
                ->select('h5p_libraries', 'h_l');
              $query
                ->condition('machine_name', $dependency['machineName'], '=');
              $query
                ->fields('h_l', [
                'library_id',
              ]);
              $query
                ->orderBy('major_version', 'DESC');
              $query
                ->orderBy('minor_version', 'DESC');
              $query
                ->orderBy('patch_version', 'DESC');
              $library_id = $query
                ->execute()
                ->fetchField();
            }
            if ($h5p_json['mainLibrary'] == $dependency['machineName']) {
              $main_library_values = [
                'content_id' => $h5p_content
                  ->id(),
                'library_id' => $library_id,
                'dependency_type' => 'preloaded',
                'drop_css' => 0,
                'weight' => count($dependencies) + 1,
              ];
              continue;
            }
            if ($library_id) {
              $this->database
                ->insert('h5p_content_libraries')
                ->fields([
                'content_id',
                'library_id',
                'dependency_type',
                'drop_css',
                'weight',
              ])
                ->values([
                'content_id' => $h5p_content
                  ->id(),
                'library_id' => $library_id,
                'dependency_type' => 'preloaded',
                'drop_css' => 0,
                'weight' => $dependency_key + 1,
              ])
                ->execute();
            }
          }
          if (!empty($main_library_values)) {
            $this->database
              ->insert('h5p_content_libraries')
              ->fields([
              'content_id',
              'library_id',
              'dependency_type',
              'drop_css',
              'weight',
            ])
              ->values($main_library_values)
              ->execute();
          }
        }
      }
      break;
  }
  $new_activity
    ->save();
  return $new_activity;
}