Merge pull request #5818 from christianbeeznest/rna-22039

Migration: Handle missing users in migration by assigning files to fallback_user - refs BT#22039
pull/5838/head
christianbeeznest 12 months ago committed by GitHub
commit 5b64cf532b
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
  1. 91
      src/CoreBundle/Migrations/Schema/V200/Version20230720143000.php
  2. 6
      src/CoreBundle/Migrations/Schema/V200/Version20230720222140.php

@ -26,54 +26,71 @@ final class Version20230720143000 extends AbstractMigrationChamilo
$kernel = $this->container->get('kernel'); $kernel = $this->container->get('kernel');
$rootPath = $kernel->getProjectDir(); $rootPath = $kernel->getProjectDir();
$q = $this->entityManager->createQuery('SELECT u FROM Chamilo\CoreBundle\Entity\User u'); $fallbackUser = $this->getFallbackUser();
$directory = $this->getUpdateRootPath().'/app/upload/users/';
/** @var User $userEntity */
foreach ($q->toIterable() as $userEntity) {
$id = $userEntity->getId();
$path = "users/{$id}/";
$variable = 'split_users_upload_directory'; $variable = 'split_users_upload_directory';
// Query the 'selected_value' from the 'settings' table where the 'variable' is 'split_users_upload_directory'
$query = $this->entityManager->createQuery('SELECT s.selectedValue FROM Chamilo\CoreBundle\Entity\SettingsCurrent s WHERE s.variable = :variable') $query = $this->entityManager->createQuery('SELECT s.selectedValue FROM Chamilo\CoreBundle\Entity\SettingsCurrent s WHERE s.variable = :variable')
->setParameter('variable', $variable) ->setParameter('variable', $variable);
;
// Get the result of the query (it should return a single row with the 'selected_value' column)
$result = $query->getOneOrNullResult(); $result = $query->getOneOrNullResult();
$settingValueAsString = 'false'; $splitUsersUploadDirectory = $result['selectedValue'] ?? 'false';
if (null !== $result) {
// Convert the 'selected_value' to a string and store it in $settingValueAsString if ('true' === $splitUsersUploadDirectory) {
$settingValue = $result['selectedValue']; $parentDirectories = glob($directory.'*', GLOB_ONLYDIR);
$settingValueAsString = (string) $settingValue;
foreach ($parentDirectories as $parentDir) {
$firstDigit = basename($parentDir);
$subDirectories = glob($parentDir.'/*', GLOB_ONLYDIR);
foreach ($subDirectories as $userDir) {
$userId = basename($userDir);
$this->processUserDirectory($userId, $userDir, $fallbackUser, true);
}
}
} else {
$userDirectories = glob($directory.'*', GLOB_ONLYDIR);
foreach ($userDirectories as $userDir) {
$userId = basename($userDir);
$this->processUserDirectory($userId, $userDir, $fallbackUser, false);
}
}
}
private function processUserDirectory(string $userId, string $userDir, User $fallbackUser, bool $splitUsersUploadDirectory): void
{
$userEntity = $this->entityManager->getRepository(User::class)->find($userId);
$userToAssign = $userEntity ?? $fallbackUser;
if ($userEntity === null) {
error_log("User with ID {$userId} not found. Using fallback_user.");
} else {
error_log("Processing files for user with ID {$userId}.");
} }
// If the 'split_users_upload_directory' setting is 'true', adjust the path accordingly if ($splitUsersUploadDirectory) {
if ('true' === $settingValueAsString) { $baseDir = $userDir.'/';
$path = 'users/'.substr((string) $id, 0, 1).'/'.$id.'/'; } else {
$baseDir = $this->getUpdateRootPath().'/app/upload/users/'.$userId.'/';
} }
$baseDir = $this->getUpdateRootPath().'/app/upload/'.$path; error_log("Final path to check: {$baseDir}");
// Check if the base directory exists, if not, continue to the next user
if (!is_dir($baseDir)) { if (!is_dir($baseDir)) {
continue; error_log("Directory not found for user with ID {$userId}. Skipping.");
return;
} }
// Get all the files in the 'my_files' directory
$myFilesDir = $baseDir.'my_files/'; $myFilesDir = $baseDir.'my_files/';
$files = glob($myFilesDir.'*'); $files = glob($myFilesDir.'*');
// $files now contains a list of all files in the 'my_files' directory
foreach ($files as $file) { foreach ($files as $file) {
if (!is_file($file)) { if (!is_file($file)) {
continue; continue;
} }
$title = basename($file); $title = basename($file);
$queryBuilder = $this->entityManager->createQueryBuilder(); error_log("Processing file: {$file} for user with ID {$userToAssign->getId()}.");
// Build the query to join the ResourceNode and PersonalFile tables $queryBuilder = $this->entityManager->createQueryBuilder();
$queryBuilder $queryBuilder
->select('p') ->select('p')
->from(ResourceNode::class, 'n') ->from(ResourceNode::class, 'n')
@ -81,34 +98,34 @@ final class Version20230720143000 extends AbstractMigrationChamilo
->where('n.title = :title') ->where('n.title = :title')
->andWhere('n.creator = :creator') ->andWhere('n.creator = :creator')
->setParameter('title', $title) ->setParameter('title', $title)
->setParameter('creator', $id) ->setParameter('creator', $userToAssign->getId());
;
$result = $queryBuilder->getQuery()->getOneOrNullResult(); $result = $queryBuilder->getQuery()->getOneOrNullResult();
if ($result) { if ($result) {
// Skip creating a new entity and log a message error_log('MIGRATIONS :: '.$file.' (Skipped: Already exists) ...');
error_log('MIGRATIONS :: $file -- '.$file.' (Skipped: Already exists) ...');
continue; continue;
} }
error_log('MIGRATIONS :: $file -- '.$file.' ...'); error_log("MIGRATIONS :: Associating file {$file} to user with ID {$userToAssign->getId()}.");
// Create a new PersonalFile entity if it doesn't already exist
$personalFile = new PersonalFile(); $personalFile = new PersonalFile();
$personalFile->setTitle($title); // Set the file name as the title $personalFile->setTitle($title);
$personalFile->setCreator($userEntity); $personalFile->setCreator($userToAssign);
$personalFile->setParentResourceNode($userEntity->getResourceNode()->getId()); $personalFile->setParentResourceNode($userToAssign->getResourceNode()->getId());
$personalFile->setResourceName($title); $personalFile->setResourceName($title);
$mimeType = mime_content_type($file); $mimeType = mime_content_type($file);
$uploadedFile = new UploadedFile($file, $title, $mimeType, null, true); $uploadedFile = new UploadedFile($file, $title, $mimeType, null, true);
$personalFile->setUploadFile($uploadedFile); $personalFile->setUploadFile($uploadedFile);
$personalFile->addUserLink($userEntity); $personalFile->addUserLink($userToAssign);
// Save the object to the database // Save the object to the database
$this->entityManager->persist($personalFile); $this->entityManager->persist($personalFile);
$this->entityManager->flush(); $this->entityManager->flush();
} }
} }
private function getFallbackUser(): ?User
{
return $this->entityManager->getRepository(User::class)->findOneBy(['status' => User::ROLE_FALLBACK], ['id' => 'ASC']);
} }
} }

@ -27,6 +27,7 @@ final class Version20230720222140 extends AbstractMigrationChamilo
$userRepo = $this->container->get(UserRepository::class); $userRepo = $this->container->get(UserRepository::class);
$personalRepo = $this->container->get(PersonalFileRepository::class); $personalRepo = $this->container->get(PersonalFileRepository::class);
$fallbackUser = $userRepo->findOneBy(['status' => User::ROLE_FALLBACK], ['id' => 'ASC']);
$q = $this->entityManager->createQuery('SELECT s FROM Chamilo\CoreBundle\Entity\SocialPost s'); $q = $this->entityManager->createQuery('SELECT s FROM Chamilo\CoreBundle\Entity\SocialPost s');
@ -60,6 +61,11 @@ final class Version20230720222140 extends AbstractMigrationChamilo
// Output the user id, folder id, and filename // Output the user id, folder id, and filename
error_log('User ID: '.$userId.', Folder ID: '.$folderId.', Filename: '.$filename); error_log('User ID: '.$userId.', Folder ID: '.$folderId.', Filename: '.$filename);
$user = $userRepo->find($userId); $user = $userRepo->find($userId);
if (!$user) {
$user = $fallbackUser;
}
$personalFile = $personalRepo->getResourceByCreatorFromTitle( $personalFile = $personalRepo->getResourceByCreatorFromTitle(
$filename, $filename,
$user, $user,

Loading…
Cancel
Save