ImportCsv::importCareers()   C
last analyzed

Complexity

Conditions 14
Paths 31

Size

Total Lines 87
Code Lines 60

Duplication

Lines 0
Ratio 0 %

Importance

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