You are here

public function OpignoGroupManagerController::trainingExport in Opigno group manager 8

Same name and namespace in other branches
  1. 3.x src/Controller/OpignoGroupManagerController.php \Drupal\opigno_group_manager\Controller\OpignoGroupManagerController::trainingExport()

Export training.

Parameters

\Drupal\group\Entity\Group $group: Group object.

1 string reference to 'OpignoGroupManagerController::trainingExport'
opigno_group_manager.routing.yml in ./opigno_group_manager.routing.yml
opigno_group_manager.routing.yml

File

src/Controller/OpignoGroupManagerController.php, line 1310

Class

OpignoGroupManagerController
Controller for all the actions of the Opigno group manager app.

Namespace

Drupal\opigno_group_manager\Controller

Code

public function trainingExport(Group $group) {
  $group_content = $group
    ->getContentEntities();
  $group_fields = $group
    ->getFields();
  $files_to_export = [];
  $modules_in_courses = [];
  $activity_ids = [];
  $skipped_delta = [
    1 => 0,
    2 => 0,
    3 => 0,
  ];
  foreach ($group_content as $entity) {
    if ($entity instanceof Group && $entity
      ->bundle() == 'opigno_course') {
      $course_content = $entity
        ->getContentEntities('opigno_module_group');
      $group_content = array_merge($group_content, $course_content);
      foreach ($course_content as $module) {
        $modules_in_courses[$module
          ->id()] = $entity
          ->id();
      }
    }
    elseif (in_array($entity
      ->bundle(), [
      'opigno_moxtra_meeting',
      'opigno_ilt',
    ])) {
      $skipped_entities[$entity
        ->id()] = $entity;
    }
  }
  foreach ($group_fields as $field_key => $field) {
    $data_structure[$group
      ->id()][$field_key] = $field
      ->getValue();
  }
  $training_name = $data_structure[$group
    ->id()]['label'][0]['value'];
  $format = 'json';
  $dir = 'sites/default/files/opigno-export';
  \Drupal::service('file_system')
    ->deleteRecursive($dir);
  \Drupal::service('file_system')
    ->prepareDirectory($dir, FileSystemInterface::MODIFY_PERMISSIONS | FileSystemInterface::CREATE_DIRECTORY);

  // Load image data.
  $img_filename = '';
  if (!empty($data_structure[$group
    ->id()]['field_learning_path_media_image'][0]['target_id'])) {
    $media = Media::load($data_structure[$group
      ->id()]['field_learning_path_media_image'][0]['target_id']);
    if (!empty($media)) {
      $file_id = $media
        ->get('field_media_image')
        ->getValue()[0]['target_id'];
      $file = File::load($file_id);
      if ($file) {
        $file_uri = $file
          ->getFileUri();
        $file_path = \Drupal::service('file_system')
          ->realpath($file_uri);
        $img_filename = $file
          ->id() . '-' . $file
          ->getFilename();
        $data_structure[$group
          ->id()]['field_learning_path_media_image'] = [
          'file_name' => $file
            ->getFilename(),
          'filemime' => $file
            ->getMimeType(),
          'status' => $file
            ->get('status')
            ->getValue()[0]['value'],
          'bundle' => $media
            ->bundle(),
          'media' => $media
            ->get('field_media_image')
            ->getValue(),
        ];
      }
    }
  }
  $serializer = \Drupal::service('serializer');
  $content = $serializer
    ->serialize($data_structure, $format);
  $filename = "export-training_{$training_name}_{$group->id()}.{$format}";
  $filename_path = "{$dir}/{$filename}";
  $files_to_export['training'] = $filename;
  $context['results']['file'] = \Drupal::service('file_system')
    ->saveData($content, $filename_path, FileSystemInterface::EXISTS_REPLACE);
  $new_filename = "opigno-training_{$training_name}_{$group->id()}.opi";
  $zip = new \ZipArchive();
  $zip
    ->open($dir . '/' . $new_filename, \ZipArchive::CREATE | \ZipArchive::OVERWRITE);
  $zip
    ->addFile($filename_path, $filename);
  if (!empty($img_filename) && !empty($file_path)) {
    $zip
      ->addFile($file_path, $img_filename);
  }
  foreach ($group_content as $entity) {
    if ($entity instanceof OpignoModule || $entity instanceof Group && $entity
      ->bundle() == 'opigno_course') {
      $eid = $entity
        ->id();
      if ($entity instanceof OpignoModule) {
        $activities = $entity
          ->getModuleActivities();
        $group_content_type_id = 'ContentTypeModule';
      }
      else {
        $activities = [];
        $group_content_type_id = 'ContentTypeCourse';
      }
      $module_fields = $entity
        ->getFields();
      $data_structure = [];
      $data_structure[$eid]['parent_links'] = [];
      foreach ($module_fields as $field_key => $field) {
        $data_structure[$eid][$field_key] = $field
          ->getValue();
      }
      $managed_content_array = OpignoGroupManagedContent::loadByProperties([
        'group_content_type_id' => $group_content_type_id,
        'entity_id' => $eid,
        'group_id' => $group
          ->id(),
      ]);
      $managed_content = reset($managed_content_array);
      $link_group_id = $group
        ->id();
      if (!$managed_content && isset($modules_in_courses[$entity
        ->id()])) {
        $managed_content_array = OpignoGroupManagedContent::loadByProperties([
          'group_content_type_id' => $group_content_type_id,
          'entity_id' => $entity
            ->id(),
          'group_id' => $modules_in_courses[$entity
            ->id()],
        ]);
        $managed_content = reset($managed_content_array);
        $data_structure[$eid]['course_rel'] = $modules_in_courses[$eid];
        $link_group_id = $modules_in_courses[$eid];
      }
      if ($managed_content) {
        $parent_links = $managed_content
          ->getParentsLinks();
        foreach ($parent_links as $link) {
          $parent_old_content = OpignoGroupManagedContent::load($link
            ->getParentContentId());
          $parent_module_id = $parent_old_content
            ->getEntityId();
          if (!empty($skipped_entities[$parent_module_id])) {

            // Recalculate position of module if some steps of Training were skipped.
            $coordinate_x = $managed_content
              ->getCoordinateX();
            $coordinate_y = $managed_content
              ->getCoordinateY();
            $skipped_delta[$coordinate_x]++;
            $managed_content
              ->setCoordinateY($coordinate_y - $skipped_delta[$coordinate_x]);
          }
          $parent_new_content_array = OpignoGroupManagedContent::loadByProperties([
            'group_content_type_id' => 'ContentTypeModule',
            'entity_id' => $parent_module_id,
            'group_id' => $link_group_id,
          ]);
          $parent_new_content = reset($parent_new_content_array);
          if ($parent_new_content) {
            $parent_id = $parent_new_content
              ->id();
            $link = [
              'group_id' => $link_group_id,
              'parent_content_id' => $parent_id,
              'child_content_id' => $eid,
              'required_score' => $link
                ->getRequiredScore(),
              'required_activities' => $link
                ->getRequiredActivities(),
            ];
            $data_structure[$eid]['parent_links'][] = $link;
          }
        }
      }
      $data_structure[$eid]['managed_content'] = $managed_content;
      if ($group_content_type_id == 'ContentTypeModule') {
        $entity_name = $data_structure[$entity
          ->id()]['name'][0]['value'];
        $entity_name = preg_replace('/[^a-zA-Z0-9-_\\.]/', '-', $entity_name);
        $filename = "export-module_{$entity_name}_{$entity->id()}.{$format}";
        $files_to_export['modules'][$entity_name . '_' . $entity
          ->id()] = $filename;
      }
      else {
        $entity_name = $data_structure[$entity
          ->id()]['label'][0]['value'];
        $entity_name = preg_replace('/[^a-zA-Z0-9-_\\.]/', '-', $entity_name);
        $filename = "export-course_{$entity_name}_{$entity->id()}.{$format}";
        $files_to_export['courses'][$entity_name . '_' . $entity
          ->id()] = $filename;
      }
      $content = $serializer
        ->serialize($data_structure, $format);
      $filename_path = "{$dir}/{$filename}";
      \Drupal::service('file_system')
        ->saveData($content, $filename_path, \Drupal\Core\File\FileSystemInterface::EXISTS_REPLACE);
      $zip
        ->addFile($filename_path, $filename);
      foreach ($activities as $activity) {
        $opigno_activity = OpignoActivity::load($activity->id);
        $fields = $opigno_activity
          ->getFields();
        $data_structure = [];
        $aid = $opigno_activity
          ->id();
        $activity_ids[$eid . '-' . $aid] = $aid;
        foreach ($fields as $field_key => $field) {
          $data_structure[$eid . '-' . $aid][$field_key] = $field
            ->getValue();
        }
        $max_score = [];
        if ($entity instanceof OpignoModule) {
          $max_score = $this
            ->getMaxScore($entity, $activity);
          $max_score = isset($max_score['max_score']) ? $max_score['max_score'] : 10;
        }
        if (empty($data_structure[$eid . '-' . $aid]['max_score'])) {
          $data_structure[$eid . '-' . $aid]['max_score'] = $max_score;
        }
        $activity_name = $data_structure[$eid . '-' . $aid]['name'][0]['value'];
        $activity_name = preg_replace('/[^a-zA-Z0-9-_\\.]/', '-', $activity_name);
        $filename = "export-activity_{$activity_name}_{$eid}_{$aid}.{$format}";
        $filename_path = "{$dir}/{$filename}";
        $files_to_export['activities'][$entity_name . '_' . $entity
          ->id()][] = $filename;
        switch ($opigno_activity
          ->bundle()) {
          case 'opigno_scorm':
            if (isset($opigno_activity
              ->get('opigno_scorm_package')->target_id)) {
              $file = File::load($opigno_activity
                ->get('opigno_scorm_package')->target_id);
              if ($file) {
                $file_uri = $file
                  ->getFileUri();
                $file_path = \Drupal::service('file_system')
                  ->realpath($file_uri);
                $scorm_filename = $file
                  ->id() . '-' . $file
                  ->getFilename();
                $data_structure[$eid . '-' . $aid]['files'][$scorm_filename] = [
                  'file_name' => $file
                    ->getFilename(),
                  'filemime' => $file
                    ->getMimeType(),
                  'status' => $file
                    ->get('status')
                    ->getValue()[0]['value'],
                ];
                $zip
                  ->addFile($file_path, $scorm_filename);
              }
            }
            break;
          case 'opigno_tincan':
            if (isset($opigno_activity
              ->get('opigno_tincan_package')->target_id)) {
              $file = File::load($opigno_activity
                ->get('opigno_tincan_package')->target_id);
              if ($file) {
                $file_uri = $file
                  ->getFileUri();
                $file_path = \Drupal::service('file_system')
                  ->realpath($file_uri);
                $tincan_filename = $file
                  ->id() . '-' . $file
                  ->getFilename();
                $data_structure[$eid . '-' . $aid]['files'][$tincan_filename] = [
                  'file_name' => $file
                    ->getFilename(),
                  'filemime' => $file
                    ->getMimeType(),
                  'status' => $file
                    ->get('status')
                    ->getValue()[0]['value'],
                ];
                $zip
                  ->addFile($file_path, $tincan_filename);
              }
            }
            break;
          case 'opigno_slide':
            if (isset($opigno_activity
              ->get('opigno_slide_pdf')->target_id)) {
              $media = Media::load($opigno_activity
                ->get('opigno_slide_pdf')->target_id);
              $file_id = $media
                ->get('field_media_file')
                ->getValue()[0]['target_id'];
              $file = File::load($file_id);
              if ($file) {
                $file_uri = $file
                  ->getFileUri();
                $file_path = \Drupal::service('file_system')
                  ->realpath($file_uri);
                $pdf_filename = $file
                  ->id() . '-' . $file
                  ->getFilename();
                $data_structure[$eid . '-' . $aid]['files'][$pdf_filename] = [
                  'file_name' => $file
                    ->getFilename(),
                  'filemime' => $file
                    ->getMimeType(),
                  'status' => $file
                    ->get('status')
                    ->getValue()[0]['value'],
                  'bundle' => $media
                    ->bundle(),
                ];
                $zip
                  ->addFile($file_path, $pdf_filename);
              }
            }
            break;
          case 'opigno_video':
            if (isset($opigno_activity
              ->get('field_video')->target_id)) {
              $file = File::load($opigno_activity
                ->get('field_video')->target_id);
              if ($file) {
                $file_uri = $file
                  ->getFileUri();
                $file_path = \Drupal::service('file_system')
                  ->realpath($file_uri);
                $video_filename = $file
                  ->id() . '-' . $file
                  ->getFilename();
                $data_structure[$eid . '-' . $aid]['files'][$video_filename] = [
                  'file_name' => $file
                    ->getFilename(),
                  'filemime' => $file
                    ->getMimeType(),
                  'status' => $file
                    ->get('status')
                    ->getValue()[0]['value'],
                ];
                $zip
                  ->addFile($file_path, $video_filename);
              }
            }
            break;
        }
        if ($opigno_activity
          ->bundle() == 'opigno_h5p') {
          $hp5_id = $data_structure[$eid . '-' . $aid]['opigno_h5p'][0]['h5p_content_id'];
          $h5p_content = H5PContent::load($hp5_id);
          $h5p_content
            ->getFilteredParameters();
          $hp5_archive = "interactive-content-{$hp5_id}.h5p";
          $zip
            ->addFile('sites/default/files/h5p/exports/' . $hp5_archive, $hp5_archive);
        }
        $content = $serializer
          ->serialize($data_structure, $format);
        $context['results']['file'] = \Drupal::service('file_system')
          ->saveData($content, $filename_path, \Drupal\Core\File\FileSystemInterface::EXISTS_REPLACE);
        $zip
          ->addFile($filename_path, $filename);
      }
      $skipped_entity = FALSE;
    }
  }

  // Export documents library.
  $main_tid = $group
    ->get('field_learning_path_folder')
    ->getString();
  $items_list = $this
    ->documentsLibraryList($main_tid);
  $folder_library = $dir . '/library';
  \Drupal::service('file_system')
    ->prepareDirectory($folder_library, FileSystemInterface::MODIFY_PERMISSIONS | FileSystemInterface::CREATE_DIRECTORY);
  $zip
    ->addEmptyDir('library');
  foreach ($items_list as $item) {
    if ($item['type'] == 'file') {
      $media = Media::load($item['id']);
      $filename = $media
        ->id() . '_media_' . $media
        ->label() . '.' . $format;
      $filename_path = "{$folder_library}/{$filename}";
      $files_to_export['files'][$item['id']]['media'] = $filename;
      $content = $serializer
        ->serialize($media, $format);
      $context['results']['file'] = \Drupal::service('file_system')
        ->saveData($content, $filename_path, \Drupal\Core\File\FileSystemInterface::EXISTS_REPLACE);
      $zip
        ->addFile($filename_path, 'library/' . $filename);
      $file_id = $media
        ->get('tft_file')
        ->getValue()[0]['target_id'];
      $file = File::load($file_id);
      if ($file) {
        $file_uri = $file
          ->getFileUri();
        $filename = $file
          ->id() . '-' . $file
          ->getFilename();
        $file_path = \Drupal::service('file_system')
          ->realpath($file_uri);
        $zip
          ->addFile($file_path, 'library/' . $filename);
        $filename = $file
          ->id() . '_file_' . $file
          ->label() . '.' . $format;
        $files_to_export['files'][$item['id']]['file'] = $filename;
        $filename_path = "{$folder_library}/{$filename}";
        $content = $serializer
          ->serialize($file, $format);
        $context['results']['file'] = \Drupal::service('file_system')
          ->saveData($content, $filename_path, \Drupal\Core\File\FileSystemInterface::EXISTS_REPLACE);
        $zip
          ->addFile($filename_path, 'library/' . $filename);
      }
    }
    elseif ($item['type'] == 'term') {
      $term = Term::load($item['id']);
      if ($term) {
        $filename = $term
          ->id() . '_' . $term
          ->label() . '.' . $format;
        $filename_path = "{$folder_library}/{$filename}";
        $files_to_export['terms'][] = $filename;
        $content = $serializer
          ->serialize($term, $format);
        $context['results']['file'] = \Drupal::service('file_system')
          ->saveData($content, $filename_path, \Drupal\Core\File\FileSystemInterface::EXISTS_REPLACE);
        $zip
          ->addFile($filename_path, 'library/' . $filename);
      }
    }
  }
  $content = $serializer
    ->serialize($files_to_export, $format);
  $filename = "list_of_files.{$format}";
  $filename_path = "{$dir}/{$filename}";
  $files_to_export['activities'][] = $filename;
  \Drupal::service('file_system')
    ->saveData($content, $filename_path, \Drupal\Core\File\FileSystemInterface::EXISTS_REPLACE);
  $zip
    ->addFile($filename_path, $filename);
  if (file_exists($filename_path)) {
    $zip
      ->close();
  }
  $headers = [
    'Content-Type' => 'application/opi',
    'Content-Disposition' => 'attachment; filename="' . $new_filename . '"',
  ];
  if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE')) {
    $headers['Cache-Control'] = 'must-revalidate, post-check=0, pre-check=0';
    $headers['Pragma'] = 'public';
  }
  else {
    $headers['Pragma'] = 'no-cache';
  }
  return new BinaryFileResponse($dir . '/' . $new_filename, 200, $headers);
}