Passed
Pull Request — master (#5832)
by
unknown
09:10
created

Version20230913162700::recursiveFileSearch()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 5
c 0
b 0
f 0
nc 3
nop 2
dl 0
loc 10
rs 10
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\Course;
10
use Chamilo\CoreBundle\Migrations\AbstractMigrationChamilo;
11
use Chamilo\CoreBundle\Repository\Node\CourseRepository;
12
use Chamilo\CoreBundle\Repository\ResourceNodeRepository;
13
use Chamilo\CourseBundle\Entity\CDocument;
14
use Chamilo\CourseBundle\Repository\CDocumentRepository;
15
use Doctrine\DBAL\Schema\Schema;
16
use Exception;
17
use RecursiveDirectoryIterator;
18
use RecursiveIteratorIterator;
19
20
use const PHP_URL_PATH;
21
22
final class Version20230913162700 extends AbstractMigrationChamilo
23
{
24
    public function getDescription(): string
25
    {
26
        return 'Replace old document path by resource file path';
27
    }
28
29
    public function up(Schema $schema): void
30
    {
31
        $documentRepo = $this->container->get(CDocumentRepository::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

31
        /** @scrutinizer ignore-call */ 
32
        $documentRepo = $this->container->get(CDocumentRepository::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...
32
        $resourceNodeRepo = $this->container->get(ResourceNodeRepository::class);
33
34
        $q = $this->entityManager->createQuery('SELECT c FROM Chamilo\CoreBundle\Entity\Course c');
0 ignored issues
show
Bug introduced by
The method createQuery() 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

34
        /** @scrutinizer ignore-call */ 
35
        $q = $this->entityManager->createQuery('SELECT c FROM Chamilo\CoreBundle\Entity\Course c');

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...
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_course_description', 'field' => 'content'],
42
            ['table' => 'c_student_publication', 'field' => 'description'],
43
            ['table' => 'c_student_publication_comment', 'field' => 'comment'],
44
            ['table' => 'c_forum_category', 'field' => 'cat_comment'],
45
            ['table' => 'c_forum_forum', 'field' => 'forum_comment'],
46
            ['table' => 'c_forum_post', 'field' => 'post_text'],
47
            ['table' => 'c_glossary', 'field' => 'description'],
48
            ['table' => 'c_survey', 'fields' => ['title', 'subtitle']],
49
            ['table' => 'c_survey_question', 'fields' => ['survey_question', 'survey_question_comment']],
50
            ['table' => 'c_survey_question_option', 'field' => 'option_text'],
51
        ];
52
53
        /** @var Course $course */
54
        foreach ($q->toIterable() as $course) {
55
            $courseId = $course->getId();
56
            $courseDirectory = $course->getDirectory();
57
58
            if (empty($courseDirectory)) {
59
                continue;
60
            }
61
62
            foreach ($updateConfigurations as $config) {
63
                $this->updateContent($config, $courseDirectory, $courseId, $documentRepo);
64
            }
65
66
            $this->updateHtmlContent($courseDirectory, $courseId, $documentRepo, $resourceNodeRepo);
67
        }
68
    }
69
70
71
    private function updateContent($config, $courseDirectory, $courseId, $documentRepo): void
72
    {
73
        if (isset($config['field'])) {
74
            $fields = [$config['field']];
75
        } elseif (isset($config['fields'])) {
76
            $fields = $config['fields'];
77
        } else {
78
            throw new Exception('No field or fields specified for updating.');
79
        }
80
81
        foreach ($fields as $field) {
82
            $sql = "SELECT iid, {$field} FROM {$config['table']} WHERE c_id = {$courseId}";
83
            $result = $this->connection->executeQuery($sql);
84
            $items = $result->fetchAllAssociative();
85
86
            foreach ($items as $item) {
87
                $originalText = $item[$field];
88
                if (!empty($originalText)) {
89
                    $updatedText = $this->replaceOldURLsWithNew($originalText, $courseDirectory, $courseId, $documentRepo);
90
                    if ($originalText !== $updatedText) {
91
                        error_log("SIMULACIÓN: Actualizar campo {$field} en {$config['table']} para ID {$item['iid']}");
92
                        // Simular sin guardar cambios
93
                        // $sql = "UPDATE {$config['table']} SET {$field} = :newText WHERE iid = :id";
94
                        // $params = ['newText' => $updatedText, 'id' => $item['iid']];
95
                        // $this->connection->executeQuery($sql, $params);
96
                    }
97
                }
98
            }
99
        }
100
    }
101
102
    private function updateHtmlContent($courseDirectory, $courseId, $documentRepo, $resourceNodeRepo): void
103
    {
104
        $sql = "SELECT iid, resource_node_id FROM c_document WHERE filetype = 'file' AND resource_node_id IS NOT NULL";
105
        $result = $this->connection->executeQuery($sql);
106
        $items = $result->fetchAllAssociative();
107
108
        foreach ($items as $item) {
109
            /** @var CDocument $document */
110
            $document = $documentRepo->find($item['iid']);
111
            if (!$document) {
112
                continue;
113
            }
114
115
            $resourceNode = $document->getResourceNode();
116
117
            if (!$resourceNode || !$resourceNode->hasResourceFile()) {
118
                continue;
119
            }
120
121
            $resourceFile = $resourceNode->getResourceFiles()->first();
122
123
            if (!$resourceFile) {
124
                continue;
125
            }
126
127
            $filePath = $resourceFile->getTitle();
128
            if ('text/html' === $resourceFile->getMimeType()) {
129
                error_log("Verificando archivo HTML: $filePath");
130
131
                try {
132
                    $content = $resourceNodeRepo->getResourceNodeFileContent($resourceNode);
133
                    $updatedContent = $this->replaceOldURLsWithNew($content, $courseDirectory, $courseId, $documentRepo);
134
135
                    if ($content !== $updatedContent) {
136
                        error_log("SIMULACIÓN: Actualizar contenido HTML en {$filePath}");
137
                        // Simular sin guardar cambios
138
                        // $documentRepo->updateResourceFileContent($document, $updatedContent);
139
                        // $documentRepo->update($document);
140
                    }
141
                } catch (Exception $e) {
142
                    error_log("Error al procesar archivo $filePath: " . $e->getMessage());
143
                }
144
            }
145
        }
146
    }
147
148
    private function replaceOldURLsWithNew($itemDataText, $courseDirectory, $courseId, $documentRepo): array|string|null
149
    {
150
        $contentText = $itemDataText;
151
        $specificCoursePattern = '/(src|href)=["\']((https?:\/\/[^\/]+)?(\/courses\/([^\/]+)\/document\/[^"\']+\.\w+))["\']/i';
152
        preg_match_all($specificCoursePattern, $contentText, $matches);
153
154
        foreach ($matches[2] as $index => $fullUrl) {
155
            $videoPath = parse_url($fullUrl, PHP_URL_PATH) ?: $fullUrl;
156
            $actualCourseDirectory = $matches[5][$index];
157
            if ($actualCourseDirectory !== $courseDirectory) {
158
                $videoPath = preg_replace("/^\\/courses\\/$actualCourseDirectory\\//i", "/courses/$courseDirectory/", $videoPath);
159
            }
160
161
            $documentPath = str_replace('/courses/'.$courseDirectory.'/document/', '/', $videoPath);
162
163
            $sql = "SELECT iid, path, resource_node_id FROM c_document WHERE c_id = $courseId AND path LIKE '$documentPath'";
164
            $result = $this->connection->executeQuery($sql);
165
            $documents = $result->fetchAllAssociative();
166
167
            if (!empty($documents)) {
168
                $this->replaceDocumentLinks($documents, $documentRepo, $matches, $index, $videoPath, $courseId, $contentText);
169
            } else {
170
                $document = $this->createNewDocument($videoPath, $courseId);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $document is correct as $this->createNewDocument($videoPath, $courseId) targeting Chamilo\CoreBundle\Migra...00::createNewDocument() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
171
                if ($document) {
172
                    $newUrl = $documentRepo->getResourceFileUrl($document);
173
                    if ($newUrl) {
174
                        $replacement = $matches[1][$index].'="'.$newUrl.'"';
175
                        $contentText = str_replace($matches[0][$index], $replacement, $contentText);
176
                    }
177
                }
178
            }
179
        }
180
181
        return $contentText;
182
    }
183
184
    private function replaceDocumentLinks($documents, $documentRepo, $matches, $index, $videoPath, $courseId, &$contentText): void
185
    {
186
        foreach ($documents as $documentData) {
187
            $resourceNodeId = (int) $documentData['resource_node_id'];
188
            $documentFile = $documentRepo->getResourceFromResourceNode($resourceNodeId);
189
            if ($documentFile) {
190
                $newUrl = $documentRepo->getResourceFileUrl($documentFile);
191
                if (!empty($newUrl)) {
192
                    $patternForReplacement = '/'.preg_quote($matches[0][$index], '/').'/';
193
                    $replacement = $matches[1][$index].'="'.$newUrl.'"';
194
                    $contentText = preg_replace($patternForReplacement, $replacement, $contentText, 1);
195
                }
196
            }
197
        }
198
    }
199
200
    private function createNewDocument($videoPath, $courseId)
201
    {
202
        try {
203
            $documentRepo = $this->container->get(CDocumentRepository::class);
204
            $kernel = $this->container->get('kernel');
205
            $rootPath = $kernel->getProjectDir();
206
            $appCourseOldPath = $rootPath . '/app' . $videoPath;
207
            $title = basename($appCourseOldPath);
208
209
            $courseRepo = $this->container->get(CourseRepository::class);
210
            $course = $courseRepo->find($courseId);
211
            if (!$course) {
212
                throw new Exception("Course with ID $courseId not found.");
213
            }
214
215
            error_log("SIMULACIÓN: Intentando localizar archivo {$title} en la ruta esperada: {$appCourseOldPath}");
216
217
            // Verificar si el archivo existe en la ubicación esperada
218
            if (file_exists($appCourseOldPath) && !is_dir($appCourseOldPath)) {
219
                error_log("SIMULACIÓN: Archivo encontrado en ruta esperada: {$appCourseOldPath}");
220
                return null; // Retorna null en modo de solo lectura
221
            }
222
223
            // Buscar en directorios alternativos usando recursiveFileSearch
224
            $generalCoursesPath = $this->getUpdateRootPath() . '/app/courses/';
225
            $foundPath = $this->recursiveFileSearch($generalCoursesPath, $title);
226
            if ($foundPath) {
227
                // Registrar el valor de foundPath sin realizar ninguna operación de escritura
228
                error_log("SIMULACIÓN: Archivo encontrado en nueva ubicación: {$foundPath}");
229
            } else {
230
                error_log("SIMULACIÓN: Archivo {$title} no encontrado en {$generalCoursesPath}");
231
            }
232
233
            return null; // No realizar ninguna operación de creación
234
        } catch (Exception $e) {
235
            error_log('Error en la migración: ' . $e->getMessage());
236
            return null;
237
        }
238
    }
239
240
241
    private function recursiveFileSearch($directory, $title)
242
    {
243
        $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory));
244
        foreach ($iterator as $file) {
245
            if ($file->isFile() && $file->getFilename() === $title) {
246
                return $file->getRealPath();
247
            }
248
        }
249
250
        return null;
251
    }
252
}
253