Passed
Push — master ( 5f975d...198b2c )
by Julito
10:29
created

AbstractMigrationChamilo::fileExists()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 1
nc 3
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
/* For licensing terms, see /license.txt */
6
7
namespace Chamilo\CoreBundle\Migrations;
8
9
use Chamilo\CoreBundle\Entity\AbstractResource;
10
use Chamilo\CoreBundle\Entity\ResourceInterface;
11
use Chamilo\CoreBundle\Entity\ResourceLink;
12
use Chamilo\CoreBundle\Entity\SettingsCurrent;
13
use Chamilo\CoreBundle\Entity\SettingsOptions;
14
use Chamilo\CoreBundle\Entity\User;
15
use Chamilo\CoreBundle\Repository\Node\UserRepository;
16
use Chamilo\CoreBundle\Repository\ResourceRepository;
17
use Chamilo\CoreBundle\Repository\SessionRepository;
18
use Chamilo\CourseBundle\Repository\CGroupRepository;
19
use Doctrine\DBAL\Connection;
20
use Doctrine\Migrations\AbstractMigration;
21
use Doctrine\ORM\EntityManager;
22
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
23
use Symfony\Component\DependencyInjection\ContainerInterface;
24
use Symfony\Component\HttpFoundation\File\UploadedFile;
25
26
abstract class AbstractMigrationChamilo extends AbstractMigration implements ContainerAwareInterface
27
{
28
    public const BATCH_SIZE = 20;
29
30
    private ?EntityManager $manager = null;
31
    private ?ContainerInterface $container = null;
32
33
    public function setEntityManager(EntityManager $manager): void
34
    {
35
        $this->manager = $manager;
36
    }
37
38
    public function setContainer(ContainerInterface $container = null): void
39
    {
40
        $this->container = $container;
41
    }
42
43
    /**
44
     * @return ContainerInterface
45
     */
46
    public function getContainer()
47
    {
48
        return $this->container;
49
    }
50
51
    public function adminExist(): bool
52
    {
53
        $em = $this->getEntityManager();
54
        $connection = $em->getConnection();
55
56
        $sql = 'SELECT user_id FROM admin WHERE user_id IN (SELECT id FROM user) ORDER BY id LIMIT 1';
57
        $result = $connection->executeQuery($sql);
58
        $adminRow = $result->fetchAssociative();
59
60
        if (empty($adminRow)) {
61
            return false;
62
        }
63
64
        return true;
65
    }
66
67
    public function getAdmin(): User
68
    {
69
        $container = $this->getContainer();
70
        $em = $this->getEntityManager();
71
        $connection = $em->getConnection();
72
        $userRepo = $container->get(UserRepository::class);
73
74
        $sql = 'SELECT user_id FROM admin ORDER BY id LIMIT 1';
75
        $result = $connection->executeQuery($sql);
76
        $adminRow = $result->fetchAssociative();
77
        $adminId = $adminRow['user_id'];
78
79
        return $userRepo->find($adminId);
80
    }
81
82
    /**
83
     * @return EntityManager
84
     */
85
    public function getEntityManager()
86
    {
87
        return $this->getContainer()->get('doctrine')->getManager();
88
    }
89
90
    /**
91
     * Speeds up SettingsCurrent creation.
92
     *
93
     * @param string $variable            The variable itself
94
     * @param string $subKey              The subkey
95
     * @param string $type                The type of setting (text, radio, select, etc)
96
     * @param string $category            The category (Platform, User, etc)
97
     * @param string $selectedValue       The default value
98
     * @param string $title               The setting title string name
99
     * @param string $comment             The setting comment string name
100
     * @param string $scope               The scope
101
     * @param string $subKeyText          Text if there is a subKey
102
     * @param int    $accessUrl           What URL it is for
103
     * @param bool   $accessUrlChangeable Whether it can be changed on each url
104
     * @param bool   $accessUrlLocked     Whether the setting for the current URL is
105
     *                                    locked to the current value
106
     * @param array  $options             Optional array in case of a radio-type field,
107
     *                                    to insert options
108
     */
109
    public function addSettingCurrent(
110
        $variable,
111
        $subKey,
112
        $type,
113
        $category,
114
        $selectedValue,
115
        $title,
116
        $comment,
117
        $scope = '',
118
        $subKeyText = '',
119
        $accessUrl = 1,
120
        $accessUrlChangeable = false,
121
        $accessUrlLocked = true,
122
        $options = []
123
    ): void {
124
        $em = $this->getEntityManager();
125
        $setting = new SettingsCurrent();
126
        $setting
127
            ->setVariable($variable)
128
            ->setSubkey($subKey)
129
            ->setType($type)
130
            ->setCategory($category)
131
            ->setSelectedValue($selectedValue)
132
            ->setTitle($title)
133
            ->setComment($comment)
134
            ->setScope($scope)
135
            ->setSubkeytext($subKeyText)
136
            ->setUrl($accessUrl)
137
            ->setAccessUrlChangeable($accessUrlChangeable)
138
            ->setAccessUrlLocked($accessUrlLocked)
139
        ;
140
141
        $em->persist($setting);
142
143
        if (\count($options) > 0) {
144
            foreach ($options as $option) {
145
                if (empty($option['text'])) {
146
                    if ('true' === $option['value']) {
147
                        $option['text'] = 'Yes';
148
                    } else {
149
                        $option['text'] = 'No';
150
                    }
151
                }
152
153
                $settingOption = new SettingsOptions();
154
                $settingOption
155
                    ->setVariable($variable)
156
                    ->setValue($option['value'])
157
                    ->setDisplayText($option['text'])
158
                ;
159
160
                $em->persist($settingOption);
161
            }
162
        }
163
        $em->flush();
164
    }
165
166
    /**
167
     * @param string $variable
168
     */
169
    public function getConfigurationValue($variable)
170
    {
171
        global $_configuration;
172
        if (isset($_configuration[$variable])) {
173
            return $_configuration[$variable];
174
        }
175
176
        return false;
177
    }
178
179
    /**
180
     * Remove a setting completely.
181
     *
182
     * @param string $variable The setting variable name
183
     */
184
    public function removeSettingCurrent($variable): void
185
    {
186
        //to be implemented
187
    }
188
189
    public function addLegacyFileToResource(
190
        string $filePath,
191
        ResourceRepository $repo,
192
        AbstractResource $resource,
193
        $id,
194
        $fileName = '',
195
        $description = ''
196
    ): bool {
197
        $class = \get_class($resource);
198
        $documentPath = basename($filePath);
199
200
        if (is_dir($filePath) || (!is_dir($filePath) && !file_exists($filePath))) {
201
            $this->warnIf(true, "Cannot migrate {$class} #'.{$id}.' file not found: {$documentPath}");
202
203
            return false;
204
        }
205
206
        $mimeType = mime_content_type($filePath);
207
        if (empty($fileName)) {
208
            $fileName = basename($documentPath);
209
        }
210
        $file = new UploadedFile($filePath, $fileName, $mimeType, null, true);
211
        $repo->addFile($resource, $file);
212
213
        return true;
214
    }
215
216
    public function fixItemProperty(
217
        $tool,
218
        ResourceRepository $repo,
219
        $course,
220
        $admin,
221
        ResourceInterface $resource,
222
        $parentResource,
223
        array $items = []
224
    ) {
225
        $container = $this->getContainer();
226
        $doctrine = $container->get('doctrine');
227
        $em = $doctrine->getManager();
228
        /** @var Connection $connection */
229
        $connection = $em->getConnection();
230
231
        $courseId = $course->getId();
232
        $id = $resource->getResourceIdentifier();
233
234
        if (empty($items)) {
235
            $sql = "SELECT * FROM c_item_property
236
                    WHERE tool = '{$tool}' AND c_id = {$courseId} AND ref = {$id}";
237
            $result = $connection->executeQuery($sql);
238
            $items = $result->fetchAllAssociative();
239
        }
240
241
        // For some reason the resource doesnt have a c_item_property value.
242
        if (empty($items)) {
243
            return false;
244
        }
245
246
        $sessionRepo = $container->get(SessionRepository::class);
247
        $groupRepo = $container->get(CGroupRepository::class);
248
        $userRepo = $container->get(UserRepository::class);
249
250
        $resource->setParent($parentResource);
0 ignored issues
show
Bug introduced by
The method setParent() does not exist on Chamilo\CoreBundle\Entity\ResourceInterface. Since it exists in all sub-types, consider adding an abstract or default implementation to Chamilo\CoreBundle\Entity\ResourceInterface. ( Ignorable by Annotation )

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

250
        $resource->/** @scrutinizer ignore-call */ 
251
                   setParent($parentResource);
Loading history...
251
        $resourceNode = null;
252
        $userList = [];
253
        $groupList = [];
254
        $sessionList = [];
255
        foreach ($items as $item) {
256
            $visibility = (int) $item['visibility'];
257
            $userId = (int) $item['insert_user_id'];
258
            $sessionId = $item['session_id'] ?? 0;
259
            $groupId = $item['to_group_id'] ?? 0;
260
261
            $newVisibility = ResourceLink::VISIBILITY_PENDING;
262
            // Old visibility (item property) is based in this switch:
263
            switch ($visibility) {
264
                case 0:
265
                    $newVisibility = ResourceLink::VISIBILITY_PENDING;
266
267
                    break;
268
                case 1:
269
                    $newVisibility = ResourceLink::VISIBILITY_PUBLISHED;
270
271
                    break;
272
                case 2:
273
                    $newVisibility = ResourceLink::VISIBILITY_DELETED;
274
275
                    break;
276
            }
277
278
            // If c_item_property.insert_user_id doesn't exist we use the first admin id.
279
            $user = null;
280
            if (isset($userList[$userId])) {
281
                $user = $userList[$userId];
282
            } else {
283
                if (!empty($userId)) {
284
                    $userFound = $userRepo->find($userId);
285
                    if ($userFound) {
286
                        $user = $userList[$userId] = $userRepo->find($userId);
287
                    }
288
                }
289
            }
290
291
            if (null === $user) {
292
                $user = $admin;
293
            }
294
295
            $session = null;
296
            if (!empty($sessionId)) {
297
                if (isset($sessionList[$sessionId])) {
298
                    $session = $sessionList[$sessionId];
299
                } else {
300
                    $session = $sessionList[$sessionId] = $sessionRepo->find($sessionId);
301
                }
302
            }
303
304
            $group = null;
305
            if (!empty($groupId)) {
306
                if (isset($groupList[$groupId])) {
307
                    $group = $groupList[$groupId];
308
                } else {
309
                    $group = $groupList[$groupId] = $groupRepo->find($groupId);
310
                }
311
            }
312
313
            if (null === $resourceNode) {
314
                $resourceNode = $repo->addResourceNode($resource, $user, $parentResource);
315
                $em->persist($resourceNode);
316
            }
317
            $resource->addCourseLink($course, $session, $group, $newVisibility);
0 ignored issues
show
Bug introduced by
The method addCourseLink() does not exist on Chamilo\CoreBundle\Entity\ResourceInterface. It seems like you code against a sub-type of said class. However, the method does not exist in Chamilo\CoreBundle\Entity\User. Are you sure you never get one of those? ( Ignorable by Annotation )

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

317
            $resource->/** @scrutinizer ignore-call */ 
318
                       addCourseLink($course, $session, $group, $newVisibility);
Loading history...
318
            $em->persist($resource);
319
        }
320
321
        return true;
322
    }
323
324
    public function fileExists($filePath): bool
325
    {
326
        return file_exists($filePath) && !is_dir($filePath) && is_readable($filePath);
327
    }
328
}
329