Passed
Push — master ( 6f8cb0...cccadf )
by Julito
09:47
created

ImportCsv::run()   F

Complexity

Conditions 31
Paths > 20000

Size

Total Lines 187
Code Lines 129

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 31
eloc 129
nc 22190
nop 0
dl 0
loc 187
rs 0
c 0
b 0
f 0

How to fix   Long Method    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
/* For licensing terms, see /license.txt */
3
4
use Chamilo\CourseBundle\Entity\CCalendarEvent;
5
use Chamilo\CourseBundle\Entity\CItemProperty;
6
use Chamilo\PluginBundle\Entity\StudentFollowUp\CarePost;
7
use Fhaculty\Graph\Graph;
8
use Monolog\Handler\BufferHandler;
9
use Monolog\Handler\RotatingFileHandler;
10
use Monolog\Handler\StreamHandler;
11
use Monolog\Logger;
12
13
if (PHP_SAPI != 'cli') {
14
    die('Run this script through the command line or comment this line in the code');
15
}
16
17
if (file_exists('multiple_url_fix.php')) {
18
    require 'multiple_url_fix.php';
19
}
20
21
require_once __DIR__.'/../inc/global.inc.php';
22
23
ini_set('memory_limit', -1);
24
ini_set('max_execution_time', 0);
25
ini_set('log_errors', '1');
26
ini_set('display_errors', '1');
27
28
/**
29
 * Class ImportCsv.
30
 */
31
class ImportCsv
32
{
33
    public $test;
34
    public $defaultLanguage = 'dutch';
35
    public $extraFieldIdNameList = [
36
        'session' => 'external_session_id',
37
        'session_career' => 'external_career_id',
38
        'course' => 'external_course_id',
39
        'user' => 'external_user_id',
40
        'calendar_event' => 'external_calendar_event_id',
41
        'career' => 'external_career_id',
42
        'career_urls' => 'career_urls',
43
        'career_diagram' => 'career_diagram',
44
    ];
45
    public $defaultAdminId = 1;
46
    public $defaultSessionVisibility = 1;
47
48
    /**
49
     * When creating a user the expiration date is set to registration date + this value.
50
     *
51
     * @var int number of years
52
     */
53
    public $expirationDateInUserCreation = 1;
54
55
    public $batchSize = 20;
56
57
    /**
58
     * When updating a user the expiration date is set to update date + this value.
59
     *
60
     * @var int number of years
61
     */
62
    public $expirationDateInUserUpdate = 1;
63
    public $daysCoachAccessBeforeBeginning = 14;
64
    public $daysCoachAccessAfterBeginning = 14;
65
    public $conditions;
66
    private $logger;
67
    private $dumpValues;
68
    private $updateEmailToDummy;
69
70
    /**
71
     * @param Monolog\Logger $logger
72
     * @param array
73
     */
74
    public function __construct($logger, $conditions)
75
    {
76
        $this->logger = $logger;
77
        $this->conditions = $conditions;
78
        $this->updateEmailToDummy = false;
79
    }
80
81
    /**
82
     * @param bool $dump
83
     */
84
    public function setDumpValues($dump)
85
    {
86
        $this->dumpValues = $dump;
87
    }
88
89
    /**
90
     * @return bool
91
     */
92
    public function getDumpValues()
93
    {
94
        return $this->dumpValues;
95
    }
96
97
    /**
98
     * Runs the import process.
99
     */
100
    public function run()
101
    {
102
        global $_configuration;
103
104
        $value = api_get_configuration_value('import_csv_custom_url_id');
105
        if (!empty($value)) {
106
            $_configuration['access_url'] = $value;
107
        }
108
109
        $path = api_get_path(SYS_CODE_PATH).'cron/incoming/';
110
        if (!is_dir($path)) {
111
            echo "The folder! $path does not exits";
112
113
            return 0;
114
        }
115
116
        if ($this->getDumpValues()) {
117
            $this->dumpDatabaseTables();
118
        }
119
120
        echo 'Reading files: '.PHP_EOL.PHP_EOL;
121
122
        $files = scandir($path);
123
        $fileToProcess = [];
124
        $fileToProcessStatic = [];
125
        $teacherBackup = [];
126
        $groupBackup = [];
127
128
        $this->prepareImport();
129
130
        if (!empty($files)) {
131
            foreach ($files as $file) {
132
                $fileInfo = pathinfo($file);
133
                if (isset($fileInfo['extension']) && $fileInfo['extension'] === 'csv') {
134
                    // Checking teachers_yyyymmdd.csv,
135
                    // courses_yyyymmdd.csv, students_yyyymmdd.csv and sessions_yyyymmdd.csv
136
                    $parts = explode('_', $fileInfo['filename']);
137
                    $preMethod = ucwords($parts[1]);
138
                    $preMethod = str_replace('-static', 'Static', $preMethod);
139
                    $method = 'import'.$preMethod;
140
141
                    $isStatic = strpos($method, 'Static');
142
143
                    if ($method == 'importSessionsextidStatic') {
144
                        $method = 'importSessionsExtIdStatic';
145
                    }
146
147
                    if ($method == 'importCourseinsertStatic') {
148
                        $method = 'importSubscribeUserToCourse';
149
                    }
150
151
                    if ($method == 'importUnsubsessionsextidStatic') {
152
                        $method = 'importUnsubsessionsExtidStatic';
153
                    }
154
155
                    if ($method == 'importCareersdiagram') {
156
                        $method = 'importCareersDiagram';
157
                    }
158
159
                    if ($method == 'importCareersresults') {
160
                        $method = 'importCareersResults';
161
                    }
162
163
                    if ($method == 'importOpensessions') {
164
                        $method = 'importOpenSessions';
165
                    }
166
167
                    if ($method == 'importSubsessionsextidStatic') {
168
                        $method = 'importSubscribeUserToCourseSessionExtStatic';
169
                    }
170
                    if (method_exists($this, $method)) {
171
                        if ((
172
                                $method == 'importSubscribeStatic' ||
173
                                $method == 'importSubscribeUserToCourse'
174
                            ) ||
175
                            empty($isStatic)
176
                        ) {
177
                            $fileToProcess[$parts[1]][] = [
178
                                'method' => $method,
179
                                'file' => $path.$fileInfo['basename'],
180
                            ];
181
                        } else {
182
                            $fileToProcessStatic[$parts[1]][] = [
183
                                'method' => $method,
184
                                'file' => $path.$fileInfo['basename'],
185
                            ];
186
                        }
187
                    } else {
188
                        echo "Error - This file '$file' can't be processed.".PHP_EOL;
189
                        echo "Trying to call $method".PHP_EOL;
190
                        echo "The file have to has this format:".PHP_EOL;
191
                        echo "prefix_students_ddmmyyyy.csv, prefix_teachers_ddmmyyyy.csv, 
192
                        prefix_courses_ddmmyyyy.csv, prefix_sessions_ddmmyyyy.csv ".PHP_EOL;
193
                        exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
194
                    }
195
                }
196
            }
197
198
            if (empty($fileToProcess) && empty($fileToProcessStatic)) {
199
                echo 'Error - no files to process.';
200
201
                return 0;
202
            }
203
204
            $sections = [
205
                'students',
206
                'teachers',
207
                'courses',
208
                'sessions',
209
                'opensessions',
210
                'subscribe-static',
211
                'courseinsert-static',
212
                'unsubscribe-static',
213
                'care',
214
                'careers',
215
                'careersdiagram',
216
                'careersresults',
217
            ];
218
219
            foreach ($sections as $section) {
220
                if (isset($fileToProcess[$section]) && !empty($fileToProcess[$section])) {
221
                    $this->logger->addInfo("-- Import $section --");
222
                    $files = $fileToProcess[$section];
223
                    foreach ($files as $fileInfo) {
224
                        $method = $fileInfo['method'];
225
                        $file = $fileInfo['file'];
226
                        echo 'File: '.$file.PHP_EOL;
227
                        echo 'Method : '.$method.PHP_EOL;
228
                        echo PHP_EOL;
229
230
                        $this->logger->addInfo('====================================================');
231
                        $this->logger->addInfo("Reading file: $file");
232
                        $this->logger->addInfo("Loading method $method ");
233
                        if ($method == 'importSessions' || $method == 'importOpenSessions') {
234
                            $this->$method(
235
                                $file,
236
                                true,
237
                                $teacherBackup,
238
                                $groupBackup
239
                            );
240
                        } else {
241
                            $this->$method($file, true);
242
                        }
243
                        $this->logger->addInfo('--Finish reading file--');
244
                    }
245
                }
246
            }
247
248
            $sections = [
249
                'students-static',
250
                'teachers-static',
251
                'courses-static',
252
                'sessions-static',
253
                'sessionsextid-static',
254
                'unsubscribe-static',
255
                'unsubsessionsextid-static',
256
                'subsessionsextid-static',
257
                'calendar-static',
258
            ];
259
260
            foreach ($sections as $section) {
261
                if (isset($fileToProcessStatic[$section]) &&
262
                    !empty($fileToProcessStatic[$section])
263
                ) {
264
                    $this->logger->addInfo("-- Import static files $section --");
265
                    $files = $fileToProcessStatic[$section];
266
                    foreach ($files as $fileInfo) {
267
                        $method = $fileInfo['method'];
268
269
                        $file = $fileInfo['file'];
270
                        echo 'Static file: '.$file.PHP_EOL;
271
                        echo 'Method : '.$method.PHP_EOL;
272
                        echo PHP_EOL;
273
                        $this->logger->addInfo("Reading static file: $file");
274
                        $this->logger->addInfo("Loading method $method ");
275
                        $this->$method(
276
                            $file,
277
                            true,
278
                            $teacherBackup,
279
                            $groupBackup
280
                        );
281
                        $this->logger->addInfo('--Finish reading file--');
282
                    }
283
                }
284
            }
285
            $this->logger->addInfo('teacher backup');
286
            $this->logger->addInfo(print_r($teacherBackup, 1));
287
        }
288
    }
289
290
    /**
291
     * @param $file
292
     * @param bool $moveFile
293
     */
294
    public function importCare($file, $moveFile = false)
295
    {
296
        $data = Import::csv_reader($file);
297
        $counter = 1;
298
        $batchSize = $this->batchSize;
299
        $em = Database::getManager();
300
301
        if (!empty($data)) {
302
            $this->logger->addInfo(count($data)." records found.");
303
            $items = [];
304
            foreach ($data as $list) {
305
                $post = [];
306
                foreach ($list as $key => $value) {
307
                    $key = (string) trim($key);
308
                    // Remove utf8 bom
309
                    $key = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $key);
310
                    $post[$key] = $value;
311
                }
312
313
                if (empty($post)) {
314
                    continue;
315
                }
316
317
                $externalId = $post['External_care_id'];
318
                $items[$externalId] = $post;
319
            }
320
            ksort($items);
321
322
            foreach ($items as $row) {
323
                // Insert user
324
                //$insertUserInfo = api_get_user_info_from_username($row['Added_by']);
325
326
                // User about the post
327
                $userId = UserManager::get_user_id_from_original_id(
328
                    $row['Added_by'],
329
                    $this->extraFieldIdNameList['user']
330
                );
331
332
                $insertUserInfo = api_get_user_info($userId);
333
334
                if (empty($insertUserInfo)) {
335
                    $this->logger->addInfo("User: '".$row['Added_by']."' doesn't exists. Skip this entry.");
336
                    continue;
337
                }
338
                $insertUserInfo = api_get_user_entity($insertUserInfo['user_id']);
339
340
                // User about the post
341
                $userId = UserManager::get_user_id_from_original_id(
342
                    $row['External_user_id'],
343
                    $this->extraFieldIdNameList['user']
344
                );
345
346
                if (empty($userId)) {
347
                    $this->logger->addInfo("User does '".$row['External_user_id']."' not exists skip this entry.");
348
                    continue;
349
                }
350
351
                $userInfo = api_get_user_entity($userId);
352
353
                if (empty($userInfo)) {
354
                    $this->logger->addInfo("Chamilo user does not found: #".$userId."' ");
355
                    continue;
356
                }
357
358
                // Dates
359
                $createdAt = $this->createDateTime($row['Added_On']);
360
                $updatedAt = $this->createDateTime($row['Edited_on']);
361
362
                // Parent
363
                $parent = null;
364
                if (!empty($row['Parent_id'])) {
365
                    $parentId = $items[$row['Parent_id']];
366
                    $criteria = [
367
                        'externalCareId' => $parentId,
368
                    ];
369
                    $parent = $em->getRepository('ChamiloPluginBundle:StudentFollowUp\CarePost')->findOneBy($criteria);
370
                }
371
372
                // Tags
373
                $tags = explode(',', $row['Tags']);
374
375
                // Check if post already was added:
376
                $criteria = [
377
                    'externalCareId' => $row['External_care_id'],
378
                ];
379
                $post = $em->getRepository('ChamiloPluginBundle:StudentFollowUp\CarePost')->findOneBy($criteria);
380
381
                if (empty($post)) {
382
                    $post = new CarePost();
383
                    $this->logger->addInfo("New post will be created no match for externalCareId = ".$row['External_care_id']);
384
                }
385
386
                $contentDecoded = utf8_encode(base64_decode($row['Article']));
387
388
                $post
389
                    ->setTitle($row['Title'])
390
                    ->setContent($contentDecoded)
391
                    ->setExternalCareId($row['External_care_id'])
392
                    ->setCreatedAt($createdAt)
393
                    ->setUpdatedAt($updatedAt)
394
                    ->setPrivate((int) $row['Private'])
395
                    ->setInsertUser($insertUserInfo)
396
                    ->setExternalSource((int) $row['Source_is_external'])
397
                    ->setParent($parent)
398
                    ->setTags($tags)
399
                    ->setUser($userInfo)
400
                    ->setAttachment($row['Attachement'])
401
                ;
402
                $em->persist($post);
403
                $em->flush();
404
405
                $this->logger->addInfo("Post id saved #".$post->getId());
406
407
                if (($counter % $batchSize) === 0) {
408
                    $em->flush();
409
                    $em->clear(); // Detaches all objects from Doctrine!
410
                }
411
                $counter++;
412
            }
413
414
            $em->clear(); // Detaches all objects from Doctrine!
415
        }
416
    }
417
418
    /**
419
     * @return mixed
420
     */
421
    public function getUpdateEmailToDummy()
422
    {
423
        return $this->updateEmailToDummy;
424
    }
425
426
    /**
427
     * @param mixed $updateEmailToDummy
428
     */
429
    public function setUpdateEmailToDummy($updateEmailToDummy)
430
    {
431
        $this->updateEmailToDummy = $updateEmailToDummy;
432
    }
433
434
    /**
435
     * Change emails of all users except admins.
436
     */
437
    public function updateUsersEmails()
438
    {
439
        if ($this->getUpdateEmailToDummy() === true) {
440
            $sql = "UPDATE user SET email = CONCAT(username,'@example.com') WHERE id NOT IN (SELECT user_id FROM admin)";
441
            Database::query($sql);
442
        }
443
    }
444
445
    /**
446
     * Prepares extra fields before the import.
447
     */
448
    private function prepareImport()
449
    {
450
        // Create user extra field: extra_external_user_id
451
        UserManager::create_extra_field(
452
            $this->extraFieldIdNameList['user'],
453
            1,
454
            'External user id',
455
            null
456
        );
457
458
        // Create course extra field: extra_external_course_id
459
        CourseManager::create_course_extra_field(
460
            $this->extraFieldIdNameList['course'],
461
            1,
462
            'External course id',
463
            ''
464
        );
465
466
        CourseManager::create_course_extra_field(
467
            'disable_import_calendar',
468
            13,
469
            'Disable import calendar',
470
            ''
471
        );
472
473
        // Create session extra field extra_external_session_id
474
        SessionManager::create_session_extra_field(
475
            $this->extraFieldIdNameList['session'],
476
            1,
477
            'External session id'
478
        );
479
480
        SessionManager::create_session_extra_field(
481
            $this->extraFieldIdNameList['session_career'],
482
            1,
483
            'Career id'
484
        );
485
486
        // Create calendar_event extra field extra_external_session_id
487
        $extraField = new ExtraField('calendar_event');
488
        $extraField->save(
489
            [
490
                'field_type' => ExtraField::FIELD_TYPE_TEXT,
491
                'variable' => $this->extraFieldIdNameList['calendar_event'],
492
                'display_text' => 'External calendar event id',
493
            ]
494
        );
495
496
        $extraField = new ExtraField('career');
497
        $extraField->save(
498
            [
499
                'visible_to_self' => 1,
500
                'field_type' => ExtraField::FIELD_TYPE_TEXT,
501
                'variable' => $this->extraFieldIdNameList['career'],
502
                'display_text' => 'External career id',
503
            ]
504
        );
505
506
        $extraField->save(
507
            [
508
                'visible_to_self' => 1,
509
                'field_type' => ExtraField::FIELD_TYPE_TEXTAREA,
510
                'variable' => $this->extraFieldIdNameList['career_diagram'],
511
                'display_text' => 'Career diagram',
512
            ]
513
        );
514
515
        $extraField->save(
516
            [
517
                'visible_to_self' => 1,
518
                'field_type' => ExtraField::FIELD_TYPE_TEXTAREA,
519
                'variable' => $this->extraFieldIdNameList['career_urls'],
520
                'display_text' => 'Career urls',
521
            ]
522
        );
523
    }
524
525
    /**
526
     * @param string $file
527
     */
528
    private function moveFile($file)
529
    {
530
        $moved = str_replace('incoming', 'treated', $file);
531
532
        if ($this->test) {
533
            $result = 1;
534
        } else {
535
            $result = rename($file, $moved);
536
        }
537
538
        if ($result) {
539
            $this->logger->addInfo("Moving file to the treated folder: $file");
540
        } else {
541
            $this->logger->addError(
542
                "Error - Cant move file to the treated folder: $file"
543
            );
544
        }
545
    }
546
547
    /**
548
     * @param array $row
549
     *
550
     * @return array
551
     */
552
    private function cleanUserRow($row)
553
    {
554
        $row['lastname'] = $row['LastName'];
555
        $row['firstname'] = $row['FirstName'];
556
        $row['email'] = $row['Email'];
557
        $row['username'] = $row['UserName'];
558
        $row['password'] = $row['Password'];
559
        $row['auth_source'] = isset($row['AuthSource']) ? $row['AuthSource'] : PLATFORM_AUTH_SOURCE;
560
        $row['official_code'] = $row['OfficialCode'];
561
        $row['phone'] = isset($row['PhoneNumber']) ? $row['PhoneNumber'] : '';
562
563
        if (isset($row['StudentID'])) {
564
            $row['extra_'.$this->extraFieldIdNameList['user']] = $row['StudentID'];
565
        }
566
567
        if (isset($row['TeacherID'])) {
568
            $row['extra_'.$this->extraFieldIdNameList['user']] = $row['TeacherID'];
569
        }
570
571
        return $row;
572
    }
573
574
    /**
575
     * @param array $row
576
     *
577
     * @return array
578
     */
579
    private function cleanCourseRow($row)
580
    {
581
        $row['title'] = $row['Title'];
582
        $row['course_code'] = $row['Code'];
583
        $row['course_category'] = $row['CourseCategory'];
584
        $row['email'] = $row['Teacher'];
585
        $row['language'] = $row['Language'];
586
        $row['visibility'] = isset($row['Visibility']) ? $row['Visibility'] : COURSE_VISIBILITY_REGISTERED;
587
588
        $row['teachers'] = [];
589
        if (isset($row['Teacher']) && !empty($row['Teacher'])) {
590
            $this->logger->addInfo("Teacher list found: ".$row['Teacher']);
591
            $teachers = explode(',', $row['Teacher']);
592
            if (!empty($teachers)) {
593
                foreach ($teachers as $teacherUserName) {
594
                    $teacherUserName = trim($teacherUserName);
595
                    $userInfo = api_get_user_info_from_username($teacherUserName);
596
                    if (!empty($userInfo)) {
597
                        $this->logger->addInfo("Username found: $teacherUserName");
598
                        $row['teachers'][] = $userInfo['user_id'];
599
                    }
600
                }
601
            }
602
        }
603
604
        if (isset($row['CourseID'])) {
605
            $row['extra_'.$this->extraFieldIdNameList['course']] = $row['CourseID'];
606
        }
607
608
        return $row;
609
    }
610
611
    /**
612
     * File to import.
613
     *
614
     * @param string $file
615
     */
616
    private function importTeachersStatic($file)
617
    {
618
        $this->importTeachers($file, true);
619
    }
620
621
    /**
622
     * File to import.
623
     *
624
     * @param string $file
625
     * @param bool   $moveFile
626
     */
627
    private function importTeachers($file, $moveFile = true)
628
    {
629
        $this->fixCSVFile($file);
630
        $data = Import::csvToArray($file);
631
632
        /* Unique identifier: official-code username.
633
        Email address and password should never get updated. *ok
634
        The only fields that I can think of that should update if the data changes in the csv file are FirstName and LastName. *ok
635
        A slight edit of these fields should be taken into account. ???
636
        Adding teachers is no problem, but deleting them shouldn’t be automated, but we should get a log of “to delete teachers”.
637
        We’ll handle that manually if applicable.
638
        No delete!
639
        */
640
        $language = $this->defaultLanguage;
641
642
        if (!empty($data)) {
643
            $this->logger->addInfo(count($data)." records found.");
644
            $expirationDateOnCreation = api_get_utc_datetime(strtotime("+".intval($this->expirationDateInUserCreation)."years"));
645
            $expirationDateOnUpdate = api_get_utc_datetime(strtotime("+".intval($this->expirationDateInUserUpdate)."years"));
646
647
            $batchSize = $this->batchSize;
648
            $em = Database::getManager();
649
            $counter = 1;
650
            foreach ($data as $row) {
651
                $row = $this->cleanUserRow($row);
652
653
                $user_id = UserManager::get_user_id_from_original_id(
654
                    $row['extra_'.$this->extraFieldIdNameList['user']],
655
                    $this->extraFieldIdNameList['user']
656
                );
657
                $userInfo = [];
658
                $userInfoByOfficialCode = null;
659
660
                if (!empty($user_id)) {
661
                    $userInfo = api_get_user_info($user_id);
662
                    $userInfoByOfficialCode = api_get_user_info_from_official_code($row['official_code']);
663
                }
664
665
                if (empty($userInfo) && empty($userInfoByOfficialCode)) {
666
                    // Create user
667
                    $userId = UserManager::create_user(
668
                        $row['firstname'],
669
                        $row['lastname'],
670
                        COURSEMANAGER,
671
                        $row['email'],
672
                        $row['username'],
673
                        $row['password'],
674
                        $row['official_code'],
675
                        $language, //$row['language'],
676
                        $row['phone'],
677
                        null, //$row['picture'], //picture
678
                        $row['auth_source'], // ?
679
                        $expirationDateOnCreation, //'0000-00-00 00:00:00', //$row['expiration_date'], //$expiration_date = '0000-00-00 00:00:00',
680
                        1, //active
681
                        0,
682
                        null, // extra
683
                        null, //$encrypt_method = '',
684
                        false //$send_mail = false
685
                    );
686
687
                    $row['extra_mail_notify_invitation'] = 1;
688
                    $row['extra_mail_notify_message'] = 1;
689
                    $row['extra_mail_notify_group_message'] = 1;
690
691
                    if ($userId) {
692
                        foreach ($row as $key => $value) {
693
                            if (substr($key, 0, 6) == 'extra_') {
694
                                //an extra field
695
                                UserManager::update_extra_field_value(
696
                                    $userId,
697
                                    substr($key, 6),
698
                                    $value
699
                                );
700
                            }
701
                        }
702
                        $this->logger->addInfo("Teachers - User created: ".$row['username']);
703
                    } else {
704
                        $this->logger->addError("Teachers - User NOT created: ".$row['username']." ".$row['firstname']." ".$row['lastname']);
705
                        $this->logger->addError(strip_tags(Display::getFlashToString()));
706
                        Display::cleanFlashMessages();
707
                    }
708
                } else {
709
                    if (empty($userInfo)) {
710
                        $this->logger->addError("Teachers - Can't update user :".$row['username']);
711
                        continue;
712
                    }
713
714
                    // Update user
715
                    $result = UserManager::update_user(
716
                        $userInfo['user_id'],
717
                        $row['firstname'], // <<-- changed
718
                        $row['lastname'], // <<-- changed
719
                        $userInfo['username'],
720
                        null, //$password = null,
721
                        $row['auth_source'],
722
                        $userInfo['email'],
723
                        COURSEMANAGER,
724
                        $userInfo['official_code'],
725
                        $userInfo['phone'],
726
                        $userInfo['picture_uri'],
727
                        $expirationDateOnUpdate,
728
                        $userInfo['active'],
729
                        null, //$creator_id = null,
730
                        0, //$hr_dept_id = 0,
731
                        null, // $extra = null,
732
                        null, //$language = 'english',
733
                        null, //$encrypt_method = '',
734
                        false, //$send_email = false,
735
                        0 //$reset_password = 0
736
                    );
737
738
                    if ($result) {
739
                        foreach ($row as $key => $value) {
740
                            if (substr($key, 0, 6) == 'extra_') {
741
                                //an extra field
742
                                UserManager::update_extra_field_value(
743
                                    $userInfo['user_id'],
744
                                    substr($key, 6),
745
                                    $value
746
                                );
747
                            }
748
                        }
749
                        $this->logger->addInfo("Teachers - User updated: ".$row['username']);
750
                    } else {
751
                        $this->logger->addError("Teachers - User not updated: ".$row['username']);
752
                    }
753
                }
754
755
                if (($counter % $batchSize) === 0) {
756
                    $em->flush();
757
                    $em->clear(); // Detaches all objects from Doctrine!
758
                }
759
                $counter++;
760
            }
761
762
            $em->clear(); // Detaches all objects from Doctrine!
763
        }
764
765
        if ($moveFile) {
766
            $this->moveFile($file);
767
        }
768
769
        $this->updateUsersEmails();
770
    }
771
772
    /**
773
     * @param string $file
774
     */
775
    private function importStudentsStatic($file)
776
    {
777
        $this->importStudents($file, true);
778
    }
779
780
    /**
781
     * @param string $file
782
     * @param bool   $moveFile
783
     */
784
    private function importStudents($file, $moveFile = true)
785
    {
786
        $this->fixCSVFile($file);
787
        $data = Import::csvToArray($file);
788
789
        /*
790
         * Another users import.
791
        Unique identifier: official code and username . ok
792
        Password should never get updated. ok
793
        If an update should need to occur (because it changed in the .csv),
794
        we’ll want that logged. We will handle this manually in that case.
795
        All other fields should be updateable, though passwords should of course not get updated. ok
796
        If a user gets deleted (not there anymore),
797
        He should be set inactive one year after the current date.
798
        So I presume you’ll just update the expiration date.
799
        We want to grant access to courses up to a year after deletion.
800
         */
801
        $timeStart = microtime(true);
802
803
        $batchSize = $this->batchSize;
804
        $em = Database::getManager();
805
806
        if (!empty($data)) {
807
            $language = $this->defaultLanguage;
808
            $this->logger->addInfo(count($data)." records found.");
809
810
            $expirationDateOnCreate = api_get_utc_datetime(
811
                strtotime("+".intval($this->expirationDateInUserCreation)."years")
812
            );
813
            $expirationDateOnUpdate = api_get_utc_datetime(
814
                strtotime("+".intval($this->expirationDateInUserUpdate)."years")
815
            );
816
817
            $counter = 1;
818
            $secondsInYear = 365 * 24 * 60 * 60;
819
820
            foreach ($data as $row) {
821
                $row = $this->cleanUserRow($row);
822
                $user_id = UserManager::get_user_id_from_original_id(
823
                    $row['extra_'.$this->extraFieldIdNameList['user']],
824
                    $this->extraFieldIdNameList['user']
825
                );
826
827
                $userInfo = [];
828
                $userInfoByOfficialCode = null;
829
                if (!empty($user_id)) {
830
                    $userInfo = api_get_user_info($user_id, false, true);
831
                    $userInfoByOfficialCode = api_get_user_info_from_official_code($row['official_code']);
832
                }
833
834
                $userInfoFromUsername = api_get_user_info_from_username($row['username']);
835
                if (!empty($userInfoFromUsername)) {
836
                    $extraFieldValue = new ExtraFieldValue('user');
837
                    $extraFieldValues = $extraFieldValue->get_values_by_handler_and_field_variable(
838
                        $userInfoFromUsername['user_id'],
839
                        $this->extraFieldIdNameList['user']
840
                    );
841
842
                    if (!empty($extraFieldValues)) {
843
                        $value = 0;
844
                        foreach ($extraFieldValues as $extraFieldValue) {
845
                            $value = $extraFieldValue['value'];
846
                        }
847
                        if (!empty($user_id) && $value != $user_id) {
848
                            $emails = api_get_configuration_value('cron_notification_help_desk');
849
                            if (!empty($emails)) {
850
                                $this->logger->addInfo('Preparing email to users in configuration: "cron_notification_help_desk"');
851
                                $subject = 'User not added due to same username';
852
                                $body = 'Cannot add username: "'.$row['username'].'" 
853
                                    with external_user_id: '.$row['extra_'.$this->extraFieldIdNameList['user']].'
854
                                    because '.$userInfoFromUsername['username'].' with external_user_id '.$value.' exists on the portal';
855
                                $this->logger->addInfo($body);
856
                                foreach ($emails as $email) {
857
                                    api_mail_html('', $email, $subject, $body);
858
                                }
859
                            }
860
                        }
861
                    }
862
                }
863
864
                if (empty($userInfo) && empty($userInfoByOfficialCode)) {
865
                    // Create user
866
                    $result = UserManager::create_user(
867
                        $row['firstname'],
868
                        $row['lastname'],
869
                        STUDENT,
870
                        $row['email'],
871
                        $row['username'],
872
                        $row['password'],
873
                        $row['official_code'],
874
                        $language, //$row['language'],
875
                        $row['phone'],
876
                        null, //$row['picture'], //picture
877
                        $row['auth_source'], // ?
878
                        $expirationDateOnCreate,
879
                        1, //active
880
                        0,
881
                        null, // extra
882
                        null, //$encrypt_method = '',
883
                        false //$send_mail = false
884
                    );
885
886
                    $row['extra_mail_notify_invitation'] = 1;
887
                    $row['extra_mail_notify_message'] = 1;
888
                    $row['extra_mail_notify_group_message'] = 1;
889
890
                    if ($result) {
891
                        foreach ($row as $key => $value) {
892
                            if (substr($key, 0, 6) === 'extra_') {
893
                                //an extra field
894
                                UserManager::update_extra_field_value(
895
                                    $result,
896
                                    substr($key, 6),
897
                                    $value
898
                                );
899
                            }
900
                        }
901
                        $this->logger->addInfo("Students - User created: ".$row['username']);
902
                    } else {
903
                        $this->logger->addError("Students - User NOT created: ".$row['username']." ".$row['firstname']." ".$row['lastname']);
904
                        $this->logger->addError(strip_tags(Display::getFlashToString()));
905
                        Display::cleanFlashMessages();
906
                    }
907
                } else {
908
                    if (empty($userInfo)) {
909
                        $this->logger->addError("Students - Can't update user :".$row['username']);
910
                        continue;
911
                    }
912
913
                    if (isset($row['action']) && $row['action'] === 'delete') {
914
                        // Inactive one year later
915
                        $userInfo['expiration_date'] = api_get_utc_datetime(api_strtotime(time() + $secondsInYear));
916
                    }
917
918
                    $password = $row['password']; // change password
919
                    $email = $row['email']; // change email
920
                    $resetPassword = 2; // allow password change
921
922
                    // Conditions that disables the update of password and email:
923
                    if (isset($this->conditions['importStudents'])) {
924
                        if (isset($this->conditions['importStudents']['update']) &&
925
                            isset($this->conditions['importStudents']['update']['avoid'])
926
                        ) {
927
                            // Blocking email update -
928
                            // 1. Condition
929
                            $avoidUsersWithEmail = $this->conditions['importStudents']['update']['avoid']['email'];
930
                            if ($userInfo['email'] != $row['email'] && in_array($row['email'], $avoidUsersWithEmail)) {
931
                                $this->logger->addInfo("Students - User email is not updated : ".$row['username']." because the avoid conditions (email).");
932
                                // Do not change email keep the old email.
933
                                $email = $userInfo['email'];
934
                            }
935
936
                            // 2. Condition
937
                            if (!in_array($userInfo['email'], $avoidUsersWithEmail) && !in_array($row['email'], $avoidUsersWithEmail)) {
938
                                $email = $userInfo['email'];
939
                            }
940
941
                            // 3. Condition
942
                            if (in_array($userInfo['email'], $avoidUsersWithEmail) && !in_array($row['email'], $avoidUsersWithEmail)) {
943
                                $email = $row['email'];
944
                            }
945
946
                            // Blocking password update
947
                            //$avoidUsersWithPassword = $this->conditions['importStudents']['update']['avoid']['password'];
948
949
                            /*if (isset($row['password'])) {
950
                                $user = api_get_user_entity($userInfo['id']);
951
                                $encoded = UserManager::encryptPassword(
952
                                    $row['password'],
953
                                    $user
954
                                );
955
956
                                if ($userInfo['password'] != $encoded &&
957
                                    in_array($row['password'], $avoidUsersWithPassword)
958
                                ) {
959
                                    $this->logger->addInfo(
960
                                        "Students - User password is not updated: ".$row['username']." because the avoid conditions (password)."
961
                                    );
962
                                    $password = null;
963
                                    $resetPassword = 0; // disallow password change
964
                                }
965
                            }*/
966
                        }
967
                    }
968
969
                    // Always disallow password change during update
970
                    $password = null;
971
                    $resetPassword = 0; // disallow password change
972
973
                    // Update user
974
                    $result = UserManager::update_user(
975
                        $userInfo['user_id'],
976
                        $row['firstname'], // <<-- changed
977
                        $row['lastname'], // <<-- changed
978
                        $row['username'], // <<-- changed
979
                        $password, //$password = null,
980
                        $row['auth_source'],
981
                        $email,
982
                        STUDENT,
983
                        $userInfo['official_code'],
984
                        $userInfo['phone'],
985
                        $userInfo['picture_uri'],
986
                        $expirationDateOnUpdate,
987
                        $userInfo['active'],
988
                        null, //$creator_id = null,
989
                        0, //$hr_dept_id = 0,
990
                        null, // $extra = null,
991
                        null, //$language = 'english',
992
                        null, //$encrypt_method = '',
993
                        false, //$send_email = false,
994
                        $resetPassword //$reset_password = 0
995
                    );
996
997
                    if ($result) {
998
                        if ($row['username'] != $userInfo['username']) {
999
                            $this->logger->addInfo("Students - Username was changes from '".$userInfo['username']."' to '".$row['username']."' ");
1000
                        }
1001
                        foreach ($row as $key => $value) {
1002
                            if (substr($key, 0, 6) === 'extra_') {
1003
                                //an extra field
1004
                                UserManager::update_extra_field_value(
1005
                                    $userInfo['user_id'],
1006
                                    substr($key, 6),
1007
                                    $value
1008
                                );
1009
                            }
1010
                        }
1011
                        $this->logger->addInfo("Students - User updated: ".$row['username']);
1012
                    } else {
1013
                        $this->logger->addError("Students - User NOT updated: ".$row['username']." ".$row['firstname']." ".$row['lastname']);
1014
                    }
1015
                }
1016
1017
                if (($counter % $batchSize) === 0) {
1018
                    $em->flush();
1019
                    $em->clear(); // Detaches all objects from Doctrine!
1020
                    $this->logger->addInfo("Detaches all objects");
1021
                }
1022
                $counter++;
1023
            }
1024
            $em->clear(); // Detaches all objects from Doctrine!
1025
        }
1026
1027
        $timeEnd = microtime(true);
1028
        $executionTime = round(($timeEnd - $timeStart) / 60, 2);
1029
        $this->logger->addInfo("Execution Time for process students: $executionTime Min");
1030
1031
        if ($moveFile) {
1032
            $this->moveFile($file);
1033
        }
1034
1035
        $this->updateUsersEmails();
1036
    }
1037
1038
    /**
1039
     * @param string $file
1040
     */
1041
    private function importCoursesStatic($file, $moveFile, &$teacherBackup = [], &$groupBackup = [])
1042
    {
1043
        $this->importCourses($file, true, $teacherBackup, $groupBackup);
1044
    }
1045
1046
    /**
1047
     * @param string $file
1048
     * @param bool   $moveFile
1049
     *
1050
     * @return int
1051
     */
1052
    private function importCalendarStatic($file, $moveFile = true)
1053
    {
1054
        $this->fixCSVFile($file);
1055
1056
        $this->updateUsersEmails();
1057
        $data = Import::csvToArray($file);
1058
1059
        if (!empty($data)) {
1060
            $this->logger->addInfo(count($data).' records found.');
1061
            $eventsToCreate = [];
1062
            $errorFound = false;
1063
1064
            $courseExtraFieldValue = new ExtraFieldValue('course');
1065
1066
            foreach ($data as $row) {
1067
                $sessionId = null;
1068
                $externalSessionId = null;
1069
                if (isset($row['external_sessionID'])) {
1070
                    $externalSessionId = $row['external_sessionID'];
1071
                    $sessionId = SessionManager::getSessionIdFromOriginalId(
1072
                        $externalSessionId,
1073
                        $this->extraFieldIdNameList['session']
1074
                    );
1075
                }
1076
1077
                $courseCode = null;
1078
                if (isset($row['coursecode'])) {
1079
                    $courseCode = $row['coursecode'];
1080
                }
1081
                $courseInfo = api_get_course_info($courseCode);
1082
1083
                $item = $courseExtraFieldValue->get_values_by_handler_and_field_variable(
1084
                    $courseInfo['real_id'],
1085
                    'disable_import_calendar'
1086
                );
1087
1088
                if (!empty($item) && isset($item['value']) && $item['value'] == 1) {
1089
                    $this->logger->addInfo(
1090
                        "Course '".$courseInfo['code']."' has 'disable_import_calendar' turn on. Skip"
1091
                    );
1092
                    $errorFound = true;
1093
                }
1094
1095
                if (empty($courseInfo)) {
1096
                    $this->logger->addInfo("Course '$courseCode' does not exists");
1097
                } else {
1098
                    if ($courseInfo['visibility'] == COURSE_VISIBILITY_HIDDEN) {
1099
                        $this->logger->addInfo("Course '".$courseInfo['code']."' has hidden visiblity. Skip");
1100
                        $errorFound = true;
1101
                    }
1102
                }
1103
1104
                if (empty($sessionId)) {
1105
                    $this->logger->addInfo("external_sessionID: $externalSessionId does not exists.");
1106
                }
1107
                $teacherId = null;
1108
                $sessionInfo = [];
1109
                if (!empty($sessionId) && !empty($courseInfo)) {
1110
                    $sessionInfo = api_get_session_info($sessionId);
1111
                    $courseIncluded = SessionManager::relation_session_course_exist(
1112
                        $sessionId,
1113
                        $courseInfo['real_id']
1114
                    );
1115
1116
                    if ($courseIncluded == false) {
1117
                        $this->logger->addInfo(
1118
                            "Course '$courseCode' is not included in session: $sessionId"
1119
                        );
1120
                        $errorFound = true;
1121
                    } else {
1122
                        $teachers = CourseManager::get_coach_list_from_course_code(
1123
                            $courseInfo['code'],
1124
                            $sessionId
1125
                        );
1126
1127
                        // Getting first teacher.
1128
                        if (!empty($teachers)) {
1129
                            $teacher = current($teachers);
1130
                            $teacherId = $teacher['user_id'];
1131
                        } else {
1132
                            $teacherId = $sessionInfo['id_coach'];
1133
                        }
1134
                    }
1135
                } else {
1136
                    $errorFound = true;
1137
                }
1138
1139
                if (empty($teacherId)) {
1140
                    $errorFound = true;
1141
                    $this->logger->addInfo(
1142
                        "No teacher found in course code : '$courseCode' and session: '$sessionId'"
1143
                    );
1144
                }
1145
1146
                $date = $row['date'];
1147
                $startTime = $row['time_start'];
1148
                $endTime = $row['time_end'];
1149
                $title = $row['title'];
1150
                $comment = $row['comment'];
1151
                $color = isset($row['color']) ? $row['color'] : '';
1152
1153
                $startDateYear = substr($date, 0, 4);
1154
                $startDateMonth = substr($date, 4, 2);
1155
                $startDateDay = substr($date, 6, 8);
1156
1157
                $startDate = $startDateYear.'-'.$startDateMonth.'-'.$startDateDay.' '.$startTime.':00';
1158
                $endDate = $startDateYear.'-'.$startDateMonth.'-'.$startDateDay.' '.$endTime.':00';
1159
1160
                if (!api_is_valid_date($startDate) || !api_is_valid_date($endDate)) {
1161
                    $this->logger->addInfo("Verify your dates:  '$startDate' : '$endDate' ");
1162
                    $errorFound = true;
1163
                }
1164
1165
                // Check session dates
1166
                if ($sessionInfo && !empty($sessionInfo['access_start_date'])) {
1167
                    $date = new \DateTime($sessionInfo['access_start_date']);
1168
                    $interval = new \DateInterval('P7D');
1169
                    $date->sub($interval);
1170
                    if ($date->getTimestamp() > time()) {
1171
                        $this->logger->addInfo(
1172
                            "Calendar event # ".$row['external_calendar_itemID']." 
1173
                            in session [$externalSessionId] was not added 
1174
                            because the startdate is more than 7 days in the future: ".$sessionInfo['access_start_date']
1175
                        );
1176
                        $errorFound = true;
1177
                    }
1178
                }
1179
1180
                if ($errorFound == false) {
1181
                    $eventsToCreate[] = [
1182
                        'start' => $startDate,
1183
                        'end' => $endDate,
1184
                        'title' => $title,
1185
                        'sender_id' => $teacherId,
1186
                        'course_id' => $courseInfo['real_id'],
1187
                        'session_id' => $sessionId,
1188
                        'comment' => $comment,
1189
                        'color' => $color,
1190
                        $this->extraFieldIdNameList['calendar_event'] => $row['external_calendar_itemID'],
1191
                    ];
1192
                }
1193
                $errorFound = false;
1194
            }
1195
1196
            if (empty($eventsToCreate)) {
1197
                $this->logger->addInfo('No events to add');
1198
1199
                return 0;
1200
            }
1201
1202
            $extraFieldValue = new ExtraFieldValue('calendar_event');
1203
            $extraFieldName = $this->extraFieldIdNameList['calendar_event'];
1204
            $externalEventId = null;
1205
1206
            $extraField = new ExtraField('calendar_event');
1207
            $extraFieldInfo = $extraField->get_handler_field_info_by_field_variable($extraFieldName);
1208
1209
            if (empty($extraFieldInfo)) {
1210
                $this->logger->addInfo(
1211
                    "No calendar event extra field created: $extraFieldName"
1212
                );
1213
1214
                return 0;
1215
            }
1216
1217
            $this->logger->addInfo('Ready to insert # '.count($eventsToCreate).' events');
1218
            $batchSize = $this->batchSize;
1219
            $counter = 1;
1220
            $em = Database::getManager();
1221
            $eventStartDateList = [];
1222
            $eventEndDateList = [];
1223
            $report = [
1224
                'mail_sent' => 0,
1225
                'mail_not_sent_announcement_exists' => 0,
1226
                'mail_not_sent_because_date' => 0,
1227
            ];
1228
1229
            $eventsToCreateFinal = [];
1230
            foreach ($eventsToCreate as $event) {
1231
                $update = false;
1232
                $item = null;
1233
                if (!isset($event[$extraFieldName])) {
1234
                    $this->logger->addInfo('No external_calendar_itemID found. Skipping ...');
1235
                    continue;
1236
                } else {
1237
                    $externalEventId = $event[$extraFieldName];
1238
                    if (empty($externalEventId)) {
1239
                        $this->logger->addInfo('external_calendar_itemID was set but empty. Skipping ...');
1240
                        continue;
1241
                    }
1242
1243
                    $item = $extraFieldValue->get_item_id_from_field_variable_and_field_value(
1244
                        $extraFieldName,
1245
                        $externalEventId,
1246
                        false,
1247
                        false,
1248
                        false
1249
                    );
1250
1251
                    if (!empty($item)) {
1252
                        $update = true;
1253
                    }
1254
                }
1255
1256
                $courseInfo = api_get_course_info_by_id($event['course_id']);
1257
                $event['course_info'] = $courseInfo;
1258
                $event['update'] = $update;
1259
                $event['item'] = $item;
1260
1261
                $calendarEvent = null;
1262
                /* Check if event changed of course code */
1263
                if (!empty($item) && isset($item['item_id']) && !empty($item['item_id'])) {
1264
                    /** @var CCalendarEvent $calendarEvent */
1265
                    $calendarEvent = $em->getRepository('ChamiloCourseBundle:CCalendarEvent')->find($item['item_id']);
1266
                }
1267
1268
                if ($calendarEvent) {
1269
                    $this->logger->addInfo('Calendar event found '.$item['item_id']);
1270
                    if ($calendarEvent->getCId() != $courseInfo['real_id']) {
1271
                        $this->logger->addInfo('Move from course #'.$calendarEvent->getCId().' to #'.$courseInfo['real_id']);
1272
                        // Seems that the course id changed in the csv
1273
                        $calendarEvent->setCId($courseInfo['real_id']);
1274
                        $em->persist($calendarEvent);
1275
                        $em->flush();
1276
1277
                        $criteria = [
1278
                            'tool' => 'calendar_event',
1279
                            'ref' => $item['item_id'],
1280
                        ];
1281
                        /** @var CItemProperty $itemProperty */
1282
                        $itemProperty = $em->getRepository('ChamiloCourseBundle:CItemProperty')->findOneBy($criteria);
1283
                        $courseEntity = $em->getRepository('ChamiloCoreBundle:Course')->find($courseInfo['real_id']);
1284
                        if ($itemProperty && $courseEntity) {
1285
                            $itemProperty->setCourse($courseEntity);
1286
                            $em->persist($itemProperty);
1287
                            $em->flush();
1288
                        }
1289
                    }
1290
1291
                    // Checking if session still exists
1292
                    $calendarSessionId = (int) $calendarEvent->getSessionId();
1293
                    if (!empty($calendarSessionId)) {
1294
                        $calendarSessionInfo = api_get_session_info($calendarSessionId);
1295
                        if (empty($calendarSessionInfo)) {
1296
                            $calendarId = (int) $calendarEvent->getIid();
1297
1298
                            // Delete calendar events because the session was deleted!
1299
                            $this->logger->addInfo(
1300
                                "Delete event # $calendarId because session # $calendarSessionId doesn't exist"
1301
                            );
1302
1303
                            $sql = "DELETE FROM c_calendar_event 
1304
                                    WHERE iid = $calendarId AND session_id = $calendarSessionId";
1305
                            Database::query($sql);
1306
                            $this->logger->addInfo($sql);
1307
1308
                            $sql = "DELETE FROM c_item_property 
1309
                                    WHERE 
1310
                                        tool = 'calendar_event' AND 
1311
                                        ref = $calendarSessionId AND 
1312
                                        session_id = $calendarSessionId";
1313
                            Database::query($sql);
1314
                            $this->logger->addInfo($sql);
1315
                        }
1316
                    }
1317
                } else {
1318
                    $this->logger->addInfo('Calendar event not found '.$item['item_id']);
1319
                }
1320
1321
                $event['external_event_id'] = $externalEventId;
1322
                if (isset($eventStartDateList[$courseInfo['real_id']]) &&
1323
                    isset($eventStartDateList[$courseInfo['real_id']][$event['session_id']])
1324
                ) {
1325
                    $currentItemDate = api_strtotime($event['start']);
1326
                    $firstDate = $eventStartDateList[$courseInfo['real_id']][$event['session_id']];
1327
                    if ($currentItemDate < api_strtotime($firstDate)) {
1328
                        $eventStartDateList[$courseInfo['real_id']][$event['session_id']] = $event['start'];
1329
                        $eventEndDateList[$courseInfo['real_id']][$event['session_id']] = $event['end'];
1330
                    }
1331
                } else {
1332
                    // First time
1333
                    $eventStartDateList[$courseInfo['real_id']][$event['session_id']] = $event['start'];
1334
                    $eventEndDateList[$courseInfo['real_id']][$event['session_id']] = $event['end'];
1335
                }
1336
                $eventsToCreateFinal[] = $event;
1337
            }
1338
1339
            $eventAlreadySent = [];
1340
1341
            $tpl = new Template(null, false, false, false, false, false, false);
1342
1343
            foreach ($eventsToCreateFinal as $event) {
1344
                $courseInfo = $event['course_info'];
1345
                $item = $event['item'];
1346
                $update = $event['update'];
1347
                $externalEventId = $event['external_event_id'];
1348
                $info = 'Course: '.$courseInfo['real_id'].' ('.$courseInfo['code'].') - Session: '.$event['session_id'].' external event id: '.$externalEventId;
1349
1350
                $agenda = new Agenda(
1351
                    'course',
1352
                    $event['sender_id'],
1353
                    $courseInfo['real_id'],
1354
                    $event['session_id']
1355
                );
1356
                $agenda->set_course($courseInfo);
1357
                $agenda->setSessionId($event['session_id']);
1358
                $agenda->setSenderId($event['sender_id']);
1359
                $agenda->setIsAllowedToEdit(true);
1360
                $eventComment = $event['comment'];
1361
                $color = $event['color'];
1362
1363
                // To use the event comment you need
1364
                // ALTER TABLE c_calendar_event ADD COLUMN comment TEXT;
1365
                // add in configuration.php allow_agenda_event_comment = true
1366
                if (empty($courseInfo)) {
1367
                    $this->logger->addInfo(
1368
                        "No course found for event #$externalEventId Course #".$event['course_id']." Skipping ..."
1369
                    );
1370
                    continue;
1371
                }
1372
1373
                if (empty($event['sender_id'])) {
1374
                    $this->logger->addInfo(
1375
                        "No sender found for event #$externalEventId Send #".$event['sender_id']." Skipping ..."
1376
                    );
1377
                    continue;
1378
                }
1379
1380
                // Taking first element of course-session event
1381
                $alreadyAdded = false;
1382
                $firstDate = $eventStartDateList[$courseInfo['real_id']][$event['session_id']];
1383
                $firstEndDate = $eventEndDateList[$courseInfo['real_id']][$event['session_id']];
1384
1385
                if (isset($eventAlreadySent[$courseInfo['real_id']]) &&
1386
                    isset($eventAlreadySent[$courseInfo['real_id']][$event['session_id']])
1387
                ) {
1388
                    $alreadyAdded = true;
1389
                } else {
1390
                    $eventAlreadySent[$courseInfo['real_id']][$event['session_id']] = true;
1391
                }
1392
1393
                // Working days (Mon-Fri)see BT#12156#note-16
1394
                $days = 3;
1395
                $startDatePlusDays = api_strtotime("$days weekdays");
1396
1397
                /*
1398
                $timePart = date('H:i:s', api_strtotime('now'));
1399
                $datePart = date('Y-m-d', api_strtotime("$days weekdays"));
1400
                $startDatePlusDays = "$timePart $datePart";
1401
                */
1402
                $this->logger->addInfo(
1403
                    'startDatePlusDays: '.api_get_utc_datetime($startDatePlusDays).' - First date: '.$firstDate
1404
                );
1405
1406
                // Send
1407
                $sendMail = false;
1408
                if ($startDatePlusDays > api_strtotime($firstDate)) {
1409
                    $sendMail = true;
1410
                }
1411
1412
                // Send announcement to users
1413
                if ($sendMail && $alreadyAdded == false) {
1414
                    $start = $firstDate;
1415
                    $end = $firstEndDate;
1416
1417
                    if (!empty($end) &&
1418
                        api_format_date($start, DATE_FORMAT_LONG) ==
1419
                        api_format_date($end, DATE_FORMAT_LONG)
1420
                    ) {
1421
                        $date = api_format_date($start, DATE_FORMAT_LONG).' ('.
1422
                            api_format_date($start, TIME_NO_SEC_FORMAT).' '.
1423
                            api_format_date($end, TIME_NO_SEC_FORMAT).')';
1424
                    } else {
1425
                        $date = api_format_date($start, DATE_TIME_FORMAT_LONG_24H).' - '.
1426
                                api_format_date($end, DATE_TIME_FORMAT_LONG_24H);
1427
                    }
1428
1429
                    $sessionName = '';
1430
                    $sessionId = isset($event['session_id']) && !empty($event['session_id']) ? $event['session_id'] : 0;
1431
                    if (!empty($sessionId)) {
1432
                        $sessionName = api_get_session_name($sessionId);
1433
                    }
1434
1435
                    $courseTitle = $courseInfo['title'];
1436
1437
                    // Get the value of the "careerid" extra field of this
1438
                    // session
1439
                    $sessionExtraFieldValue = new ExtraFieldValue('session');
1440
                    $externalCareerIdList = $sessionExtraFieldValue->get_values_by_handler_and_field_variable(
1441
                        $event['session_id'],
1442
                        'careerid'
1443
                    );
1444
                    $externalCareerIdList = $externalCareerIdList['value'];
1445
                    if (substr($externalCareerIdList, 0, 1) === '[') {
1446
                        $externalCareerIdList = substr($externalCareerIdList, 1, -1);
1447
                        $externalCareerIds = preg_split('/,/', $externalCareerIdList);
1448
                    } else {
1449
                        $externalCareerIds = [$externalCareerIdList];
1450
                    }
1451
1452
                    $careerExtraFieldValue = new ExtraFieldValue('career');
1453
                    $career = new Career();
1454
                    $careerName = '';
1455
1456
                    // Concat the names of each career linked to this session
1457
                    foreach ($externalCareerIds as $externalCareerId) {
1458
                        // Using the external_career_id field (from above),
1459
                        // find the career ID
1460
                        $careerValue = $careerExtraFieldValue->get_item_id_from_field_variable_and_field_value(
1461
                            'external_career_id',
1462
                            $externalCareerId
1463
                        );
1464
                        $career = $career->find($careerValue['item_id']);
1465
                        $careerName .= $career['name'].', ';
1466
                    }
1467
                    // Remove trailing comma
1468
                    $careerName = substr($careerName, 0, -2);
1469
1470
                    $subject = sprintf(
1471
                        get_lang('WelcomeToPortalXInCourseSessionX'),
1472
                        api_get_setting('Institution'),
1473
                        $courseInfo['title']
1474
                    );
1475
1476
                    $tpl->assign('course_title', $courseTitle);
1477
                    $tpl->assign('career_name', $careerName);
1478
                    $tpl->assign('first_lesson', $date);
1479
                    $tpl->assign('location', $eventComment);
1480
                    $tpl->assign('session_name', $sessionName);
1481
1482
                    if (empty($sessionId)) {
1483
                        $teachersToString = CourseManager::getTeacherListFromCourseCodeToString($courseInfo['code'], ',');
1484
                    } else {
1485
                        $teachersToString = SessionManager::getCoachesByCourseSessionToString(
1486
                            $sessionId,
1487
                            $courseInfo['real_id'],
1488
                            ','
1489
                        );
1490
                    }
1491
1492
                    $tpl->assign('teachers', $teachersToString);
1493
1494
                    $templateName = $tpl->get_template('mail/custom_calendar_welcome.tpl');
1495
                    $emailBody = $tpl->fetch($templateName);
1496
1497
                    $coaches = SessionManager::getCoachesByCourseSession(
1498
                        $event['session_id'],
1499
                        $courseInfo['real_id']
1500
                    );
1501
1502
                    // Search if an announcement exists:
1503
                    $announcementsWithTitleList = AnnouncementManager::getAnnouncementsByTitle(
1504
                        $subject,
1505
                        $courseInfo['real_id'],
1506
                        $event['session_id'],
1507
                        1
1508
                    );
1509
1510
                    if (count($announcementsWithTitleList) === 0) {
1511
                        $this->logger->addInfo(
1512
                            'Mail to be sent because start date: '.$event['start'].' and no announcement found.'
1513
                        );
1514
1515
                        $senderId = $this->defaultAdminId;
1516
                        if (!empty($coaches) && isset($coaches[0]) && !empty($coaches[0])) {
1517
                            $senderId = $coaches[0];
1518
                        }
1519
1520
                        $announcementId = AnnouncementManager::add_announcement(
1521
                            $courseInfo,
1522
                            $event['session_id'],
1523
                            $subject,
1524
                            $emailBody,
1525
                            [
1526
                                'everyone',
1527
                                'users' => $coaches,
1528
                            ],
1529
                            [],
1530
                            null,
1531
                            null,
1532
                            false,
1533
                            $senderId
1534
                        );
1535
1536
                        if ($announcementId) {
1537
                            $this->logger->addInfo("Announcement added: $announcementId in $info");
1538
                            $this->logger->addInfo("<<--SENDING MAIL Sender id: $senderId-->>");
1539
                            $report['mail_sent']++;
1540
                            AnnouncementManager::sendEmail(
1541
                                $courseInfo,
1542
                                $event['session_id'],
1543
                                $announcementId,
1544
                                false,
1545
                                false,
1546
                                $this->logger,
1547
                                $senderId,
1548
                                true
1549
                            );
1550
                        } else {
1551
                            $this->logger->addError(
1552
                                "Error when trying to add announcement with title $subject here: $info and SenderId = $senderId"
1553
                            );
1554
                        }
1555
                    } else {
1556
                        $report['mail_not_sent_announcement_exists']++;
1557
                        $this->logger->addInfo(
1558
                            "Mail NOT sent. An announcement seems to be already saved in '$info'"
1559
                        );
1560
                    }
1561
                } else {
1562
                    $this->logger->addInfo(
1563
                        "Send Mail: ".intval($sendMail).' - Already added: '.intval($alreadyAdded)
1564
                    );
1565
                    if ($sendMail == false) {
1566
                        $report['mail_not_sent_because_date']++;
1567
                    }
1568
                }
1569
1570
                $content = '';
1571
                if ($update && isset($item['item_id'])) {
1572
                    $eventInfo = $agenda->get_event($item['item_id']);
1573
                    if (empty($eventInfo)) {
1574
                        // Means that agenda external id exists but the event doesn't exist
1575
                        $this->logger->addInfo("external event id exists: $externalEventId");
1576
                        $this->logger->addInfo("but Chamilo event doesn't exists: ".$item['item_id']);
1577
1578
                        $eventId = $agenda->addEvent(
1579
                            $event['start'],
1580
                            $event['end'],
1581
                            false,
1582
                            $event['title'],
1583
                            $content,
1584
                            ['everyone'], // $usersToSend
1585
                            false, //$addAsAnnouncement = false
1586
                            null, //  $parentEventId
1587
                            [], //$attachmentArray = array(),
1588
                            [], //$attachmentCommentList
1589
                            $eventComment,
1590
                            $color
1591
                        );
1592
1593
                        if (!empty($eventId)) {
1594
                            $this->logger->addInfo("Chamilo event created: ".$eventId);
1595
                            $extraFieldValueItem = $extraFieldValue->get_values_by_handler_and_field_id(
1596
                                $item['item_id'],
1597
                                $extraFieldInfo['id']
1598
                            );
1599
1600
                            if (!empty($extraFieldValueItem) && isset($extraFieldValueItem['id'])) {
1601
                                $params = [
1602
                                    'id' => $extraFieldValueItem['id'],
1603
                                    'item_id' => $eventId,
1604
                                ];
1605
                                $extraFieldValue->update($params);
1606
                                $this->logger->addInfo(
1607
                                    'Updating calendar extra field #'.$extraFieldValueItem['id'].' 
1608
                                    new item_id: '.$eventId.' old item_id: '.$item['item_id']
1609
                                );
1610
                            }
1611
                        } else {
1612
                            $this->logger->addInfo("Error while creating event external id: $externalEventId");
1613
                        }
1614
                    } else {
1615
                        // The event already exists, just update
1616
                        $eventResult = $agenda->editEvent(
1617
                            $item['item_id'],
1618
                            $event['start'],
1619
                            $event['end'],
1620
                            false,
1621
                            $event['title'],
1622
                            $content,
1623
                            ['everyone'], // $usersToSend
1624
                            [], //$attachmentArray = array(),
1625
                            [], //$attachmentCommentList
1626
                            $eventComment,
1627
                            $color,
1628
                            false,
1629
                            false,
1630
                            $this->defaultAdminId
1631
                        );
1632
1633
                        if ($eventResult !== false) {
1634
                            $this->logger->addInfo(
1635
                                "Event updated #".$item['item_id']." External cal Id: (".$externalEventId.") $info"
1636
                            );
1637
                        } else {
1638
                            $this->logger->addInfo(
1639
                                "Error while updating event with external id: $externalEventId"
1640
                            );
1641
                        }
1642
                    }
1643
                } else {
1644
                    // New event. Create it.
1645
                    $eventId = $agenda->addEvent(
1646
                        $event['start'],
1647
                        $event['end'],
1648
                        false,
1649
                        $event['title'],
1650
                        $content,
1651
                        ['everyone'], // $usersToSend
1652
                        false, //$addAsAnnouncement = false
1653
                        null, //  $parentEventId
1654
                        [], //$attachmentArray = array(),
1655
                        [], //$attachmentCommentList
1656
                        $eventComment,
1657
                        $color
1658
                    );
1659
1660
                    if (!empty($eventId)) {
1661
                        $extraFieldValue->save(
1662
                            [
1663
                                'value' => $externalEventId,
1664
                                'field_id' => $extraFieldInfo['id'],
1665
                                'item_id' => $eventId,
1666
                            ]
1667
                        );
1668
                        $this->logger->addInfo(
1669
                            "Event added: #$eventId External cal id: (".$externalEventId.") $info"
1670
                        );
1671
                    } else {
1672
                        $this->logger->addInfo(
1673
                            "Error while creating event external id: $externalEventId"
1674
                        );
1675
                    }
1676
                }
1677
1678
                if (($counter % $batchSize) === 0) {
1679
                    $em->flush();
1680
                    $em->clear(); // Detaches all objects from Doctrine!
1681
                }
1682
                $counter++;
1683
            }
1684
1685
            $em->clear(); // Detaches all objects from Doctrine!
1686
            $this->logger->addInfo('------Summary------');
1687
            foreach ($report as $title => $count) {
1688
                $this->logger->addInfo("$title: $count");
1689
            }
1690
            $this->logger->addInfo('------End Summary------');
1691
        }
1692
1693
        if ($moveFile) {
1694
            $this->moveFile($file);
1695
        }
1696
    }
1697
1698
    /**
1699
     * @param string $file
1700
     * @param bool   $moveFile
1701
     * @param array  $teacherBackup
1702
     * @param array  $groupBackup
1703
     */
1704
    private function importCourses(
1705
        $file,
1706
        $moveFile = true,
1707
        &$teacherBackup = [],
1708
        &$groupBackup = []
1709
    ) {
1710
        $this->fixCSVFile($file);
1711
        $data = Import::csvToArray($file);
1712
1713
        if (!empty($data)) {
1714
            $this->logger->addInfo(count($data)." records found.");
1715
1716
            foreach ($data as $row) {
1717
                $row = $this->cleanCourseRow($row);
1718
1719
                $courseId = CourseManager::get_course_id_from_original_id(
1720
                    $row['extra_'.$this->extraFieldIdNameList['course']],
1721
                    $this->extraFieldIdNameList['course']
1722
                );
1723
1724
                $courseInfo = api_get_course_info_by_id($courseId);
1725
1726
                if (empty($courseInfo)) {
1727
                    // Create
1728
                    $params = [];
1729
                    $params['title'] = $row['title'];
1730
                    $params['exemplary_content'] = false;
1731
                    $params['wanted_code'] = $row['course_code'];
1732
                    $params['course_category'] = $row['course_category'];
1733
                    $params['course_language'] = $row['language'];
1734
                    $params['teachers'] = $row['teachers'];
1735
                    $params['visibility'] = $row['visibility'];
1736
1737
                    $courseInfo = CourseManager::create_course(
1738
                        $params,
1739
                        $this->defaultAdminId
1740
                    );
1741
1742
                    if (!empty($courseInfo)) {
1743
                        CourseManager::update_course_extra_field_value(
1744
                            $courseInfo['code'],
1745
                            'external_course_id',
1746
                            $row['extra_'.$this->extraFieldIdNameList['course']]
1747
                        );
1748
1749
                        $this->logger->addInfo("Courses - Course created ".$courseInfo['code']);
1750
                    } else {
1751
                        $this->logger->addError("Courses - Can't create course:".$row['title']);
1752
                    }
1753
                } else {
1754
                    // Update
1755
                    $params = [
1756
                        'title' => $row['title'],
1757
                        'category_code' => $row['course_category'],
1758
                        'visibility' => $row['visibility'],
1759
                    ];
1760
1761
                    $result = CourseManager::update_attributes(
1762
                        $courseInfo['real_id'],
1763
                        $params
1764
                    );
1765
1766
                    $addTeacherToSession = isset($courseInfo['add_teachers_to_sessions_courses']) && !empty($courseInfo['add_teachers_to_sessions_courses']) ? true : false;
1767
1768
                    $teachers = $row['teachers'];
1769
                    if (!is_array($teachers)) {
1770
                        $teachers = [$teachers];
1771
                    }
1772
1773
                    if ($addTeacherToSession) {
1774
                        $this->logger->addInfo("Add teacher to all course sessions");
1775
                        CourseManager::updateTeachers(
1776
                            $courseInfo,
1777
                            $row['teachers'],
1778
                            false,
1779
                            true,
1780
                            false,
1781
                            $teacherBackup,
1782
                            $this->logger
1783
                        );
1784
                    } else {
1785
                        CourseManager::updateTeachers(
1786
                            $courseInfo,
1787
                            $row['teachers'],
1788
                            true,
1789
                            false,
1790
                            false,
1791
                            $teacherBackup,
1792
                            $this->logger
1793
                        );
1794
                    }
1795
1796
                    foreach ($teachers as $teacherId) {
1797
                        if (isset($groupBackup['tutor'][$teacherId]) &&
1798
                            isset($groupBackup['tutor'][$teacherId][$courseInfo['code']])
1799
                        ) {
1800
                            foreach ($groupBackup['tutor'][$teacherId][$courseInfo['code']] as $data) {
1801
                                $groupInfo = GroupManager::get_group_properties($data['group_id']);
1802
                                GroupManager::subscribe_tutors(
1803
                                    [$teacherId],
1804
                                    $groupInfo,
1805
                                    $data['c_id']
1806
                                );
1807
                            }
1808
                        }
1809
1810
                        if (isset($groupBackup['user'][$teacherId]) &&
1811
                            isset($groupBackup['user'][$teacherId][$courseInfo['code']]) &&
1812
                            !empty($groupBackup['user'][$teacherId][$courseInfo['code']])
1813
                        ) {
1814
                            foreach ($groupBackup['user'][$teacherId][$courseInfo['code']] as $data) {
1815
                                $groupInfo = GroupManager::get_group_properties($data['group_id']);
1816
                                GroupManager::subscribe_users(
1817
                                    [$teacherId],
1818
                                    $groupInfo,
1819
                                    $data['c_id']
1820
                                );
1821
                            }
1822
                        }
1823
                    }
1824
1825
                    if ($result) {
1826
                        $this->logger->addInfo("Courses - Course updated ".$courseInfo['code']);
1827
                    } else {
1828
                        $this->logger->addError("Courses - Course NOT updated ".$courseInfo['code']);
1829
                    }
1830
                }
1831
            }
1832
        }
1833
1834
        if ($moveFile) {
1835
            $this->moveFile($file);
1836
        }
1837
    }
1838
1839
    /**
1840
     * Parse filename: encora_subsessionsextid-static_31082016.csv.
1841
     *
1842
     * @param string $file
1843
     */
1844
    private function importSubscribeUserToCourseSessionExtStatic($file, $moveFile = true)
1845
    {
1846
        $data = Import::csv_reader($file);
1847
        if (!empty($data)) {
1848
            $this->logger->addInfo(count($data)." records found.");
1849
            $userIdList = [];
1850
            foreach ($data as $row) {
1851
                $chamiloUserName = $row['UserName'];
1852
                $chamiloCourseCode = $row['CourseCode'];
1853
                $externalSessionId = $row['ExtSessionID'];
1854
                $status = $row['Status'];
1855
1856
                $chamiloSessionId = null;
1857
                if (!empty($externalSessionId)) {
1858
                    $chamiloSessionId = SessionManager::getSessionIdFromOriginalId(
1859
                        $externalSessionId,
1860
                        $this->extraFieldIdNameList['session']
1861
                    );
1862
                }
1863
1864
                $sessionInfo = api_get_session_info($chamiloSessionId);
1865
1866
                if (empty($sessionInfo)) {
1867
                    $this->logger->addError('Session does not exists: '.$chamiloSessionId);
1868
                    continue;
1869
                }
1870
1871
                $courseInfo = api_get_course_info($chamiloCourseCode);
1872
                if (empty($courseInfo)) {
1873
                    $this->logger->addError('Course does not exists: '.$courseInfo);
1874
                    continue;
1875
                }
1876
1877
                $userId = UserManager::get_user_id_from_username($chamiloUserName);
1878
1879
                if (empty($userId)) {
1880
                    $this->logger->addError('User does not exists: '.$chamiloUserName);
1881
                    continue;
1882
                }
1883
1884
                switch ($status) {
1885
                    case 'student':
1886
                        SessionManager::subscribe_users_to_session_course(
1887
                            [$userId],
1888
                            $chamiloSessionId,
1889
                            $courseInfo['code']
1890
                        );
1891
                        break;
1892
                    case 'teacher':
1893
                        SessionManager::set_coach_to_course_session(
1894
                            $userId,
1895
                            $chamiloSessionId,
1896
                            $courseInfo['code']
1897
                        );
1898
                        break;
1899
                    case 'drh':
1900
                        $removeAllSessionsFromUser = true;
1901
                        if (in_array($userId, $userIdList)) {
1902
                            $removeAllSessionsFromUser = false;
1903
                        } else {
1904
                            $userIdList[] = $userId;
1905
                        }
1906
1907
                        $userInfo = api_get_user_info($userId);
1908
                        SessionManager::subscribeSessionsToDrh(
1909
                            $userInfo,
1910
                            [$chamiloSessionId],
1911
                            false,
1912
                            $removeAllSessionsFromUser
1913
                        );
1914
                        break;
1915
                }
1916
1917
                $this->logger->addError(
1918
                    "User '$chamiloUserName' was added as '$status' to Session: #$chamiloSessionId - Course: ".$courseInfo['code']
1919
                );
1920
            }
1921
        }
1922
1923
        if ($moveFile) {
1924
            $this->moveFile($file);
1925
        }
1926
    }
1927
1928
    /**
1929
     * @param $file
1930
     * @param bool $moveFile
1931
     */
1932
    private function importUnsubSessionsExtIdStatic($file, $moveFile = true)
1933
    {
1934
        $data = Import::csv_reader($file);
1935
1936
        if (!empty($data)) {
1937
            $this->logger->addInfo(count($data)." records found.");
1938
            foreach ($data as $row) {
1939
                $chamiloUserName = $row['UserName'];
1940
                $chamiloCourseCode = $row['CourseCode'];
1941
                $externalSessionId = $row['ExtSessionID'];
1942
                $dateStop = $row['DateStop'];
1943
1944
                $chamiloSessionId = null;
1945
                if (!empty($externalSessionId)) {
1946
                    $chamiloSessionId = SessionManager::getSessionIdFromOriginalId(
1947
                        $externalSessionId,
1948
                        $this->extraFieldIdNameList['session']
1949
                    );
1950
                }
1951
1952
                $sessionInfo = api_get_session_info($chamiloSessionId);
1953
1954
                if (empty($sessionInfo)) {
1955
                    $this->logger->addError('Session does not exists: '.$chamiloSessionId);
1956
                    continue;
1957
                }
1958
1959
                $courseInfo = api_get_course_info($chamiloCourseCode);
1960
                if (empty($courseInfo)) {
1961
                    $this->logger->addError('Course does not exists: '.$courseInfo);
1962
                    continue;
1963
                }
1964
1965
                $userId = UserManager::get_user_id_from_username($chamiloUserName);
1966
1967
                if (empty($userId)) {
1968
                    $this->logger->addError('User does not exists: '.$chamiloUserName);
1969
                    continue;
1970
                }
1971
1972
                SessionManager::removeUsersFromCourseSession(
1973
                    [$userId],
1974
                    $chamiloSessionId,
1975
                    $courseInfo
1976
                );
1977
1978
                $this->logger->addError(
1979
                    "User '$chamiloUserName' was remove from Session: #$chamiloSessionId - Course: ".$courseInfo['code']
1980
                );
1981
            }
1982
        }
1983
1984
        if ($moveFile) {
1985
            $this->moveFile($file);
1986
        }
1987
    }
1988
1989
    /**
1990
     * @param string $file
1991
     */
1992
    private function importSessionsExtIdStatic($file, $moveFile = true)
1993
    {
1994
        $data = Import::csv_reader($file);
1995
1996
        if (!empty($data)) {
1997
            $this->logger->addInfo(count($data)." records found.");
1998
            foreach ($data as $row) {
1999
                $chamiloUserName = $row['UserName'];
2000
                $chamiloCourseCode = $row['CourseCode'];
2001
                $externalSessionId = $row['ExtSessionID'];
2002
                $type = $row['Type'];
2003
2004
                $chamiloSessionId = null;
2005
                if (!empty($externalSessionId)) {
2006
                    $chamiloSessionId = SessionManager::getSessionIdFromOriginalId(
2007
                        $externalSessionId,
2008
                        $this->extraFieldIdNameList['session']
2009
                    );
2010
                }
2011
2012
                $sessionInfo = api_get_session_info($chamiloSessionId);
2013
2014
                if (empty($sessionInfo)) {
2015
                    $this->logger->addError('Session does not exists: '.$chamiloSessionId);
2016
                    continue;
2017
                }
2018
2019
                $courseInfo = api_get_course_info($chamiloCourseCode);
2020
                if (empty($courseInfo)) {
2021
                    $this->logger->addError('Course does not exists: '.$courseInfo);
2022
                    continue;
2023
                }
2024
2025
                $userId = UserManager::get_user_id_from_username($chamiloUserName);
2026
2027
                if (empty($userId)) {
2028
                    $this->logger->addError('User does not exists: '.$chamiloUserName);
2029
                    continue;
2030
                }
2031
                switch ($type) {
2032
                    case 'student':
2033
                        SessionManager::subscribe_users_to_session_course(
2034
                            [$userId],
2035
                            $chamiloSessionId,
2036
                            $courseInfo['code'],
2037
                            null,
2038
                            false
2039
                        );
2040
                        break;
2041
                    case 'teacher':
2042
                        SessionManager::set_coach_to_course_session(
2043
                            $userId,
2044
                            $chamiloSessionId,
2045
                            $courseInfo['code']
2046
                        );
2047
                        break;
2048
                }
2049
2050
                $this->logger->addError(
2051
                    "User '$chamiloUserName' with status $type was added to session: #$chamiloSessionId - Course: ".$courseInfo['code']
2052
                );
2053
            }
2054
        }
2055
2056
        if ($moveFile) {
2057
            $this->moveFile($file);
2058
        }
2059
    }
2060
2061
    /**
2062
     * Updates the session synchronize with the csv file.
2063
     *
2064
     * @param bool   $moveFile
2065
     * @param string $file
2066
     */
2067
    private function importSessionsStatic($file, $moveFile = true)
2068
    {
2069
        $content = file($file);
2070
        $sessions = [];
2071
        $tag_names = [];
2072
2073
        foreach ($content as $key => $enreg) {
2074
            $enreg = explode(';', trim($enreg));
2075
            if ($key) {
2076
                foreach ($tag_names as $tag_key => $tag_name) {
2077
                    if (isset($enreg[$tag_key])) {
2078
                        $sessions[$key - 1][$tag_name] = $enreg[$tag_key];
2079
                    }
2080
                }
2081
            } else {
2082
                foreach ($enreg as $tag_name) {
2083
                    $tag_names[] = api_preg_replace(
2084
                        '/[^a-zA-Z0-9_\-]/',
2085
                        '',
2086
                        $tag_name
2087
                    );
2088
                }
2089
                if (!in_array('SessionName', $tag_names) ||
2090
                    !in_array('DateStart', $tag_names) || !in_array('DateEnd', $tag_names)
2091
                ) {
2092
                    $error_message = get_lang('NoNeededData');
2093
                    break;
2094
                }
2095
            }
2096
        }
2097
2098
        if (!empty($sessions)) {
2099
            // Looping the sessions.
2100
            foreach ($sessions as $session) {
2101
                if (!empty($session['SessionID'])) {
2102
                    $sessionId = SessionManager::getSessionIdFromOriginalId(
2103
                        $session['SessionID'],
2104
                        $this->extraFieldIdNameList['session']
2105
                    );
2106
2107
                    $coachUserName = isset($session['Coach']) ? $session['Coach'] : null;
2108
                    $categoryId = isset($session['category_id']) ? $session['category_id'] : null;
2109
2110
                    // 2014-06-30
2111
                    $dateStart = explode('/', $session['DateStart']);
2112
                    $dateEnd = explode('/', $session['DateEnd']);
2113
                    $visibility = $this->defaultSessionVisibility;
2114
2115
                    $coachId = null;
2116
                    if (!empty($coachUserName)) {
2117
                        $coachInfo = api_get_user_info_from_username($coachUserName);
2118
                        $coachId = $coachInfo['user_id'];
2119
                    }
2120
2121
                    $dateStart = $dateStart[0].'-'.$dateStart[1].'-'.$dateStart[2].' 00:00:00';
2122
                    $dateEnd = $dateEnd[0].'-'.$dateEnd[1].'-'.$dateEnd[2].' 23:59:59';
2123
2124
                    $date = new \DateTime($dateStart);
2125
                    $interval = new DateInterval('P'.$this->daysCoachAccessBeforeBeginning.'D');
2126
                    $date->sub($interval);
2127
                    $coachBefore = $date->format('Y-m-d h:i');
2128
2129
                    $date = new \DateTime($dateEnd);
2130
                    $interval = new DateInterval('P'.$this->daysCoachAccessAfterBeginning.'D');
2131
                    $date->add($interval);
2132
                    $coachAfter = $date->format('Y-m-d h:i');
2133
2134
                    /*$dateStart = api_get_utc_datetime($dateStart);
2135
                    $dateEnd = api_get_utc_datetime($dateEnd);
2136
                    $coachBefore = api_get_utc_datetime($coachBefore);
2137
                    $coachAfter = api_get_utc_datetime($coachAfter);*/
2138
2139
                    if (empty($sessionId)) {
2140
                        $result = SessionManager::create_session(
2141
                            $session['SessionName'],
2142
                            $dateStart,
2143
                            $dateEnd,
2144
                            $dateStart,
2145
                            $dateEnd,
2146
                            $coachBefore,
2147
                            $coachAfter,
2148
                            $coachId,
2149
                            $categoryId,
2150
                            $visibility
2151
                        );
2152
2153
                        if (is_numeric($result)) {
2154
                            $sessionId = $result;
2155
                            $this->logger->addInfo("Session #$sessionId created: ".$session['SessionName']);
2156
                            SessionManager::update_session_extra_field_value(
2157
                                $sessionId,
2158
                                $this->extraFieldIdNameList['session'],
2159
                                $session['SessionID']
2160
                            );
2161
                        } else {
2162
                            $this->logger->addInfo("Failed creating session: ".$session['SessionName']);
2163
                        }
2164
                    } else {
2165
                        $sessionInfo = api_get_session_info($sessionId);
2166
                        $accessBefore = null;
2167
                        $accessAfter = null;
2168
2169
                        if (empty($sessionInfo['nb_days_access_before_beginning']) ||
2170
                            (!empty($sessionInfo['nb_days_access_before_beginning']) &&
2171
                                $sessionInfo['nb_days_access_before_beginning'] < $this->daysCoachAccessBeforeBeginning)
2172
                        ) {
2173
                            $accessBefore = $coachBefore;
2174
                        }
2175
2176
                        $accessAfter = null;
2177
                        if (empty($sessionInfo['nb_days_access_after_end']) ||
2178
                            (!empty($sessionInfo['nb_days_access_after_end']) &&
2179
                                $sessionInfo['nb_days_access_after_end'] < $this->daysCoachAccessAfterBeginning)
2180
                        ) {
2181
                            $accessAfter = $coachAfter;
2182
                        }
2183
2184
                        $showDescription = isset($sessionInfo['show_description']) ? $sessionInfo['show_description'] : 1;
2185
2186
                        $result = SessionManager::edit_session(
2187
                            $sessionId,
2188
                            $session['SessionName'],
2189
                            $dateStart,
2190
                            $dateEnd,
2191
                            $dateStart,
2192
                            $dateEnd,
2193
                            $accessBefore,
2194
                            $accessAfter,
2195
                            $coachId,
2196
                            $categoryId,
2197
                            $visibility,
2198
                            null, //$description = null,
2199
                            $showDescription
2200
                        );
2201
2202
                        if (is_numeric($result)) {
2203
                            $this->logger->addInfo("Session #$sessionId updated: ".$session['SessionName']);
2204
                            $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
2205
                            $params = [
2206
                                'description' => $session['SessionDescription'],
2207
                            ];
2208
                            Database::update(
2209
                                $tbl_session,
2210
                                $params,
2211
                                ['id = ?' => $sessionId]
2212
                            );
2213
                        }
2214
                    }
2215
2216
                    if (!empty($sessionId)) {
2217
                        // Courses
2218
                        $courses = explode('|', $session['Courses']);
2219
                        $courseList = [];
2220
                        $courseListWithCoach = [];
2221
                        foreach ($courses as $course) {
2222
                            $courseArray = bracketsToArray($course);
2223
                            $courseCode = $courseArray[0];
2224
                            if (CourseManager::course_exists($courseCode)) {
2225
                                $courseInfo = api_get_course_info($courseCode);
2226
                                $courseList[] = $courseInfo['real_id'];
2227
                                // Extracting course coaches
2228
                                $courseCoaches = isset($courseArray[1]) ? $courseArray[1] : null;
2229
                                $courseCoaches = explode(',', $courseCoaches);
2230
2231
                                // Extracting students
2232
                                $courseUsers = isset($courseArray[2]) ? $courseArray[2] : null;
2233
                                $courseUsers = explode(',', $courseUsers);
2234
2235
                                $courseListWithCoach[] = [
2236
                                    'course_info' => $courseInfo,
2237
                                    'coaches' => $courseCoaches,
2238
                                    'course_users' => $courseUsers,
2239
                                ];
2240
                            }
2241
                        }
2242
2243
                        SessionManager::add_courses_to_session(
2244
                            $sessionId,
2245
                            $courseList,
2246
                            true
2247
                        );
2248
2249
                        $this->logger->addInfo("Session #$sessionId: Courses added: '".implode(', ', $courseList)."'");
2250
2251
                        if (empty($courseListWithCoach)) {
2252
                            $this->logger->addInfo("No users/coaches to update");
2253
                            continue;
2254
                        }
2255
2256
                        foreach ($courseListWithCoach as $courseData) {
2257
                            $courseInfo = $courseData['course_info'];
2258
                            $courseCode = $courseInfo['code'];
2259
                            $courseId = $courseInfo['real_id'];
2260
                            $courseCoaches = $courseData['coaches'];
2261
                            $courseUsers = $courseData['course_users'];
2262
2263
                            // Coaches
2264
                            if (!empty($courseCoaches)) {
2265
                                $coachList = [];
2266
                                foreach ($courseCoaches as $courseCoach) {
2267
                                    $courseCoachId = UserManager::get_user_id_from_username(
2268
                                        $courseCoach
2269
                                    );
2270
                                    if ($courseCoachId !== false) {
2271
                                        // Just insert new coaches
2272
                                        $coachList[] = $courseCoachId;
2273
                                    }
2274
                                }
2275
2276
                                $this->logger->addInfo("Session #$sessionId: course '$courseCode' coaches added: '".implode(', ', $coachList)."'");
2277
2278
                                SessionManager::updateCoaches(
2279
                                    $sessionId,
2280
                                    $courseId,
2281
                                    $coachList,
2282
                                    true
2283
                                );
2284
                            } else {
2285
                                $this->logger->addInfo("No coaches added");
2286
                            }
2287
2288
                            // Students
2289
                            if (!empty($courseUsers)) {
2290
                                $userList = [];
2291
                                foreach ($courseUsers as $username) {
2292
                                    $userInfo = api_get_user_info_from_username(trim($username));
2293
                                    if (!empty($userInfo)) {
2294
                                        $userList[] = $userInfo['user_id'];
2295
                                    }
2296
                                }
2297
2298
                                $this->logger->addInfo("Session #$sessionId: course '$courseCode': Students added '".implode(', ', $userList)."'");
2299
                                SessionManager::subscribe_users_to_session_course(
2300
                                    $userList,
2301
                                    $sessionId,
2302
                                    $courseCode,
2303
                                    SESSION_VISIBLE_READ_ONLY,
2304
                                    true
2305
                                );
2306
                            } else {
2307
                                $this->logger->addInfo("No users to register.");
2308
                            }
2309
                        }
2310
                    } else {
2311
                        $this->logger->addInfo(
2312
                            'SessionID not found in system.'
2313
                        );
2314
                    }
2315
                } else {
2316
                    $this->logger->addInfo('SessionID does not exists');
2317
                }
2318
            }
2319
        } else {
2320
            $this->logger->addInfo($error_message);
2321
        }
2322
2323
        if ($moveFile) {
2324
            $this->moveFile($file);
2325
        }
2326
    }
2327
2328
    /**
2329
     * @param $file
2330
     * @param bool  $moveFile
2331
     * @param array $teacherBackup
2332
     * @param array $groupBackup
2333
     */
2334
    private function importOpenSessions(
2335
        $file,
2336
        $moveFile = true,
2337
        &$teacherBackup = [],
2338
        &$groupBackup = []
2339
    ) {
2340
        $this->importSessions($file, $moveFile, $teacherBackup, $groupBackup);
2341
    }
2342
2343
    /**
2344
     * @param string $file
2345
     * @param bool   $moveFile
2346
     * @param array  $teacherBackup
2347
     * @param array  $groupBackup
2348
     */
2349
    private function importSessions(
2350
        $file,
2351
        $moveFile = true,
2352
        &$teacherBackup = [],
2353
        &$groupBackup = []
2354
    ) {
2355
        $avoid = null;
2356
        if (isset($this->conditions['importSessions']) &&
2357
            isset($this->conditions['importSessions']['update'])
2358
        ) {
2359
            $avoid = $this->conditions['importSessions']['update'];
2360
        }
2361
        $result = SessionManager::importCSV(
2362
            $file,
2363
            true,
2364
            $this->defaultAdminId,
2365
            $this->logger,
2366
            [
2367
                'SessionID' => 'extra_'.$this->extraFieldIdNameList['session'],
2368
                'CareerId' => 'extra_'.$this->extraFieldIdNameList['session_career'],
2369
            ],
2370
            $this->extraFieldIdNameList['session'],
2371
            $this->daysCoachAccessBeforeBeginning,
2372
            $this->daysCoachAccessAfterBeginning,
2373
            $this->defaultSessionVisibility,
2374
            $avoid,
2375
            false, // deleteUsersNotInList
2376
            false, // updateCourseCoaches
2377
            true, // sessionWithCoursesModifier
2378
            true, //$addOriginalCourseTeachersAsCourseSessionCoaches
2379
            false, //$removeAllTeachersFromCourse
2380
            1, // $showDescription,
2381
            $teacherBackup,
2382
            $groupBackup
2383
        );
2384
2385
        if (!empty($result['error_message'])) {
2386
            $this->logger->addError($result['error_message']);
2387
        }
2388
        $this->logger->addInfo("Sessions - Sessions parsed: ".$result['session_counter']);
2389
2390
        if ($moveFile) {
2391
            $this->moveFile($file);
2392
        }
2393
    }
2394
2395
    /**
2396
     * @param string $file
2397
     * @param bool   $moveFile
2398
     */
2399
    private function importSubscribeStatic($file, $moveFile = true)
2400
    {
2401
        $data = Import::csv_reader($file);
2402
2403
        if (!empty($data)) {
2404
            $this->logger->addInfo(count($data)." records found.");
2405
            foreach ($data as $row) {
2406
                $chamiloUserName = $row['UserName'];
2407
                $chamiloCourseCode = $row['CourseCode'];
2408
                $chamiloSessionId = $row['SessionID'];
2409
                $type = $row['Type'];
2410
2411
                $sessionInfo = api_get_session_info($chamiloSessionId);
2412
2413
                if (empty($sessionInfo)) {
2414
                    $this->logger->addError('Session does not exists: '.$chamiloSessionId);
2415
                    continue;
2416
                }
2417
2418
                $courseInfo = api_get_course_info($chamiloCourseCode);
2419
                if (empty($courseInfo)) {
2420
                    $this->logger->addError('Course does not exists: '.$courseInfo);
2421
                    continue;
2422
                }
2423
2424
                $userId = UserManager::get_user_id_from_username($chamiloUserName);
2425
2426
                if (empty($userId)) {
2427
                    $this->logger->addError('User does not exists: '.$chamiloUserName);
2428
                    continue;
2429
                }
2430
2431
                switch ($type) {
2432
                    case 'student':
2433
                        SessionManager::subscribe_users_to_session_course(
2434
                            [$userId],
2435
                            $chamiloSessionId,
2436
                            $courseInfo['code'],
2437
                            null,
2438
                            false
2439
                        );
2440
                        break;
2441
                    case 'teacher':
2442
                        SessionManager::set_coach_to_course_session(
2443
                            $userId,
2444
                            $chamiloSessionId,
2445
                            $courseInfo['real_id']
2446
                        );
2447
                        break;
2448
                }
2449
2450
                $this->logger->addError(
2451
                    "User '$chamiloUserName' with status $type was added to session: #$chamiloSessionId - Course: ".$courseInfo['code']
2452
                );
2453
            }
2454
        }
2455
2456
        if ($moveFile) {
2457
            $this->moveFile($file);
2458
        }
2459
    }
2460
2461
    /**
2462
     * @param $file
2463
     * @param bool $moveFile
2464
     */
2465
    private function importSubscribeUserToCourse($file, $moveFile = false, &$teacherBackup = [])
2466
    {
2467
        $data = Import::csv_reader($file);
2468
2469
        if (!empty($data)) {
2470
            $this->logger->addInfo(count($data)." records found.");
2471
            foreach ($data as $row) {
2472
                $chamiloUserName = $row['UserName'];
2473
                $chamiloCourseCode = $row['CourseCode'];
2474
                $status = $row['Status'];
2475
2476
                $courseInfo = api_get_course_info($chamiloCourseCode);
2477
2478
                if (empty($courseInfo)) {
2479
                    $this->logger->addError(
2480
                        'Course does not exists: '.$chamiloCourseCode
2481
                    );
2482
                    continue;
2483
                }
2484
2485
                $userId = UserManager::get_user_id_from_username(
2486
                    $chamiloUserName
2487
                );
2488
2489
                if (empty($userId)) {
2490
                    $this->logger->addError(
2491
                        'User does not exists: '.$chamiloUserName
2492
                    );
2493
                    continue;
2494
                }
2495
2496
                $userCourseCategory = '';
2497
                if (isset($teacherBackup[$userId]) &&
2498
                    isset($teacherBackup[$userId][$courseInfo['code']])
2499
                ) {
2500
                    $courseUserData = $teacherBackup[$userId][$courseInfo['code']];
2501
                    $userCourseCategory = $courseUserData['user_course_cat'];
2502
                }
2503
2504
                $result = CourseManager::subscribeUser(
2505
                    $userId,
2506
                    $courseInfo['code'],
2507
                    $status,
2508
                    0,
2509
                    $userCourseCategory
2510
                );
2511
2512
                if ($result) {
2513
                    $this->logger->addInfo(
2514
                        "User $userId added to course ".$courseInfo['code']." with status '$status' with course category: '$userCourseCategory'"
2515
                    );
2516
                } else {
2517
                    $this->logger->addInfo(
2518
                        "User $userId was NOT ADDED to course ".$courseInfo['code']." with status '$status' with course category: '$userCourseCategory'"
2519
                    );
2520
                }
2521
            }
2522
        }
2523
2524
        if ($moveFile) {
2525
            $this->moveFile($file);
2526
        }
2527
    }
2528
2529
    /**
2530
     * 23/4/2017 to datetime.
2531
     *
2532
     * @param $string
2533
     *
2534
     * @return mixed
2535
     */
2536
    private function createDateTime($string)
2537
    {
2538
        if (empty($string)) {
2539
            return null;
2540
        }
2541
2542
        $date = DateTime::createFromFormat('j/m/Y', $string);
2543
        if ($date) {
2544
            return $date;
2545
        }
2546
2547
        return null;
2548
    }
2549
2550
    /**
2551
     * @param $file
2552
     * @param bool  $moveFile
2553
     * @param array $teacherBackup
2554
     * @param array $groupBackup
2555
     *
2556
     * @return bool
2557
     */
2558
    private function importCareers(
2559
        $file,
2560
        $moveFile = false,
2561
        &$teacherBackup = [],
2562
        &$groupBackup = []
2563
    ) {
2564
        $data = Import::csv_reader($file);
2565
2566
        if (!empty($data)) {
2567
            $this->logger->addInfo(count($data).' records found.');
2568
            $extraFieldValue = new ExtraFieldValue('career');
2569
            $extraFieldName = $this->extraFieldIdNameList['career'];
2570
            $externalEventId = null;
2571
2572
            $extraField = new ExtraField('career');
2573
            $extraFieldInfo = $extraField->get_handler_field_info_by_field_variable($extraFieldName);
2574
2575
            if (empty($extraFieldInfo)) {
2576
                $this->logger->addInfo("Extra field doesn't exists: $extraFieldName");
2577
2578
                return false;
2579
            }
2580
2581
            foreach ($data as $row) {
2582
                foreach ($row as $key => $value) {
2583
                    $key = (string) trim($key);
2584
                    // Remove utf8 bom
2585
                    $key = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $key);
2586
                    $row[$key] = $value;
2587
                }
2588
2589
                $itemId = $row['CareerId'];
2590
                $item = $extraFieldValue->get_item_id_from_field_variable_and_field_value(
2591
                    $extraFieldName,
2592
                    $itemId,
2593
                    false,
2594
                    false,
2595
                    false
2596
                );
2597
2598
                $career = new Career();
2599
                if (empty($item)) {
2600
                    $params = [
2601
                        'status' => 1,
2602
                        'name' => $row['CareerName'],
2603
                    ];
2604
                    $careerId = $career->save($params);
2605
                    if ($careerId) {
2606
                        $params = [
2607
                            'item_id' => $careerId,
2608
                            'extra_'.$extraFieldName => $itemId,
2609
                        ];
2610
                        $links = isset($row['HLinks']) ? $row['HLinks'] : [];
2611
                        if (!empty($links)) {
2612
                            $extraFieldUrlName = $this->extraFieldIdNameList['career_urls'];
2613
                            $extraFieldInfo = $extraField->get_handler_field_info_by_field_variable(
2614
                                $extraFieldUrlName
2615
                            );
2616
                            if (!empty($extraFieldInfo)) {
2617
                                $params['extra_'.$extraFieldUrlName] = $links;
2618
                            }
2619
                        }
2620
                        $extraFieldValue->saveFieldValues($params);
2621
                    }
2622
                } else {
2623
                    if (isset($item['item_id'])) {
2624
                        $params = [
2625
                            'id' => $item['item_id'],
2626
                            'name' => $row['CareerName'],
2627
                        ];
2628
                        $career->update($params);
2629
                        $links = isset($row['HLinks']) ? $row['HLinks'] : [];
2630
2631
                        if (!empty($links)) {
2632
                            $extraFieldUrlName = $this->extraFieldIdNameList['career_urls'];
2633
                            $extraFieldInfo = $extraField->get_handler_field_info_by_field_variable(
2634
                                $extraFieldUrlName
2635
                            );
2636
                            if (!empty($extraFieldInfo)) {
2637
                                $params = [
2638
                                    'item_id' => $item['item_id'],
2639
                                    'extra_'.$extraFieldName => $itemId,
2640
                                    'extra_'.$extraFieldUrlName => $links,
2641
                                ];
2642
                                $extraFieldValue->saveFieldValues($params);
2643
                            }
2644
                        }
2645
                    }
2646
                }
2647
            }
2648
        }
2649
    }
2650
2651
    /**
2652
     * @param $file
2653
     * @param bool  $moveFile
2654
     * @param array $teacherBackup
2655
     * @param array $groupBackup
2656
     */
2657
    private function importCareersResults(
2658
        $file,
2659
        $moveFile = false,
2660
        &$teacherBackup = [],
2661
        &$groupBackup = []
2662
    ) {
2663
        $data = Import::csv_reader($file);
2664
2665
        if (!empty($data)) {
2666
            $this->logger->addInfo(count($data).' records found.');
2667
2668
            $extraFieldValue = new ExtraFieldValue('career');
2669
            $extraFieldName = $this->extraFieldIdNameList['career'];
2670
2671
            foreach ($data as $row) {
2672
                if (empty($row)) {
2673
                    continue;
2674
                }
2675
                foreach ($row as $key => $value) {
2676
                    $key = (string) trim($key);
2677
                    // Remove utf8 bom
2678
                    $key = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $key);
2679
                    $row[$key] = $value;
2680
                }
2681
2682
                $studentId = $row['StudentId'];
2683
                $studentId = UserManager::get_user_id_from_original_id(
2684
                    $studentId,
2685
                    $this->extraFieldIdNameList['user']
2686
                );
2687
2688
                $studentInfo = api_get_user_info($studentId);
2689
                if (empty($studentInfo)) {
2690
                    $this->logger->addInfo("Student id not found: $studentId");
2691
                    continue;
2692
                }
2693
2694
                $careerId = $row['CareerId'];
2695
                $item = $extraFieldValue->get_item_id_from_field_variable_and_field_value(
2696
                    $extraFieldName,
2697
                    $careerId
2698
                );
2699
2700
                $careerChamiloId = null;
2701
                if (empty($item)) {
2702
                    $this->logger->addInfo("Career not found: $careerId");
2703
                    continue;
2704
                } else {
2705
                    if (isset($item['item_id'])) {
2706
                        $careerChamiloId = $item['item_id'];
2707
                    } else {
2708
                        continue;
2709
                    }
2710
                }
2711
2712
                if (UserManager::userHasCareer($studentId, $careerChamiloId) === false) {
2713
                    $this->logger->addInfo(
2714
                        "User $studentId (".$row['StudentId'].") has no career #$careerChamiloId (ext #$careerId)"
2715
                    );
2716
                    continue;
2717
                }
2718
2719
                $userCareerData = UserManager::getUserCareer($studentId, $careerChamiloId);
2720
2721
                $extraData = isset($userCareerData['extra_data']) && !empty($userCareerData['extra_data']) ? unserialize($userCareerData['extra_data']) : [];
2722
2723
                $teacherInfo = api_get_user_info_from_username($row['TeacherUsername']);
2724
                $teacherName = $row['TeacherUsername'];
2725
                if ($teacherInfo) {
2726
                    $teacherName = $teacherInfo['complete_name'];
2727
                }
2728
2729
                $extraData[$row['CourseId']][$row['ResultId']] = [
2730
                    'Description' => $row['Description'],
2731
                    'Period' => $row['Period'],
2732
                    'TeacherText' => $row['TeacherText'],
2733
                    'TeacherUsername' => $teacherName,
2734
                    'ScoreText' => $row['ScoreText'],
2735
                    'ScoreValue' => $row['ScoreValue'],
2736
                    'Info' => $row['Info'],
2737
                    'BgColor' => $row['BgColor'],
2738
                    'Color' => $row['Color'],
2739
                    'BorderColor' => $row['BorderColor'],
2740
                    'Icon' => $row['Icon'],
2741
                    'IconColor' => $row['IconColor'],
2742
                ];
2743
                $serializedValue = serialize($extraData);
2744
2745
                UserManager::updateUserCareer($userCareerData['id'], $serializedValue);
2746
            }
2747
        }
2748
    }
2749
2750
    /**
2751
     * @param $file
2752
     * @param bool  $moveFile
2753
     * @param array $teacherBackup
2754
     * @param array $groupBackup
2755
     */
2756
    private function importCareersDiagram(
2757
        $file,
2758
        $moveFile = false,
2759
        &$teacherBackup = [],
2760
        &$groupBackup = []
2761
    ) {
2762
        $data = Import::csv_reader($file);
2763
2764
        $extraFieldValue = new ExtraFieldValue('career');
2765
        $extraFieldName = $this->extraFieldIdNameList['career'];
2766
        $externalEventId = null;
2767
2768
        $extraField = new ExtraField('career');
2769
        $extraFieldInfo = $extraField->get_handler_field_info_by_field_variable($extraFieldName);
2770
2771
        $careerDiagramExtraFieldName = $this->extraFieldIdNameList['career_diagram'];
2772
        $extraFieldDiagramInfo = $extraField->get_handler_field_info_by_field_variable(
2773
            $careerDiagramExtraFieldName
2774
        );
2775
2776
        if (empty($extraFieldInfo) || empty($extraFieldDiagramInfo)) {
2777
            return false;
2778
        }
2779
2780
        if (!empty($data)) {
2781
            $this->logger->addInfo(count($data).' records found.');
2782
            $values = [];
2783
            foreach ($data as $row) {
2784
                if (empty($row)) {
2785
                    continue;
2786
                }
2787
                foreach ($row as $key => $value) {
2788
                    $key = (string) trim($key);
2789
                    // Remove utf8 bom
2790
                    $key = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $key);
2791
                    $row[$key] = $value;
2792
                }
2793
                $values[$row['Column']][] = $row;
2794
            }
2795
2796
            $careerList = [];
2797
            $careerNameList = [];
2798
            ksort($values);
2799
            $careerChamiloIdList = [];
2800
            // 1. First create all items
2801
            foreach ($values as $column => $rowList) {
2802
                foreach ($rowList as $row) {
2803
                    $careerId = $row['CareerId'];
2804
                    $item = $extraFieldValue->get_item_id_from_field_variable_and_field_value(
2805
                        $extraFieldName,
2806
                        $careerId,
2807
                        false,
2808
                        false,
2809
                        false
2810
                    );
2811
2812
                    if (empty($item)) {
2813
                        $this->logger->addInfo("Career not found: $careerId");
2814
                        continue;
2815
                    } else {
2816
                        if (isset($item['item_id'])) {
2817
                            $careerChamiloId = $item['item_id'];
2818
                            $career = new Career();
2819
                            $career = $career->find($careerChamiloId);
2820
                            $chamiloCareerName = $career['name'];
2821
                            $careerNameList[$careerId] = $chamiloCareerName;
2822
                            $careerChamiloIdList[$careerId] = $careerChamiloId;
2823
                        } else {
2824
                            continue;
2825
                        }
2826
                    }
2827
2828
                    if (empty($chamiloCareerName)) {
2829
                        $this->logger->addInfo("Career not found: $careerId");
2830
                        continue;
2831
                    }
2832
2833
                    if (isset($careerList[$careerId])) {
2834
                        $graph = $careerList[$careerId];
2835
                    } else {
2836
                        $graph = new Graph($careerId);
2837
                        $graph->setAttribute('graphviz.graph.rankdir', 'LR');
2838
                        $careerList[$careerId] = $graph;
2839
                    }
2840
2841
                    $currentCourseId = $row['CourseId'];
2842
                    $name = $row['CourseName'];
2843
                    $notes = $row['Notes'];
2844
                    $groupValue = $row['Group'];
2845
                    $boxColumn = $row['Column'];
2846
                    $rowValue = $row['Row'];
2847
                    $color = isset($row['DefinedColor']) ? $row['DefinedColor'] : '';
2848
                    $arrow = isset($row['DrawArrowFrom']) ? $row['DrawArrowFrom'] : '';
2849
                    $subGroup = isset($row['SubGroup']) ? $row['SubGroup'] : '';
2850
                    $connections = isset($row['Connections']) ? $row['Connections'] : '';
2851
                    $linkedElement = isset($row['LinkedElement']) ? $row['LinkedElement'] : '';
2852
2853
                    if ($graph->hasVertex($currentCourseId)) {
2854
                        // Avoid double insertion
2855
                        continue;
2856
                    } else {
2857
                        $current = $graph->createVertex($currentCourseId);
2858
                        $current->setAttribute('graphviz.label', $name);
2859
                        $current->setAttribute('DefinedColor', $color);
2860
                        $current->setAttribute('Notes', $notes);
2861
                        $current->setAttribute('Row', $rowValue);
2862
                        $current->setAttribute('Group', $groupValue);
2863
                        $current->setAttribute('Column', $boxColumn);
2864
                        $current->setAttribute('DrawArrowFrom', $arrow);
2865
                        $current->setAttribute('SubGroup', $subGroup);
2866
                        $current->setAttribute('Connections', $connections);
2867
                        $current->setAttribute('LinkedElement', $linkedElement);
2868
                        $current->setAttribute('graphviz.shape', 'box');
2869
                        $current->setGroup($column);
2870
                    }
2871
                }
2872
            }
2873
2874
            // 2. Create connections
2875
            // $column start with 1 (depending in Column row)
2876
            foreach ($values as $column => $rowList) {
2877
                foreach ($rowList as $row) {
2878
                    $careerId = $row['CareerId'];
2879
                    if (isset($careerList[$careerId])) {
2880
                        $graph = $careerList[$careerId];
2881
                    } else {
2882
                        continue;
2883
                    }
2884
2885
                    $currentCourseId = $row['CourseId'];
2886
                    if ($graph->hasVertex($currentCourseId)) {
2887
                        $current = $graph->getVertex($currentCourseId);
2888
                    } else {
2889
                        continue;
2890
                    }
2891
2892
                    if (isset($row['DependedOn']) && !empty($row['DependedOn'])) {
2893
                        $parentList = explode(',', $row['DependedOn']);
2894
                        foreach ($parentList as $parentId) {
2895
                            $parentId = (int) $parentId;
2896
                            if ($graph->hasVertex($parentId)) {
2897
                                /** @var Vertex $parent */
2898
                                $parent = $graph->getVertex($parentId);
2899
                                /*$parent->setAttribute('graphviz.color', 'red');
2900
                                $parent->setAttribute('graphviz.label', $name);
2901
                                $parent->setAttribute('graphviz.shape', 'square');*/
2902
                                $parent->createEdgeTo($current);
2903
                            }
2904
                        }
2905
                    }
2906
                }
2907
            }
2908
2909
            /** @var Graph $graph */
2910
            foreach ($careerList as $id => $graph) {
2911
                if (isset($careerChamiloIdList[$id])) {
2912
                    $params = [
2913
                        'item_id' => $careerChamiloIdList[$id],
2914
                        'extra_'.$careerDiagramExtraFieldName => serialize($graph),
2915
                        'extra_'.$extraFieldName => $id,
2916
                    ];
2917
                    $extraFieldValue->saveFieldValues($params, true);
2918
                }
2919
            }
2920
        }
2921
    }
2922
2923
    /**
2924
     * @param string $file
2925
     * @param bool   $moveFile
2926
     * @param array  $teacherBackup
2927
     * @param array  $groupBackup
2928
     */
2929
    private function importUnsubscribeStatic(
2930
        $file,
2931
        $moveFile = false,
2932
        &$teacherBackup = [],
2933
        &$groupBackup = []
2934
    ) {
2935
        $data = Import::csv_reader($file);
2936
2937
        if (!empty($data)) {
2938
            $this->logger->addInfo(count($data)." records found.");
2939
            foreach ($data as $row) {
2940
                $chamiloUserName = $row['UserName'];
2941
                $chamiloCourseCode = $row['CourseCode'];
2942
                $chamiloSessionId = $row['SessionID'];
2943
2944
                $sessionInfo = api_get_session_info($chamiloSessionId);
2945
2946
                if (empty($sessionInfo)) {
2947
                    $this->logger->addError('Session does not exists: '.$chamiloSessionId);
2948
                    continue;
2949
                }
2950
2951
                $courseInfo = api_get_course_info($chamiloCourseCode);
2952
                if (empty($courseInfo)) {
2953
                    $this->logger->addError('Course does not exists: '.$courseInfo);
2954
                    continue;
2955
                }
2956
2957
                $userId = UserManager::get_user_id_from_username($chamiloUserName);
2958
2959
                if (empty($userId)) {
2960
                    $this->logger->addError('User does not exists: '.$chamiloUserName);
2961
                    continue;
2962
                }
2963
2964
                $sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_COURSE_USER)."
2965
                        WHERE
2966
                            user_id = ".$userId." AND
2967
                            c_id = '".$courseInfo['real_id']."'
2968
                        ";
2969
                $result = Database::query($sql);
2970
                $rows = Database::num_rows($result);
2971
                if ($rows > 0) {
2972
                    $userCourseData = Database::fetch_array($result, 'ASSOC');
2973
                    if (!empty($userCourseData)) {
2974
                        $teacherBackup[$userId][$courseInfo['code']] = $userCourseData;
2975
                    }
2976
                }
2977
2978
                $sql = "SELECT * FROM ".Database::get_course_table(TABLE_GROUP_USER)."
2979
                        WHERE
2980
                            user_id = ".$userId." AND
2981
                            c_id = '".$courseInfo['real_id']."'
2982
                        ";
2983
2984
                $result = Database::query($sql);
2985
                while ($groupData = Database::fetch_array($result, 'ASSOC')) {
2986
                    $groupBackup['user'][$userId][$courseInfo['code']][$groupData['group_id']] = $groupData;
2987
                }
2988
2989
                $sql = "SELECT * FROM ".Database::get_course_table(TABLE_GROUP_TUTOR)."
2990
                        WHERE
2991
                            user_id = ".$userId." AND
2992
                            c_id = '".$courseInfo['real_id']."'
2993
                        ";
2994
2995
                $result = Database::query($sql);
2996
                while ($groupData = Database::fetch_array($result, 'ASSOC')) {
2997
                    $groupBackup['tutor'][$userId][$courseInfo['code']][$groupData['group_id']] = $groupData;
2998
                }
2999
3000
                CourseManager::unsubscribe_user(
3001
                    $userId,
3002
                    $courseInfo['code'],
3003
                    $chamiloSessionId
3004
                );
3005
3006
                $this->logger->addError(
3007
                    "User '$chamiloUserName' was removed from session: #$chamiloSessionId, Course: ".$courseInfo['code']
3008
                );
3009
            }
3010
        }
3011
3012
        if ($moveFile) {
3013
            $this->moveFile($file);
3014
        }
3015
    }
3016
3017
    /**
3018
     *  Dump database tables.
3019
     */
3020
    private function dumpDatabaseTables()
3021
    {
3022
        echo 'Dumping tables'.PHP_EOL;
3023
3024
        // User
3025
        $table = Database::get_main_table(TABLE_MAIN_USER);
3026
        $tableAdmin = Database::get_main_table(TABLE_MAIN_ADMIN);
3027
        $sql = "DELETE FROM $table
3028
                WHERE user_id not in (select user_id from $tableAdmin) and status <> ".ANONYMOUS;
3029
        Database::query($sql);
3030
        echo $sql.PHP_EOL;
3031
3032
        // Truncate tables
3033
        $truncateTables = [
3034
            Database::get_main_table(TABLE_MAIN_COURSE),
3035
            Database::get_main_table(TABLE_MAIN_COURSE_USER),
3036
            Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE),
3037
            Database::get_main_table(TABLE_MAIN_CATEGORY),
3038
            Database::get_main_table(TABLE_MAIN_COURSE_MODULE),
3039
            Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER),
3040
            Database::get_main_table(TABLE_MAIN_SESSION),
3041
            Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY),
3042
            Database::get_main_table(TABLE_MAIN_SESSION_COURSE),
3043
            Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER),
3044
            Database::get_main_table(TABLE_MAIN_SESSION_USER),
3045
            Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION),
3046
            Database::get_main_table(TABLE_MAIN_SESSION_FIELD_VALUES),
3047
            Database::get_main_table(TABLE_MAIN_COURSE_FIELD_VALUES),
3048
            Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES),
3049
            Database::get_main_table(TABLE_MAIN_USER_FIELD),
3050
            Database::get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS),
3051
            Database::get_main_table(TABLE_MAIN_COURSE_FIELD),
3052
            Database::get_main_table(TABLE_MAIN_COURSE_FIELD_VALUES),
3053
            Database::get_main_table(TABLE_MAIN_SESSION_FIELD),
3054
            Database::get_main_table(TABLE_MAIN_SESSION_FIELD_VALUES),
3055
            Database::get_course_table(TABLE_AGENDA),
3056
            Database::get_course_table(TABLE_AGENDA_ATTACHMENT),
3057
            Database::get_course_table(TABLE_AGENDA_REPEAT),
3058
            Database::get_course_table(TABLE_AGENDA_REPEAT_NOT),
3059
            Database::get_main_table(TABLE_PERSONAL_AGENDA),
3060
            Database::get_main_table(TABLE_PERSONAL_AGENDA_REPEAT_NOT),
3061
            Database::get_main_table(TABLE_PERSONAL_AGENDA_REPEAT),
3062
            Database::get_main_table(TABLE_MAIN_CALENDAR_EVENT_VALUES),
3063
            Database::get_main_table(TABLE_STATISTIC_TRACK_E_LASTACCESS),
3064
            Database::get_main_table(TABLE_STATISTIC_TRACK_E_ACCESS),
3065
            Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN),
3066
            Database::get_main_table(TABLE_STATISTIC_TRACK_E_DOWNLOADS),
3067
            Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES),
3068
            Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT),
3069
            Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT_RECORDING),
3070
            Database::get_main_table(TABLE_STATISTIC_TRACK_E_DEFAULT),
3071
            Database::get_main_table(TABLE_STATISTIC_TRACK_E_UPLOADS),
3072
            Database::get_main_table(TABLE_STATISTIC_TRACK_E_HOTSPOT),
3073
            Database::get_main_table(TABLE_STATISTIC_TRACK_E_ITEM_PROPERTY),
3074
            Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY),
3075
            Database::get_main_table(TABLE_MAIN_GRADEBOOK_EVALUATION),
3076
            Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINKEVAL_LOG),
3077
            Database::get_main_table(TABLE_MAIN_GRADEBOOK_RESULT),
3078
            Database::get_main_table(TABLE_MAIN_GRADEBOOK_RESULT_LOG),
3079
            Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINK),
3080
            Database::get_main_table(TABLE_MAIN_GRADEBOOK_SCORE_DISPLAY),
3081
            Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE),
3082
            Database::get_course_table(TABLE_STUDENT_PUBLICATION),
3083
            Database::get_course_table(TABLE_QUIZ_QUESTION),
3084
            Database::get_course_table(TABLE_QUIZ_TEST),
3085
            Database::get_course_table(TABLE_QUIZ_ORDER),
3086
            Database::get_course_table(TABLE_QUIZ_ANSWER),
3087
            Database::get_course_table(TABLE_QUIZ_TEST_QUESTION),
3088
            Database::get_course_table(TABLE_QUIZ_QUESTION_OPTION),
3089
            Database::get_course_table(TABLE_QUIZ_QUESTION_CATEGORY),
3090
            Database::get_course_table(TABLE_QUIZ_QUESTION_REL_CATEGORY),
3091
            Database::get_course_table(TABLE_LP_MAIN),
3092
            Database::get_course_table(TABLE_LP_ITEM),
3093
            Database::get_course_table(TABLE_LP_VIEW),
3094
            Database::get_course_table(TABLE_LP_ITEM_VIEW),
3095
            Database::get_course_table(TABLE_DOCUMENT),
3096
            Database::get_course_table(TABLE_ITEM_PROPERTY),
3097
            Database::get_course_table(TABLE_TOOL_LIST),
3098
            Database::get_course_table(TABLE_TOOL_INTRO),
3099
            Database::get_course_table(TABLE_COURSE_SETTING),
3100
            Database::get_course_table(TABLE_SURVEY),
3101
            Database::get_course_table(TABLE_SURVEY_QUESTION),
3102
            Database::get_course_table(TABLE_SURVEY_QUESTION_OPTION),
3103
            Database::get_course_table(TABLE_SURVEY_INVITATION),
3104
            Database::get_course_table(TABLE_SURVEY_ANSWER),
3105
            Database::get_course_table(TABLE_SURVEY_QUESTION_GROUP),
3106
            Database::get_course_table(TABLE_SURVEY_REPORT),
3107
            Database::get_course_table(TABLE_GLOSSARY),
3108
            Database::get_course_table(TABLE_LINK),
3109
            Database::get_course_table(TABLE_LINK_CATEGORY),
3110
            Database::get_course_table(TABLE_GROUP),
3111
            Database::get_course_table(TABLE_GROUP_USER),
3112
            Database::get_course_table(TABLE_GROUP_TUTOR),
3113
            Database::get_course_table(TABLE_GROUP_CATEGORY),
3114
            Database::get_course_table(TABLE_DROPBOX_CATEGORY),
3115
            Database::get_course_table(TABLE_DROPBOX_FEEDBACK),
3116
            Database::get_course_table(TABLE_DROPBOX_POST),
3117
            Database::get_course_table(TABLE_DROPBOX_FILE),
3118
            Database::get_course_table(TABLE_DROPBOX_PERSON),
3119
        ];
3120
3121
        foreach ($truncateTables as $table) {
3122
            $sql = "TRUNCATE $table";
3123
            Database::query($sql);
3124
            echo $sql.PHP_EOL;
3125
        }
3126
3127
        $table = Database::get_course_table(TABLE_ITEM_PROPERTY);
3128
        $sql = "DELETE FROM $table WHERE tool = 'calendar_event'";
3129
        Database::query($sql);
3130
        echo $sql.PHP_EOL;
3131
    }
3132
3133
    /**
3134
     * If csv file ends with '"' character then a '";' is added.
3135
     *
3136
     * @param string $file
3137
     */
3138
    private function fixCSVFile($file)
3139
    {
3140
        /*$f = fopen($file, 'r+');
3141
        $cursor = -1;
3142
3143
        fseek($f, $cursor, SEEK_END);
3144
        $char = fgetc($f);
3145
        while ($char === "\n" || $char === "\r") {
3146
            fseek($f, $cursor--, SEEK_END);
3147
            $char = fgetc($f);
3148
        }
3149
3150
        if ($char === "\"") {
3151
            fseek($f, -1, SEEK_CUR);
3152
            fwrite($f, '";');
3153
        }*/
3154
    }
3155
}
3156
3157
$logger = new Logger('cron');
3158
$emails = isset($_configuration['cron_notification_mails']) ? $_configuration['cron_notification_mails'] : null;
3159
3160
$minLevel = Logger::DEBUG;
3161
3162
if (!is_array($emails)) {
3163
    $emails = [$emails];
3164
}
3165
$subject = "Cron main/cron/import_csv.php ".date('Y-m-d h:i:s');
3166
$from = api_get_setting('emailAdministrator');
3167
/*
3168
if (!empty($emails)) {
3169
    foreach ($emails as $email) {
3170
        $stream = new NativeMailerHandler($email, $subject, $from, $minLevel);
3171
        $logger->pushHandler(new BufferHandler($stream, 0, $minLevel));
3172
    }
3173
}*/
3174
3175
$stream = new StreamHandler(
3176
    api_get_path(SYS_ARCHIVE_PATH).'import_csv.log',
3177
    $minLevel
3178
);
3179
$logger->pushHandler(new BufferHandler($stream, 0, $minLevel));
3180
$logger->pushHandler(new RotatingFileHandler('import_csv', 5, $minLevel));
3181
3182
$cronImportCSVConditions = isset($_configuration['cron_import_csv_conditions']) ? $_configuration['cron_import_csv_conditions'] : null;
3183
3184
echo 'See the error log here: '.api_get_path(SYS_ARCHIVE_PATH).'import_csv.log'."\n";
3185
3186
$import = new ImportCsv($logger, $cronImportCSVConditions);
3187
3188
if (isset($_configuration['default_admin_user_id_for_cron'])) {
3189
    $import->defaultAdminId = $_configuration['default_admin_user_id_for_cron'];
3190
}
3191
// @todo in production disable the dump option
3192
$dump = false;
3193
3194
if (isset($argv[1]) && $argv[1] = '--dump') {
3195
    $dump = true;
3196
}
3197
3198
if (isset($_configuration['import_csv_disable_dump']) &&
3199
    $_configuration['import_csv_disable_dump'] == true
3200
) {
3201
    $import->setDumpValues(false);
3202
} else {
3203
    $import->setDumpValues($dump);
3204
}
3205
3206
$import->setUpdateEmailToDummy(api_get_configuration_value('update_users_email_to_dummy_except_admins'));
3207
3208
// Do not moves the files to treated
3209
if (isset($_configuration['import_csv_test'])) {
3210
    $import->test = $_configuration['import_csv_test'];
3211
} else {
3212
    $import->test = true;
3213
}
3214
3215
$languageFilesToLoad = api_get_language_files_to_load($import->defaultLanguage);
3216
3217
foreach ($languageFilesToLoad as $languageFile) {
3218
    include $languageFile;
3219
}
3220
3221
// Set default language to be loaded
3222
$language = $import->defaultLanguage;
3223
global $language_interface;
3224
$language_interface = $language;
3225
global $language_interface_initial_value;
3226
$language_interface_initial_value = $language;
3227
3228
$timeStart = microtime(true);
3229
$import->run();
3230
$timeEnd = microtime(true);
3231
$executionTime = round(($timeEnd - $timeStart) / 60, 2);
3232
$logger->addInfo("Total execution Time $executionTime Min");
3233
3234
if (isset($_configuration['import_csv_fix_permissions']) &&
3235
    $_configuration['import_csv_fix_permissions'] == true
3236
) {
3237
    $command = "sudo find ".api_get_path(SYS_COURSE_PATH)." -type d -exec chmod 777 {} \; ";
3238
    echo "Executing: ".$command.PHP_EOL;
3239
    system($command);
3240
3241
    $command = "sudo find ".api_get_path(SYS_CODE_PATH)."upload/users  -type d -exec chmod 777 {} \;";
3242
    echo "Executing: ".$command.PHP_EOL;
3243
    system($command);
3244
}
3245