Passed
Push — dependabot/npm_and_yarn/microm... ( e84ba6...f2f212 )
by
unknown
10:03
created

Version20241003120000::updateHtmlFiles()   B

Complexity

Conditions 11
Paths 12

Size

Total Lines 38
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 11
eloc 24
c 1
b 0
f 0
nc 12
nop 2
dl 0
loc 38
rs 7.3166

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
/* For licensing terms, see /license.txt */
6
7
namespace Chamilo\CoreBundle\Migrations\Schema\V200;
8
9
use Chamilo\CoreBundle\Entity\User;
10
use Chamilo\CoreBundle\Migrations\AbstractMigrationChamilo;
11
use Chamilo\CoreBundle\Repository\ResourceNodeRepository;
12
use Chamilo\CourseBundle\Entity\CDocument;
13
use Chamilo\CourseBundle\Repository\CDocumentRepository;
14
use Chamilo\CoreBundle\Repository\Node\PersonalFileRepository;
15
use Chamilo\CoreBundle\Repository\Node\UserRepository;
16
use Doctrine\DBAL\Schema\Schema;
17
use Exception;
18
19
final class Version20241003120000 extends AbstractMigrationChamilo
20
{
21
    public function getDescription(): string
22
    {
23
        return 'Update HTML content blocks and files to replace old user paths by fallbackUser paths for deleted users.';
24
    }
25
26
    public function up(Schema $schema): void
27
    {
28
        $this->entityManager->clear();
0 ignored issues
show
Bug introduced by
The method clear() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

28
        $this->entityManager->/** @scrutinizer ignore-call */ 
29
                              clear();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
29
30
        $userRepo = $this->container->get(UserRepository::class);
0 ignored issues
show
Bug introduced by
The method get() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

30
        /** @scrutinizer ignore-call */ 
31
        $userRepo = $this->container->get(UserRepository::class);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
31
        $personalRepo = $this->container->get(PersonalFileRepository::class);
32
        $fallbackUser = $userRepo->findOneBy(['status' => User::ROLE_FALLBACK], ['id' => 'ASC']);
33
34
        // Define the content fields to update
35
        $updateConfigurations = [
36
            ['table' => 'c_tool_intro', 'field' => 'intro_text'],
37
            ['table' => 'c_course_description', 'field' => 'content'],
38
            ['table' => 'c_quiz', 'fields' => ['description', 'text_when_finished']],
39
            ['table' => 'c_quiz_question', 'fields' => ['description', 'question']],
40
            ['table' => 'c_quiz_answer', 'fields' => ['answer', 'comment']],
41
            ['table' => 'c_student_publication', 'field' => 'description'],
42
            ['table' => 'c_student_publication_comment', 'field' => 'comment'],
43
            ['table' => 'c_forum_post', 'field' => 'post_text'],
44
            ['table' => 'c_glossary', 'field' => 'description'],
45
            ['table' => 'c_survey', 'fields' => ['title', 'subtitle']],
46
            ['table' => 'c_survey_question', 'fields' => ['survey_question', 'survey_question_comment']],
47
            ['table' => 'c_survey_question_option', 'field' => 'option_text'],
48
        ];
49
50
        // Process the tables and update the paths in the content
51
        foreach ($updateConfigurations as $config) {
52
            $this->updateContent($config, $fallbackUser, $personalRepo);
53
        }
54
55
        // Process the HTML files and update paths
56
        $this->updateHtmlFiles($fallbackUser, $personalRepo);
57
    }
58
59
    private function updateContent(array $config, $fallbackUser, $personalRepo): void
60
    {
61
        $fields = isset($config['field']) ? [$config['field']] : $config['fields'] ?? [];
62
63
        foreach ($fields as $field) {
64
            $sql = "SELECT iid, {$field} FROM {$config['table']}";
65
            $result = $this->connection->executeQuery($sql);
66
            $items = $result->fetchAllAssociative();
67
68
            foreach ($items as $item) {
69
                $content = $item[$field];
70
                if (is_string($content) && trim($content) !== '') {
71
                    // Process URLs in the content
72
                    $updatedContent = $this->processContentUrls($content, $fallbackUser, $personalRepo);
73
                    if ($content !== $updatedContent) {
74
                        $updateSql = "UPDATE {$config['table']} SET {$field} = :newContent WHERE iid = :id";
75
                        $this->connection->executeQuery($updateSql, ['newContent' => $updatedContent, 'id' => $item['iid']]);
76
                    }
77
                }
78
            }
79
        }
80
    }
81
82
    private function updateHtmlFiles($fallbackUser, $personalRepo): void
83
    {
84
        $sql = "SELECT iid, resource_node_id FROM c_document WHERE filetype = 'file'";
85
        $result = $this->connection->executeQuery($sql);
86
        $items = $result->fetchAllAssociative();
87
88
        $documentRepo = $this->container->get(CDocumentRepository::class);
89
        $resourceNodeRepo = $this->container->get(ResourceNodeRepository::class);
90
91
        foreach ($items as $item) {
92
            /** @var CDocument $document */
93
            $document = $documentRepo->find($item['iid']);
94
            if (!$document) {
95
                continue;
96
            }
97
98
            $resourceNode = $document->getResourceNode();
99
            if (!$resourceNode || !$resourceNode->hasResourceFile()) {
100
                continue;
101
            }
102
103
            $resourceFile = $resourceNode->getResourceFiles()->first();
104
            if (!$resourceFile || $resourceFile->getMimeType() !== 'text/html') {
105
                continue;
106
            }
107
108
            try {
109
                $content = $resourceNodeRepo->getResourceNodeFileContent($resourceNode);
110
                if (is_string($content) && trim($content) !== '') {
111
                    // Process URLs in the HTML content
112
                    $updatedContent = $this->processContentUrls($content, $fallbackUser, $personalRepo);
113
                    if ($content !== $updatedContent) {
114
                        $documentRepo->updateResourceFileContent($document, $updatedContent);
115
                        $documentRepo->update($document);
116
                    }
117
                }
118
            } catch (Exception $e) {
119
                error_log("Error processing file for document ID {$item['iid']}: " . $e->getMessage());
120
            }
121
        }
122
    }
123
124
    private function processContentUrls(string $content, $fallbackUser, $personalRepo): string
125
    {
126
        // Define the regular expression pattern to match URLs containing "/app/upload/users/"
127
        $pattern = '/(href|src)="[^"]*\/app\/upload\/users\/(\d+)\/(\d+)\/my_files\/([^\/"]+)"/i';
128
129
        // Use a callback function to process each matched URL
130
        return preg_replace_callback($pattern, function ($matches) use ($fallbackUser, $personalRepo) {
131
            $attribute = $matches[1];      // Capture whether it's a `href` or `src`
132
            $folderId = (int)$matches[2];  // Capture the first digit of the userId (folderId)
133
            $userId = (int)$matches[3];    // Capture the full userId
134
            $filename = urldecode($matches[4]);  // Decode the filename
135
136
            error_log("Processing file: $filename for userId: $userId (Folder ID: $folderId)");
137
138
            $user = $this->entityManager->getRepository(User::class)->find($userId);
139
            if (!$user) {
140
                // If the user doesn't exist, use the fallback user
141
                $user = $fallbackUser;
142
                error_log("User with ID $userId not found, using fallbackUser");
143
            }
144
145
            // Search for the personal file by name and creator (user)
146
            $personalFile = $personalRepo->getResourceByCreatorFromTitle($filename, $user, $user->getResourceNode());
147
            if ($personalFile !== null) {
148
                $newUrl = $personalRepo->getResourceFileUrl($personalFile);
149
                if (!empty($newUrl)) {
150
                    error_log("Replaced URL for $filename: $newUrl");
151
                    return "{$attribute}=\"{$newUrl}\"";
152
                }
153
            }
154
155
            // Return the original URL if no file was found
156
            return $matches[0];
157
        }, $content);
158
    }
159
}
160