Skip to content

Commit

Permalink
Merge pull request #5955 from christianbeeznest/ofaj-22199
Browse files Browse the repository at this point in the history
Migration: Fix resource migration and file handling for course documents - refs BT#22199
  • Loading branch information
christianbeeznest authored Dec 5, 2024
2 parents 7a938e6 + 70ae32d commit c2a6ba4
Show file tree
Hide file tree
Showing 3 changed files with 74 additions and 52 deletions.
30 changes: 13 additions & 17 deletions src/CoreBundle/Migrations/Schema/V200/Version20230913162700.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ public function up(Schema $schema): void
$resourceNodeRepo = $this->container->get(ResourceNodeRepository::class);

$q = $this->entityManager->createQuery('SELECT c FROM Chamilo\CoreBundle\Entity\Course c');
/*$updateConfigurations = [
$updateConfigurations = [
['table' => 'c_tool_intro', 'field' => 'intro_text'],
['table' => 'c_course_description', 'field' => 'content'],
['table' => 'c_quiz', 'fields' => ['description', 'text_when_finished']],
Expand All @@ -48,7 +48,7 @@ public function up(Schema $schema): void
['table' => 'c_survey', 'fields' => ['title', 'subtitle']],
['table' => 'c_survey_question', 'fields' => ['survey_question', 'survey_question_comment']],
['table' => 'c_survey_question_option', 'field' => 'option_text'],
];*/
];

/** @var Course $course */
foreach ($q->toIterable() as $course) {
Expand All @@ -59,9 +59,9 @@ public function up(Schema $schema): void
continue;
}

/* foreach ($updateConfigurations as $config) {
foreach ($updateConfigurations as $config) {
$this->updateContent($config, $courseDirectory, $courseId, $documentRepo);
}*/
}

$this->updateHtmlContent($courseDirectory, $courseId, $documentRepo, $resourceNodeRepo);
}
Expand Down Expand Up @@ -155,13 +155,6 @@ private function replaceOldURLsWithNew($itemDataText, $courseDirectory, $courseI

$documentPath = str_replace('/courses/'.$courseDirectory.'/document/', '/', $videoPath);

error_log('Debugging Replace URLs:');
error_log('Full URL: ' . $fullUrl);
error_log('Video Path: ' . $videoPath);
error_log('Actual Course Directory: ' . $actualCourseDirectory);
error_log('Processed Document Path: ' . $documentPath);

/*
$sql = "SELECT iid, path, resource_node_id FROM c_document WHERE c_id = $courseId AND path LIKE '$documentPath'";
$result = $this->connection->executeQuery($sql);
$documents = $result->fetchAllAssociative();
Expand All @@ -177,7 +170,7 @@ private function replaceOldURLsWithNew($itemDataText, $courseDirectory, $courseI
$contentText = str_replace($matches[0][$index], $replacement, $contentText);
}
}
}*/
}
}

return $contentText;
Expand Down Expand Up @@ -214,9 +207,10 @@ private function createNewDocument($videoPath, $courseId)
throw new Exception("Course with ID $courseId not found.");
}

$document = $documentRepo->findCourseResourceByTitle($title, $course->getResourceNode(), $course);
if (null !== $document) {
return $document;
$existingDocument = $documentRepo->findResourceByTitleInCourse($title, $course);
if ($existingDocument) {
error_log("Document '$title' already exists for course {$course->getId()}. Skipping creation.");
return $existingDocument;
}

if (file_exists($appCourseOldPath) && !is_dir($appCourseOldPath)) {
Expand All @@ -235,6 +229,7 @@ private function createNewDocument($videoPath, $courseId)

$documentRepo->addFileFromPath($document, $title, $appCourseOldPath);

error_log("Document '$title' successfully created for course $courseId.");
return $document;
}
$generalCoursesPath = $this->getUpdateRootPath().'/app/courses/';
Expand All @@ -259,9 +254,10 @@ private function createNewDocument($videoPath, $courseId)
return $document;
}

throw new Exception('File not found in any location.');
error_log("File '$title' not found for course $courseId. Skipping.");
return null;
} catch (Exception $e) {
error_log('Migration error: '.$e->getMessage());
error_log('Error in createNewDocument: ' . $e->getMessage());

return null;
}
Expand Down
81 changes: 46 additions & 35 deletions src/CoreBundle/Migrations/Schema/V200/Version20231022124700.php
Original file line number Diff line number Diff line change
Expand Up @@ -116,48 +116,59 @@ private function replaceURLParametersInContent(string $content): string
// Pattern to find and replace cidReq, id_session, and gidReq
$pattern = '/((https?:\/\/[^\/\s]*|)\/[^?\s]+?)\?(.*?)(cidReq=([a-zA-Z0-9_]+))((?:&|&)id_session=([0-9]+))?((?:&|&)gidReq=([0-9]+))?(.*)/i';

$newContent = @preg_replace_callback(
$pattern,
function ($matches) {
$code = $matches[5];

$courseId = null;
$sql = 'SELECT id FROM course WHERE code = :code ORDER BY id DESC LIMIT 1';
$stmt = $this->connection->executeQuery($sql, ['code' => $code]);
$course = $stmt->fetch();

if ($course) {
$courseId = $course['id'];
}
try {
$newContent = @preg_replace_callback(
$pattern,
function ($matches) {
$code = $matches[5] ?? null;

if (!$code) {
error_log('Missing cidReq in URL: ' . $matches[0]);
return $matches[0];
}

if (null === $courseId) {
return $matches[0]; // If the courseId is not found, return the original URL.
}
$courseId = null;
$sql = 'SELECT id FROM course WHERE code = :code ORDER BY id DESC LIMIT 1';
$stmt = $this->connection->executeQuery($sql, ['code' => $code]);
$course = $stmt->fetch();

if ($course) {
$courseId = $course['id'];
}

// Ensure sid and gid are always populated
$sessionId = isset($matches[7]) && !empty($matches[7]) ? $matches[7] : '0';
$groupId = isset($matches[9]) && !empty($matches[9]) ? $matches[9] : '0';
$remainingParams = isset($matches[10]) ? $matches[10] : '';
if (null === $courseId) {
error_log('Course ID not found for cidReq: ' . $code);
return $matches[0];
}

// Prepare new URL with updated parameters
$newParams = "cid=$courseId&sid=$sessionId&gid=$groupId";
$beforeCidReqParams = isset($matches[3]) ? $matches[3] : '';
// Ensure sid and gid are always populated
$sessionId = $matches[7] ?? '0';
$groupId = $matches[9] ?? '0';
$remainingParams = $matches[10] ?? '';

// Ensure other parameters are maintained
if (!empty($remainingParams)) {
$newParams .= '&'.ltrim($remainingParams, '&');
}
// Prepare new URL with updated parameters
$newParams = "cid=$courseId&sid=$sessionId&gid=$groupId";
$beforeCidReqParams = $matches[3] ?? '';

$finalUrl = $matches[1].'?'.$beforeCidReqParams.$newParams;
// Ensure other parameters are maintained
if (!empty($remainingParams)) {
$newParams .= '&' . ltrim($remainingParams, '&');
}

return str_replace('&', '&', $finalUrl); // Replace any remaining & with &
},
$content
);
$finalUrl = $matches[1].'?'.$beforeCidReqParams.$newParams;

if (PREG_NO_ERROR !== preg_last_error()) {
error_log('Error encountered in preg_replace_callback: '.preg_last_error());
$newContent = $content;
return str_replace('&', '&', $finalUrl);
},
$content
);

if (false === $newContent || null === $newContent) {
error_log('preg_replace_callback failed for content: ' . substr($content, 0, 500));
return $content;
}
} catch (Exception $e) {
error_log('Exception in replaceURLParametersInContent: ' . $e->getMessage());
return $content;
}

return $newContent;
Expand Down
15 changes: 15 additions & 0 deletions src/CoreBundle/Repository/ResourceRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -933,4 +933,19 @@ public function findByTitleAndParentResourceNode(string $title, int $parentResou
->getOneOrNullResult()
;
}

public function findResourceByTitleInCourse(
string $title,
Course $course,
?Session $session = null,
?CGroup $group = null
): ?ResourceInterface {
$qb = $this->getResourcesByCourse($course, $session, $group);

$this->addTitleQueryBuilder($title, $qb);

$qb->setMaxResults(1);

return $qb->getQuery()->getOneOrNullResult();
}
}

0 comments on commit c2a6ba4

Please sign in to comment.