Passed
Push — master ( 33172e...a587b8 )
by Julito
116:21
created

AbstractMigrationChamilo::adminExist()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 8
c 0
b 0
f 0
nc 2
nop 0
dl 0
loc 14
rs 10
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
68
    public function getAdmin(): User
69
    {
70
        $container = $this->getContainer();
71
        $em = $this->getEntityManager();
72
        $connection = $em->getConnection();
73
        $userRepo = $container->get(UserRepository::class);
74
75
        $sql = 'SELECT user_id FROM admin ORDER BY id LIMIT 1';
76
        $result = $connection->executeQuery($sql);
77
        $adminRow = $result->fetchAssociative();
78
        $adminId = $adminRow['user_id'];
79
80
        return $userRepo->find($adminId);
81
    }
82
83
    /**
84
     * @return EntityManager
85
     */
86
    public function getEntityManager()
87
    {
88
        if (empty($this->manager)) {
89
            //$params = $this->connection->getParams();
90
            /*
91
            $dbParams = [
92
                'driver' => 'pdo_mysql',
93
                'host' => $this->connection->getHost(),
94
                'user' => $this->connection->getUsername(),
95
                'password' => $this->connection->getPassword(),
96
                'dbname' => $this->connection->getDatabase(),
97
                'port' => $this->connection->getPort(),
98
            ];*/
99
            /*$database = new \Database();
100
            $database->connect(
101
                $params,
102
                __DIR__.'/../../',
103
                __DIR__.'/../../'
104
            );
105
            $this->manager = $database->getManager();*/
106
        }
107
108
        return $this->manager;
109
    }
110
111
    /**
112
     * Speeds up SettingsCurrent creation.
113
     *
114
     * @param string $variable            The variable itself
115
     * @param string $subKey              The subkey
116
     * @param string $type                The type of setting (text, radio, select, etc)
117
     * @param string $category            The category (Platform, User, etc)
118
     * @param string $selectedValue       The default value
119
     * @param string $title               The setting title string name
120
     * @param string $comment             The setting comment string name
121
     * @param string $scope               The scope
122
     * @param string $subKeyText          Text if there is a subKey
123
     * @param int    $accessUrl           What URL it is for
124
     * @param bool   $accessUrlChangeable Whether it can be changed on each url
125
     * @param bool   $accessUrlLocked     Whether the setting for the current URL is
126
     *                                    locked to the current value
127
     * @param array  $options             Optional array in case of a radio-type field,
128
     *                                    to insert options
129
     */
130
    public function addSettingCurrent(
131
        $variable,
132
        $subKey,
133
        $type,
134
        $category,
135
        $selectedValue,
136
        $title,
137
        $comment,
138
        $scope = '',
139
        $subKeyText = '',
140
        $accessUrl = 1,
141
        $accessUrlChangeable = false,
142
        $accessUrlLocked = true,
143
        $options = []
144
    ): void {
145
146
        $em = $this->getEntityManager();
147
        $setting = new SettingsCurrent();
148
        $setting
149
            ->setVariable($variable)
150
            ->setSubkey($subKey)
151
            ->setType($type)
152
            ->setCategory($category)
153
            ->setSelectedValue($selectedValue)
154
            ->setTitle($title)
155
            ->setComment($comment)
156
            ->setScope($scope)
157
            ->setSubkeytext($subKeyText)
158
            ->setUrl($accessUrl)
159
            ->setAccessUrlChangeable($accessUrlChangeable)
160
            ->setAccessUrlLocked($accessUrlLocked)
161
        ;
162
163
        $em->persist($setting);
164
165
        if (\count($options) > 0) {
166
            foreach ($options as $option) {
167
                if (empty($option['text'])) {
168
                    if ('true' === $option['value']) {
169
                        $option['text'] = 'Yes';
170
                    } else {
171
                        $option['text'] = 'No';
172
                    }
173
                }
174
175
                $settingOption = new SettingsOptions();
176
                $settingOption
177
                    ->setVariable($variable)
178
                    ->setValue($option['value'])
179
                    ->setDisplayText($option['text'])
180
                ;
181
182
                $em->persist($settingOption);
183
            }
184
        }
185
        $em->flush();
186
    }
187
188
    /**
189
     * @param string $variable
190
     */
191
    public function getConfigurationValue($variable)
192
    {
193
        global $_configuration;
194
        if (isset($_configuration[$variable])) {
195
            return $_configuration[$variable];
196
        }
197
198
        return false;
199
    }
200
201
    /**
202
     * Remove a setting completely.
203
     *
204
     * @param string $variable The setting variable name
205
     */
206
    public function removeSettingCurrent($variable): void
207
    {
208
        //to be implemented
209
    }
210
211
    public function addLegacyFileToResource(
212
        string $filePath,
213
        ResourceRepository $repo,
214
        AbstractResource $resource,
215
        $id,
216
        $fileName = '',
217
        $description = ''
218
    ): void {
219
        if (!is_dir($filePath)) {
220
            $class = \get_class($resource);
221
            $documentPath = basename($filePath);
222
            if (file_exists($filePath)) {
223
                $mimeType = mime_content_type($filePath);
224
                if (empty($fileName)) {
225
                    $fileName = basename($documentPath);
226
                }
227
                $file = new UploadedFile($filePath, $fileName, $mimeType, null, true);
228
                if ($file) {
0 ignored issues
show
introduced by
$file is of type Symfony\Component\HttpFoundation\File\UploadedFile, thus it always evaluated to true.
Loading history...
229
                    $repo->addFile($resource, $file);
230
                } else {
231
                    $this->warnIf(true, "Cannot migrate {$class} #{$id} path: {$documentPath} ");
232
                }
233
            } else {
234
                $this->warnIf(true, "Cannot migrate {$class} #'.{$id}.' file not found: {$documentPath}");
235
            }
236
        }
237
    }
238
239
    public function fixItemProperty(
240
        $tool,
241
        ResourceRepository $repo,
242
        $course,
243
        $admin,
244
        ResourceInterface $resource,
245
        $parent,
246
        array $items = []
247
    ) {
248
        $container = $this->getContainer();
249
        $doctrine = $container->get('doctrine');
250
        $em = $doctrine->getManager();
251
        /** @var Connection $connection */
252
        $connection = $em->getConnection();
253
254
        $courseId = $course->getId();
255
        $id = $resource->getResourceIdentifier();
256
257
        if (empty($items)) {
258
            $sql = "SELECT * FROM c_item_property
259
                    WHERE tool = '{$tool}' AND c_id = {$courseId} AND ref = {$id}";
260
            $result = $connection->executeQuery($sql);
261
            $items = $result->fetchAllAssociative();
262
        }
263
264
        // For some reason the resource doesnt have a c_item_property value.
265
        if (empty($items)) {
266
            return false;
267
        }
268
269
        $sessionRepo = $container->get(SessionRepository::class);
270
        $groupRepo = $container->get(CGroupRepository::class);
271
        $userRepo = $container->get(UserRepository::class);
272
273
        $resource->setParent($parent);
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

273
        $resource->/** @scrutinizer ignore-call */ 
274
                   setParent($parent);
Loading history...
274
        $resourceNode = null;
275
        $userList = [];
276
        $groupList = [];
277
        $sessionList = [];
278
        foreach ($items as $item) {
279
            $visibility = $item['visibility'];
280
            $userId = $item['insert_user_id'];
281
            $sessionId = $item['session_id'] ?? 0;
282
            $groupId = $item['to_group_id'] ?? 0;
283
284
            $newVisibility = ResourceLink::VISIBILITY_PENDING;
285
            // Old visibility (item property) is based in this switch:
286
            switch ($visibility) {
287
                case 0:
288
                    $newVisibility = ResourceLink::VISIBILITY_PENDING;
289
290
                    break;
291
                case 1:
292
                    $newVisibility = ResourceLink::VISIBILITY_PUBLISHED;
293
294
                    break;
295
                case 2:
296
                    $newVisibility = ResourceLink::VISIBILITY_DELETED;
297
298
                    break;
299
            }
300
301
            // If c_item_property.insert_user_id doesn't exist we use the first admin id.
302
            $user = null;
303
            if (isset($userList[$userId])) {
304
                $user = $userList[$userId];
305
            } else {
306
                if (!empty($userId)) {
307
                    $userFound = $userRepo->find($userId);
308
                    if ($userFound) {
309
                        $user = $userList[$userId] = $userRepo->find($userId);
310
                    }
311
                }
312
            }
313
314
            if (null === $user) {
315
                $user = $admin;
316
            }
317
318
            $session = null;
319
            if (!empty($sessionId)) {
320
                if (isset($sessionList[$sessionId])) {
321
                    $session = $sessionList[$sessionId];
322
                } else {
323
                    $session = $sessionList[$sessionId] = $sessionRepo->find($sessionId);
324
                }
325
            }
326
327
            $group = null;
328
            if (!empty($groupId)) {
329
                if (isset($groupList[$groupId])) {
330
                    $group = $groupList[$groupId];
331
                } else {
332
                    $group = $groupList[$groupId] = $groupRepo->find($groupId);
333
                }
334
            }
335
336
            if (null === $resourceNode) {
337
                $resourceNode = $repo->addResourceNode($resource, $user, $parent);
338
                $em->persist($resourceNode);
339
            }
340
            $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

340
            $resource->/** @scrutinizer ignore-call */ 
341
                       addCourseLink($course, $session, $group, $newVisibility);
Loading history...
341
            $em->persist($resource);
342
        }
343
344
        return true;
345
    }
346
}
347