Completed
Push — master ( 9b8b24...6e1754 )
by Julito
58:58
created

ImportCsv::importSessionsExtIdStatic()   C

Complexity

Conditions 10
Paths 4

Size

Total Lines 66
Code Lines 44

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 10
eloc 44
nc 4
nop 2
dl 0
loc 66
rs 6.2025
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/* For licensing terms, see /license.txt */
3
4
use Chamilo\CourseBundle\Entity\CCalendarEvent;
5
use Chamilo\CourseBundle\Entity\CItemProperty;
6
use Chamilo\PluginBundle\Entity\StudentFollowUp\CarePost;
7
use Fhaculty\Graph\Graph;
8
use Graphp\GraphViz\GraphViz;
9
use Monolog\Logger;
10
use Monolog\Handler\StreamHandler;
11
use Monolog\Handler\NativeMailerHandler;
12
use Monolog\Handler\RotatingFileHandler;
13
use Monolog\Handler\BufferHandler;
14
15
if (PHP_SAPI != 'cli') {
16
    die('Run this script through the command line or comment this line in the code');
17
}
18
19
if (file_exists('multiple_url_fix.php')) {
20
    require 'multiple_url_fix.php';
21
}
22
23
require_once __DIR__.'/../inc/global.inc.php';
24
25
ini_set('memory_limit', -1);
26
ini_set('max_execution_time', 0);
27
ini_set('log_errors', '1');
28
ini_set('display_errors', '1');
29
30
/**
31
 * Class ImportCsv
32
 */
33
class ImportCsv
34
{
35
    private $logger;
36
    private $dumpValues;
37
    public $test;
38
    public $defaultLanguage = 'dutch';
39
    public $extraFieldIdNameList = array(
40
        'session' => 'external_session_id',
41
        'session_career' => 'external_career_id',
42
        'course' => 'external_course_id',
43
        'user' => 'external_user_id',
44
        'calendar_event' => 'external_calendar_event_id',
45
        'career' => 'external_career_id',
46
        'career_urls' => 'career_urls',
47
        'career_diagram' => 'career_diagram',
48
    );
49
    public $defaultAdminId = 1;
50
    public $defaultSessionVisibility = 1;
51
52
    /**
53
     * When creating a user the expiration date is set to registration date + this value
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
     * @var int number of years
63
     */
64
    public $expirationDateInUserUpdate = 1;
65
    public $daysCoachAccessBeforeBeginning = 14;
66
    public $daysCoachAccessAfterBeginning = 14;
67
    public $conditions;
68
    private $updateEmailToDummy;
69
70
    /**
71
     * @param Monolog\Logger $logger
72
     * @param array
73
     */
74
    public function __construct($logger, $conditions)
75
    {
76
        $this->logger = $logger;
77
        $this->conditions = $conditions;
78
        $this->updateEmailToDummy = false;
79
    }
80
81
    /**
82
     * @param bool $dump
83
     */
84
    public function setDumpValues($dump)
85
    {
86
        $this->dumpValues = $dump;
87
    }
88
89
    /**
90
     * @return boolean
91
     */
92
    public function getDumpValues()
93
    {
94
        return $this->dumpValues;
95
    }
96
97
    /**
98
     * Runs the import process
99
     */
100
    public function run()
101
    {
102
        global $_configuration;
103
104
        $value = api_get_configuration_value('import_csv_custom_url_id');
105
        if (!empty($value)) {
106
            $_configuration['access_url'] = $value;
107
        }
108
109
        $path = api_get_path(SYS_CODE_PATH).'cron/incoming/';
110
        if (!is_dir($path)) {
111
            echo "The folder! $path does not exits";
112
113
            return 0;
114
        }
115
116
        if ($this->getDumpValues()) {
117
            $this->dumpDatabaseTables();
118
        }
119
120
        echo "Reading files: ".PHP_EOL.PHP_EOL;
121
122
        $files = scandir($path);
123
        $fileToProcess = array();
124
        $fileToProcessStatic = array();
125
        $teacherBackup = array();
126
        $groupBackup = array();
127
128
        if (!empty($files)) {
129
            foreach ($files as $file) {
130
                $fileInfo = pathinfo($file);
131
                if (isset($fileInfo['extension']) && $fileInfo['extension'] === 'csv') {
132
                    // Checking teachers_yyyymmdd.csv, courses_yyyymmdd.csv, students_yyyymmdd.csv and sessions_yyyymmdd.csv
133
                    $parts = explode('_', $fileInfo['filename']);
134
                    $preMethod = ucwords($parts[1]);
135
                    $preMethod = str_replace('-static', 'Static', $preMethod);
136
                    $method = 'import'.$preMethod;
137
138
                    $isStatic = strpos($method, 'Static');
139
140
                    if ($method == 'importSessionsextidStatic') {
141
                        $method = 'importSessionsExtIdStatic';
142
                    }
143
144
                    if ($method == 'importCourseinsertStatic') {
145
                        $method = 'importSubscribeUserToCourse';
146
                    }
147
148
                    if ($method == 'importUnsubsessionsextidStatic') {
149
                        $method = 'importUnsubsessionsExtidStatic';
150
                    }
151
152
                    if ($method == 'importCareersdiagram') {
153
                        $method = 'importCareersDiagram';
154
                    }
155
156
                    if ($method == 'importSubsessionsextidStatic') {
157
                        $method = 'importSubscribeUserToCourseSessionExtStatic';
158
                    }
159
                    if (method_exists($this, $method)) {
160
                        if ((
161
                                $method == 'importSubscribeStatic' ||
162
                                $method == 'importSubscribeUserToCourse'
163
                            ) ||
164
                            empty($isStatic)
165
                        ) {
166
                            $fileToProcess[$parts[1]][] = array(
167
                                'method' => $method,
168
                                'file' => $path.$fileInfo['basename']
169
                            );
170
                        } else {
171
                            $fileToProcessStatic[$parts[1]][] = array(
172
                                'method' => $method,
173
                                'file' => $path.$fileInfo['basename']
174
                            );
175
                        }
176
                    } else {
177
                        echo "Error - This file '$file' can't be processed.".PHP_EOL;
178
                        echo "Trying to call $method".PHP_EOL;
179
180
                        echo "The file have to has this format:".PHP_EOL;
181
                        echo "prefix_students_ddmmyyyy.csv, prefix_teachers_ddmmyyyy.csv, prefix_courses_ddmmyyyy.csv, prefix_sessions_ddmmyyyy.csv ".PHP_EOL;
182
                        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...
183
                    }
184
                }
185
            }
186
187
            if (empty($fileToProcess) && empty($fileToProcessStatic)) {
188
                echo 'Error - no files to process.';
189
190
                return 0;
191
            }
192
193
            $this->prepareImport();
194
195
            $sections = array(
196
                'students',
197
                'teachers',
198
                'courses',
199
                'sessions',
200
                'subscribe-static',
201
                'courseinsert-static',
202
                'unsubscribe-static',
203
                'care',
204
                'careers',
205
                'careersdiagram'
206
            );
207
208
            foreach ($sections as $section) {
209
                $this->logger->addInfo("-- Import $section --");
210
211
                if (isset($fileToProcess[$section]) && !empty($fileToProcess[$section])) {
212
                    $files = $fileToProcess[$section];
213
                    foreach ($files as $fileInfo) {
214
                        $method = $fileInfo['method'];
215
                        $file = $fileInfo['file'];
216
217
                        echo 'File: '.$file.PHP_EOL;
218
                        echo 'Method : '.$method.PHP_EOL;
219
                        echo PHP_EOL;
220
                        $this->logger->addInfo("Reading file: $file");
221
                        $this->logger->addInfo("Loading method $method ");
222
                        if ($method == 'importSessions') {
223
                            $this->$method(
224
                                $file,
225
                                true,
226
                                $teacherBackup,
227
                                $groupBackup
228
                            );
229
                        } else {
230
                            $this->$method($file, true);
231
                        }
232
                        $this->logger->addInfo("--Finish reading file--");
233
                    }
234
                }
235
            }
236
237
            $sections = array(
238
                'students-static',
239
                'teachers-static',
240
                'courses-static',
241
                'sessions-static',
242
                'calendar-static',
243
                'sessionsextid-static',
244
                'unsubscribe-static',
245
                'unsubsessionsextid-static',
246
                'subsessionsextid-static'
247
            );
248
249
            foreach ($sections as $section) {
250
                $this->logger->addInfo("-- Import static files $section --");
251
252
                if (isset($fileToProcessStatic[$section]) &&
253
                    !empty($fileToProcessStatic[$section])
254
                ) {
255
                    $files = $fileToProcessStatic[$section];
256
                    foreach ($files as $fileInfo) {
257
                        $method = $fileInfo['method'];
258
259
                        $file = $fileInfo['file'];
260
                        echo 'Static file: '.$file.PHP_EOL;
261
                        echo 'Method : '.$method.PHP_EOL;
262
                        echo PHP_EOL;
263
                        $this->logger->addInfo("Reading static file: $file");
264
                        $this->logger->addInfo("Loading method $method ");
265
                        $this->$method(
266
                            $file,
267
                            true,
268
                            $teacherBackup,
269
                            $groupBackup
270
                        );
271
                        $this->logger->addInfo("--Finish reading file--");
272
                    }
273
                }
274
            }
275
            $this->logger->addInfo("teacher backup");
276
            $this->logger->addInfo(print_r($teacherBackup, 1));
277
        }
278
    }
279
280
    /**
281
     * Prepares extra fields before the import
282
     */
283
    private function prepareImport()
284
    {
285
        // Create user extra field: extra_external_user_id
286
        UserManager::create_extra_field(
287
            $this->extraFieldIdNameList['user'],
288
            1,
289
            'External user id',
290
            null
291
        );
292
293
        // Create course extra field: extra_external_course_id
294
        CourseManager::create_course_extra_field(
295
            $this->extraFieldIdNameList['course'],
296
            1,
297
            'External course id',
298
            ''
299
        );
300
301
        // Create session extra field extra_external_session_id
302
        SessionManager::create_session_extra_field(
303
            $this->extraFieldIdNameList['session'],
304
            1,
305
            'External session id'
306
        );
307
308
        SessionManager::create_session_extra_field(
309
            $this->extraFieldIdNameList['session_career'],
310
            1,
311
            'Career id'
312
        );
313
314
        // Create calendar_event extra field extra_external_session_id
315
        $extraField = new ExtraField('calendar_event');
316
        $extraField->save(
317
            array(
318
                'field_type' => ExtraField::FIELD_TYPE_TEXT,
319
                'variable' => $this->extraFieldIdNameList['calendar_event'],
320
                'display_text' => 'External calendar event id',
321
            )
322
        );
323
324
        $extraField = new ExtraField('career');
325
        $extraField->save(
326
            array(
327
                'visible_to_self' => 1,
328
                'field_type' => ExtraField::FIELD_TYPE_TEXT,
329
                'variable' => $this->extraFieldIdNameList['career'],
330
                'display_text' => 'External career id',
331
            )
332
        );
333
334
        $extraField->save(
335
            array(
336
                'visible_to_self' => 1,
337
                'field_type' => ExtraField::FIELD_TYPE_TEXTAREA,
338
                'variable' => $this->extraFieldIdNameList['career_diagram'],
339
                'display_text' => 'Career diagram',
340
            )
341
        );
342
343
        $extraField->save(
344
            array(
345
                'visible_to_self' => 1,
346
                'field_type' => ExtraField::FIELD_TYPE_TEXTAREA,
347
                'variable' => $this->extraFieldIdNameList['career_urls'],
348
                'display_text' => 'Career urls',
349
            )
350
        );
351
    }
352
353
    /**
354
     * @param string $file
355
     */
356
    private function moveFile($file)
357
    {
358
        $moved = str_replace('incoming', 'treated', $file);
359
360
        if ($this->test) {
361
            $result = 1;
362
        } else {
363
            $result = rename($file, $moved);
364
        }
365
366
        if ($result) {
367
            $this->logger->addInfo("Moving file to the treated folder: $file");
368
        } else {
369
            $this->logger->addError(
370
                "Error - Cant move file to the treated folder: $file"
371
            );
372
        }
373
    }
374
375
    /**
376
     * @param array $row
377
     *
378
     * @return array
379
     */
380
    private function cleanUserRow($row)
381
    {
382
        $row['lastname'] = $row['LastName'];
383
        $row['firstname'] = $row['FirstName'];
384
        $row['email'] = $row['Email'];
385
        $row['username'] = $row['UserName'];
386
        $row['password'] = $row['Password'];
387
        $row['auth_source'] = isset($row['AuthSource']) ? $row['AuthSource'] : PLATFORM_AUTH_SOURCE;
388
        $row['official_code'] = $row['OfficialCode'];
389
        $row['phone'] = isset($row['PhoneNumber']) ? $row['PhoneNumber'] : '';
390
391
        if (isset($row['StudentID'])) {
392
            $row['extra_'.$this->extraFieldIdNameList['user']] = $row['StudentID'];
393
        }
394
395
        if (isset($row['TeacherID'])) {
396
            $row['extra_'.$this->extraFieldIdNameList['user']] = $row['TeacherID'];
397
        }
398
399
        return $row;
400
    }
401
402
    /**
403
     * @param array $row
404
     *
405
     * @return array
406
     */
407
    private function cleanCourseRow($row)
408
    {
409
        $row['title'] = $row['Title'];
410
        $row['course_code'] = $row['Code'];
411
        $row['course_category'] = $row['CourseCategory'];
412
        $row['email'] = $row['Teacher'];
413
        $row['language'] = $row['Language'];
414
        $row['visibility'] = isset($row['Visibility']) ? $row['Visibility'] : COURSE_VISIBILITY_REGISTERED;
415
416
        $row['teachers'] = array();
417
        if (isset($row['Teacher']) && !empty($row['Teacher'])) {
418
            $this->logger->addInfo("Teacher list found: ".$row['Teacher']);
0 ignored issues
show
Bug introduced by
Are you sure $row['Teacher'] of type mixed|integer|array can be used in concatenation? ( Ignorable by Annotation )

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

418
            $this->logger->addInfo("Teacher list found: "./** @scrutinizer ignore-type */ $row['Teacher']);
Loading history...
419
            $teachers = explode(',', $row['Teacher']);
0 ignored issues
show
Bug introduced by
It seems like $row['Teacher'] can also be of type array; however, parameter $string of explode() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

419
            $teachers = explode(',', /** @scrutinizer ignore-type */ $row['Teacher']);
Loading history...
420
            if (!empty($teachers)) {
421
                foreach ($teachers as $teacherUserName) {
422
                    $teacherUserName = trim($teacherUserName);
423
                    $userInfo = api_get_user_info_from_username($teacherUserName);
424
                    if (!empty($userInfo)) {
425
                        $this->logger->addInfo("Username found: $teacherUserName");
426
                        $row['teachers'][] = $userInfo['user_id'];
427
                    }
428
                }
429
            }
430
        }
431
432
        if (isset($row['CourseID'])) {
433
            $row['extra_'.$this->extraFieldIdNameList['course']] = $row['CourseID'];
434
        }
435
436
        return $row;
437
    }
438
439
    /**
440
     * File to import
441
     * @param string $file
442
     */
443
    private function importTeachersStatic($file)
444
    {
445
        $this->importTeachers($file, true);
446
    }
447
448
    /**
449
     * File to import
450
     * @param string $file
451
     * @param bool $moveFile
452
     */
453
    private function importTeachers($file, $moveFile = true)
454
    {
455
        $this->fixCSVFile($file);
456
        $data = Import::csvToArray($file);
457
458
        /* Unique identifier: official-code username.
459
        Email address and password should never get updated. *ok
460
        The only fields that I can think of that should update if the data changes in the csv file are FirstName and LastName. *ok
461
        A slight edit of these fields should be taken into account. ???
462
        Adding teachers is no problem, but deleting them shouldn’t be automated, but we should get a log of “to delete teachers”.
463
        We’ll handle that manually if applicable.
464
        No delete!
465
        */
466
        $language = $this->defaultLanguage;
467
468
        if (!empty($data)) {
469
            $this->logger->addInfo(count($data)." records found.");
470
            $expirationDateOnCreation = api_get_utc_datetime(strtotime("+".intval($this->expirationDateInUserCreation)."years"));
471
            $expirationDateOnUpdate = api_get_utc_datetime(strtotime("+".intval($this->expirationDateInUserUpdate)."years"));
472
473
            $batchSize = $this->batchSize;
474
            $em = Database::getManager();
475
            $counter = 1;
476
            foreach ($data as $row) {
477
                $row = $this->cleanUserRow($row);
478
479
                $user_id = UserManager::get_user_id_from_original_id(
480
                    $row['extra_'.$this->extraFieldIdNameList['user']],
481
                    $this->extraFieldIdNameList['user']
482
                );
483
                $userInfo = array();
484
                $userInfoByOfficialCode = null;
485
486
                if (!empty($user_id)) {
487
                    $userInfo = api_get_user_info($user_id);
488
                    $userInfoByOfficialCode = api_get_user_info_from_official_code($row['official_code']);
489
                }
490
491
                if (empty($userInfo) && empty($userInfoByOfficialCode)) {
492
                    // Create user
493
                    $userId = UserManager::create_user(
494
                        $row['firstname'],
495
                        $row['lastname'],
496
                        COURSEMANAGER,
497
                        $row['email'],
498
                        $row['username'],
499
                        $row['password'],
500
                        $row['official_code'],
501
                        $language, //$row['language'],
502
                        $row['phone'],
503
                        null, //$row['picture'], //picture
504
                        $row['auth_source'], // ?
505
                        $expirationDateOnCreation, //'0000-00-00 00:00:00', //$row['expiration_date'], //$expiration_date = '0000-00-00 00:00:00',
506
                        1, //active
507
                        0,
508
                        null, // extra
509
                        null, //$encrypt_method = '',
510
                        false //$send_mail = false
511
                    );
512
513
                    if ($userId) {
514
                        foreach ($row as $key => $value) {
515
                            if (substr($key, 0, 6) == 'extra_') {
516
                                //an extra field
517
                                UserManager::update_extra_field_value(
518
                                    $userId,
519
                                    substr($key, 6),
520
                                    $value
521
                                );
522
                            }
523
                        }
524
                        $this->logger->addInfo("Teachers - User created: ".$row['username']);
525
                    } else {
526
                        $this->logger->addError("Teachers - User NOT created: ".$row['username']." ".$row['firstname']." ".$row['lastname']);
527
                        $this->logger->addError(strip_tags(Display::getFlashToString()));
528
                        Display::cleanFlashMessages();
529
                    }
530
                } else {
531
                    if (empty($userInfo)) {
532
                        $this->logger->addError("Teachers - Can't update user :".$row['username']);
533
                        continue;
534
                    }
535
536
                    // Update user
537
                    $result = UserManager::update_user(
538
                        $userInfo['user_id'],
539
                        $row['firstname'], // <<-- changed
540
                        $row['lastname'], // <<-- changed
541
                        $userInfo['username'],
542
                        null, //$password = null,
543
                        $row['auth_source'],
544
                        $userInfo['email'],
545
                        COURSEMANAGER,
546
                        $userInfo['official_code'],
547
                        $userInfo['phone'],
548
                        $userInfo['picture_uri'],
549
                        $expirationDateOnUpdate,
550
                        $userInfo['active'],
551
                        null, //$creator_id = null,
552
                        0, //$hr_dept_id = 0,
553
                        null, // $extra = null,
554
                        null, //$language = 'english',
555
                        null, //$encrypt_method = '',
556
                        false, //$send_email = false,
557
                        0 //$reset_password = 0
558
                    );
559
560
                    if ($result) {
561
                        foreach ($row as $key => $value) {
562
                            if (substr($key, 0, 6) == 'extra_') {
563
                                //an extra field
564
                                UserManager::update_extra_field_value(
565
                                    $userInfo['user_id'],
566
                                    substr($key, 6),
567
                                    $value
568
                                );
569
                            }
570
                        }
571
                        $this->logger->addInfo("Teachers - User updated: ".$row['username']);
572
                    } else {
573
                        $this->logger->addError("Teachers - User not updated: ".$row['username']);
574
                    }
575
                }
576
577
                if (($counter % $batchSize) === 0) {
578
                    $em->flush();
579
                    $em->clear(); // Detaches all objects from Doctrine!
580
                }
581
                $counter++;
582
            }
583
584
            $em->clear(); // Detaches all objects from Doctrine!
585
        }
586
587
        if ($moveFile) {
588
            $this->moveFile($file);
589
        }
590
591
        $this->updateUsersEmails();
592
    }
593
594
    /**
595
     * @param string $file
596
     */
597
    private function importStudentsStatic($file)
598
    {
599
        $this->importStudents($file, true);
600
    }
601
602
    /**
603
     * @param string $file
604
     * @param bool $moveFile
605
     */
606
    private function importStudents($file, $moveFile = true)
607
    {
608
        $this->fixCSVFile($file);
609
        $data = Import::csvToArray($file);
610
611
        /*
612
         * Another users import.
613
        Unique identifier: official code and username . ok
614
        Password should never get updated. ok
615
        If an update should need to occur (because it changed in the .csv),
616
        we’ll want that logged. We will handle this manually in that case.
617
        All other fields should be updateable, though passwords should of course not get updated. ok
618
        If a user gets deleted (not there anymore),
619
        He should be set inactive one year after the current date.
620
        So I presume you’ll just update the expiration date.
621
        We want to grant access to courses up to a year after deletion.
622
         */
623
        $timeStart = microtime(true);
624
625
        $batchSize = $this->batchSize;
626
        $em = Database::getManager();
627
628
        if (!empty($data)) {
629
            $language = $this->defaultLanguage;
630
            $this->logger->addInfo(count($data)." records found.");
631
632
            $expirationDateOnCreate = api_get_utc_datetime(strtotime("+".intval($this->expirationDateInUserCreation)."years"));
633
            $expirationDateOnUpdate = api_get_utc_datetime(strtotime("+".intval($this->expirationDateInUserUpdate)."years"));
634
635
            $counter = 1;
636
            $secondsInYear = 365 * 24 * 60 * 60;
637
638
            foreach ($data as $row) {
639
                $row = $this->cleanUserRow($row);
640
                $user_id = UserManager::get_user_id_from_original_id(
641
                    $row['extra_'.$this->extraFieldIdNameList['user']],
642
                    $this->extraFieldIdNameList['user']
643
                );
644
645
                $userInfo = array();
646
                $userInfoByOfficialCode = null;
647
                if (!empty($user_id)) {
648
                    $userInfo = api_get_user_info($user_id, false, true);
649
                    $userInfoByOfficialCode = api_get_user_info_from_official_code($row['official_code']);
650
                }
651
652
                if (empty($userInfo) && empty($userInfoByOfficialCode)) {
653
                    // Create user
654
                    $result = UserManager::create_user(
655
                        $row['firstname'],
656
                        $row['lastname'],
657
                        STUDENT,
658
                        $row['email'],
659
                        $row['username'],
660
                        $row['password'],
661
                        $row['official_code'],
662
                        $language, //$row['language'],
663
                        $row['phone'],
664
                        null, //$row['picture'], //picture
665
                        $row['auth_source'], // ?
666
                        $expirationDateOnCreate, //'0000-00-00 00:00:00', //$row['expiration_date'], //$expiration_date = '0000-00-00 00:00:00',
667
                        1, //active
668
                        0,
669
                        null, // extra
670
                        null, //$encrypt_method = '',
671
                        false //$send_mail = false
672
                    );
673
674
                    if ($result) {
675
                        foreach ($row as $key => $value) {
676
                            if (substr($key, 0, 6) === 'extra_') {
677
                                //an extra field
678
                                UserManager::update_extra_field_value(
679
                                    $result,
680
                                    substr($key, 6),
681
                                    $value
682
                                );
683
                            }
684
                        }
685
                        $this->logger->addInfo("Students - User created: ".$row['username']);
686
                    } else {
687
                        $this->logger->addError("Students - User NOT created: ".$row['username']." ".$row['firstname']." ".$row['lastname']);
688
                        $this->logger->addError(strip_tags(Display::getFlashToString()));
689
                        Display::cleanFlashMessages();
690
                    }
691
                } else {
692
                    if (empty($userInfo)) {
693
                        $this->logger->addError("Students - Can't update user :".$row['username']);
694
                        continue;
695
                    }
696
697
                    if (isset($row['action']) && $row['action'] === 'delete') {
698
                        // Inactive one year later
699
                        $userInfo['expiration_date'] = api_get_utc_datetime(api_strtotime(time() + $secondsInYear));
700
                    }
701
702
                    $password = $row['password']; // change password
703
                    $email = $row['email']; // change email
704
                    $resetPassword = 2; // allow password change
705
706
                    // Conditions that disables the update of password and email:
707
                    if (isset($this->conditions['importStudents'])) {
708
                        if (isset($this->conditions['importStudents']['update']) &&
709
                            isset($this->conditions['importStudents']['update']['avoid'])
710
                        ) {
711
                            // Blocking email update -
712
                            // 1. Condition
713
                            $avoidUsersWithEmail = $this->conditions['importStudents']['update']['avoid']['email'];
714
                            if ($userInfo['email'] != $row['email'] && in_array($row['email'], $avoidUsersWithEmail)) {
715
                                $this->logger->addInfo("Students - User email is not updated : ".$row['username']." because the avoid conditions (email).");
716
                                // Do not change email keep the old email.
717
                                $email = $userInfo['email'];
718
                            }
719
720
                            // 2. Condition
721
                            if (!in_array($userInfo['email'], $avoidUsersWithEmail) && !in_array($row['email'], $avoidUsersWithEmail)) {
722
                                $email = $userInfo['email'];
723
                            }
724
725
                            // 3. Condition
726
                            if (in_array($userInfo['email'], $avoidUsersWithEmail) && !in_array($row['email'], $avoidUsersWithEmail)) {
727
                                $email = $row['email'];
728
                            }
729
730
                            // Blocking password update
731
                            //$avoidUsersWithPassword = $this->conditions['importStudents']['update']['avoid']['password'];
732
733
                            /*if (isset($row['password'])) {
734
                                $user = api_get_user_entity($userInfo['id']);
735
                                $encoded = UserManager::encryptPassword(
736
                                    $row['password'],
737
                                    $user
738
                                );
739
740
                                if ($userInfo['password'] != $encoded &&
741
                                    in_array($row['password'], $avoidUsersWithPassword)
742
                                ) {
743
                                    $this->logger->addInfo(
744
                                        "Students - User password is not updated: ".$row['username']." because the avoid conditions (password)."
745
                                    );
746
                                    $password = null;
747
                                    $resetPassword = 0; // disallow password change
748
                                }
749
                            }*/
750
                        }
751
                    }
752
753
                    // Always disallow password change during update
754
                    $password = null;
755
                    $resetPassword = 0; // disallow password change
756
757
                    // Update user
758
                    $result = UserManager::update_user(
759
                        $userInfo['user_id'],
760
                        $row['firstname'], // <<-- changed
761
                        $row['lastname'], // <<-- changed
762
                        $row['username'], // <<-- changed
763
                        $password, //$password = null,
764
                        $row['auth_source'],
765
                        $email,
766
                        STUDENT,
767
                        $userInfo['official_code'],
768
                        $userInfo['phone'],
769
                        $userInfo['picture_uri'],
770
                        $expirationDateOnUpdate,
771
                        $userInfo['active'],
772
                        null, //$creator_id = null,
773
                        0, //$hr_dept_id = 0,
774
                        null, // $extra = null,
775
                        null, //$language = 'english',
776
                        null, //$encrypt_method = '',
777
                        false, //$send_email = false,
778
                        $resetPassword //$reset_password = 0
779
                    );
780
781
                    if ($result) {
782
                        if ($row['username'] != $userInfo['username']) {
783
                            $this->logger->addInfo("Students - Username was changes from '".$userInfo['username']."' to '".$row['username']."' ");
784
                        }
785
                        foreach ($row as $key => $value) {
786
                            if (substr($key, 0, 6) === 'extra_') {
787
                                //an extra field
788
                                UserManager::update_extra_field_value(
789
                                    $userInfo['user_id'],
790
                                    substr($key, 6),
791
                                    $value
792
                                );
793
                            }
794
                        }
795
796
                        $this->logger->addInfo("Students - User updated: ".$row['username']);
797
                    } else {
798
                        $this->logger->addError("Students - User NOT updated: ".$row['username']." ".$row['firstname']." ".$row['lastname']);
799
                    }
800
                }
801
802
                if (($counter % $batchSize) === 0) {
803
                    $em->flush();
804
                    $em->clear(); // Detaches all objects from Doctrine!
805
                    $this->logger->addInfo("Detaches all objects");
806
                }
807
                $counter++;
808
            }
809
            $em->clear(); // Detaches all objects from Doctrine!
810
        }
811
812
        $timeEnd = microtime(true);
813
        $executionTime = round(($timeEnd - $timeStart) / 60, 2);
814
        $this->logger->addInfo("Execution Time for process students: $executionTime Min");
815
816
        if ($moveFile) {
817
            $this->moveFile($file);
818
        }
819
820
        $this->updateUsersEmails();
821
    }
822
823
    /**
824
     * @param string $file
825
     */
826
    private function importCoursesStatic($file, $moveFile, &$teacherBackup = array(), &$groupBackup = array())
827
    {
828
        $this->importCourses($file, true, $teacherBackup, $groupBackup);
829
    }
830
831
    /**
832
     * @param string $file
833
     * @param bool $moveFile
834
     *
835
     * @return int
836
     */
837
    private function importCalendarStatic($file, $moveFile = true)
838
    {
839
        $this->fixCSVFile($file);
840
841
        $this->updateUsersEmails();
842
        $data = Import::csvToArray($file);
843
844
        if (!empty($data)) {
845
            $this->logger->addInfo(count($data)." records found.");
846
            $eventsToCreate = array();
847
            $errorFound = false;
848
849
            foreach ($data as $row) {
850
                $sessionId = null;
851
                $externalSessionId = null;
852
                if (isset($row['external_sessionID'])) {
853
                    $externalSessionId = $row['external_sessionID'];
854
                    $sessionId = SessionManager::getSessionIdFromOriginalId(
855
                        $externalSessionId,
856
                        $this->extraFieldIdNameList['session']
857
                    );
858
                }
859
860
                $courseCode = null;
861
                if (isset($row['coursecode'])) {
862
                    $courseCode = $row['coursecode'];
863
                }
864
                $courseInfo = api_get_course_info($courseCode);
865
866
                if (empty($courseInfo)) {
867
                    $this->logger->addInfo("Course '$courseCode' does not exists");
868
                }
869
870
                if (empty($sessionId)) {
871
                    $this->logger->addInfo("external_sessionID: ".$externalSessionId." does not exists.");
872
                }
873
                $teacherId = null;
874
875
                if (!empty($sessionId) && !empty($courseInfo)) {
876
                    $courseIncluded = SessionManager::relation_session_course_exist(
877
                        $sessionId,
878
                        $courseInfo['real_id']
879
                    );
880
881
                    if ($courseIncluded == false) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
882
                        $this->logger->addInfo(
883
                            "Course '$courseCode' is not included in session: $sessionId"
884
                        );
885
                        $errorFound = true;
886
                    } else {
887
                        $teachers = CourseManager::get_coach_list_from_course_code(
888
                            $courseInfo['code'],
889
                            $sessionId
890
                        );
891
892
                        // Getting first teacher.
893
                        if (!empty($teachers)) {
894
                            $teacher = current($teachers);
895
                            $teacherId = $teacher['user_id'];
896
                        } else {
897
                            $sessionInfo = api_get_session_info($sessionId);
898
                            $teacherId = $sessionInfo['id_coach'];
899
                        }
900
                    }
901
                } else {
902
                    $errorFound = true;
903
                }
904
905
                if (empty($teacherId)) {
906
                    $errorFound = true;
907
                    $this->logger->addInfo(
908
                        "No teacher found in course code : '$courseCode' and session: '$sessionId'"
909
                    );
910
                }
911
912
                $date = $row['date'];
913
                $startTime = $row['time_start'];
914
                $endTime = $row['time_end'];
915
                $title = $row['title'];
916
                $comment = $row['comment'];
917
                $color = isset($row['color']) ? $row['color'] : '';
918
919
                $startDateYear = substr($date, 0, 4);
920
                $startDateMonth = substr($date, 4, 2);
921
                $startDateDay = substr($date, 6, 8);
922
923
                $startDate = $startDateYear.'-'.$startDateMonth.'-'.$startDateDay.' '.$startTime.":00";
924
                $endDate = $startDateYear.'-'.$startDateMonth.'-'.$startDateDay.' '.$endTime.":00";
925
926
                if (!api_is_valid_date($startDate) || !api_is_valid_date($endDate)) {
927
                    $this->logger->addInfo(
928
                        "Verify your dates:  '$startDate' : '$endDate' "
929
                    );
930
                    $errorFound = true;
931
                }
932
933
                if ($errorFound == false) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
934
                    $eventsToCreate[] = array(
935
                        'start' => $startDate,
936
                        'end' => $endDate,
937
                        'title' => $title,
938
                        'sender_id' => $teacherId,
939
                        'course_id' => $courseInfo['real_id'],
940
                        'session_id' => $sessionId,
941
                        'comment' => $comment,
942
                        'color' => $color,
943
                        $this->extraFieldIdNameList['calendar_event'] => $row['external_calendar_itemID'],
944
                    );
945
                }
946
                $errorFound = false;
947
            }
948
949
            if (empty($eventsToCreate)) {
950
                $this->logger->addInfo(
951
                    "No events to add"
952
                );
953
954
                return 0;
955
            }
956
957
            $extraFieldValue = new ExtraFieldValue('calendar_event');
958
            $extraFieldName = $this->extraFieldIdNameList['calendar_event'];
959
            $externalEventId = null;
960
961
            $extraField = new ExtraField('calendar_event');
962
            $extraFieldInfo = $extraField->get_handler_field_info_by_field_variable(
963
                $extraFieldName
964
            );
965
966
            if (empty($extraFieldInfo)) {
967
                $this->logger->addInfo(
968
                    "No calendar event extra field created: $extraFieldName"
969
                );
970
971
                return 0;
972
            }
973
974
            $this->logger->addInfo('Ready to insert # '.count($eventsToCreate).' events');
975
            $batchSize = $this->batchSize;
976
            $counter = 1;
977
            $em = Database::getManager();
978
            $eventStartDateList = [];
979
            $eventEndDateList = [];
980
            $report = [
981
                'mail_sent' => 0,
982
                'mail_not_sent_announcement_exists' => 0,
983
                'mail_not_sent_because_date' => 0
984
            ];
985
986
            $eventsToCreateFinal = [];
987
            foreach ($eventsToCreate as $event) {
988
                $update = false;
989
                $item = null;
990
                if (!isset($event[$extraFieldName])) {
991
                    $this->logger->addInfo(
992
                        "No external_calendar_itemID found. Skipping ..."
993
                    );
994
                    continue;
995
                } else {
996
                    $externalEventId = $event[$extraFieldName];
997
                    if (empty($externalEventId)) {
998
                        $this->logger->addInfo(
999
                            "external_calendar_itemID was set but empty. Skipping ..."
1000
                        );
1001
                        continue;
1002
                    }
1003
1004
                    $item = $extraFieldValue->get_item_id_from_field_variable_and_field_value(
1005
                        $extraFieldName,
1006
                        $externalEventId,
1007
                        false,
1008
                        false,
1009
                        false
1010
                    );
1011
1012
                    if (!empty($item)) {
1013
                        $update = true;
1014
                    }
1015
                }
1016
1017
                $courseInfo = api_get_course_info_by_id($event['course_id']);
1018
                $event['course_info'] = $courseInfo;
1019
                $event['update'] = $update;
1020
                $event['item'] = $item;
1021
1022
                $calendarEvent = null;
1023
                /* Check if event changed of course code */
1024
                if (!empty($item) && isset($item['item_id']) && !empty($item['item_id'])) {
1025
                    /** @var CCalendarEvent $calendarEvent */
1026
                    $calendarEvent = $em->getRepository('ChamiloCourseBundle:CCalendarEvent')->find($item['item_id']);
1027
                }
1028
1029
                if ($calendarEvent) {
1030
                    $this->logger->addInfo('Calendar event found '.$item['item_id']);
1031
                    if ($calendarEvent->getCId() != $courseInfo['real_id']) {
1032
                        $this->logger->addInfo('Move from course #'.$calendarEvent->getCId().' to #'.$courseInfo['real_id']);
1033
                        // Seems that the course id changed in the csv
1034
                        $calendarEvent->setCId($courseInfo['real_id']);
1035
                        $em->persist($calendarEvent);
1036
                        $em->flush();
1037
1038
                        $criteria = [
1039
                            'tool' => 'calendar_event',
1040
                            'ref' => $item['item_id']
1041
                        ];
1042
                        /** @var CItemProperty $itemProperty */
1043
                        $itemProperty = $em->getRepository('ChamiloCourseBundle:CItemProperty')->findOneBy($criteria);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $itemProperty is correct as $em->getRepository('Cham...)->findOneBy($criteria) targeting Doctrine\ORM\EntityRepository::findOneBy() seems to always return null.

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

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

}

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

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

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

Loading history...
1044
                        $courseEntity = $em->getRepository('ChamiloCoreBundle:Course')->find($courseInfo['real_id']);
1045
                        if ($itemProperty && $courseEntity) {
1046
                            $itemProperty->setCourse($courseEntity);
1047
                            $em->persist($itemProperty);
1048
                            $em->flush();
1049
                        }
1050
                    }
1051
                } else {
1052
                    $this->logger->addInfo('Calendar event not found '.$item['item_id']);
1053
                }
1054
1055
                $event['external_event_id'] = $externalEventId;
1056
                if (isset($eventStartDateList[$courseInfo['real_id']]) &&
1057
                    isset($eventStartDateList[$courseInfo['real_id']][$event['session_id']])
1058
                ) {
1059
                    $currentItemDate = api_strtotime($event['start']);
1060
                    $firstDate = $eventStartDateList[$courseInfo['real_id']][$event['session_id']];
1061
                    if ($currentItemDate < api_strtotime($firstDate)) {
1062
                        $eventStartDateList[$courseInfo['real_id']][$event['session_id']] = $event['start'];
1063
                        $eventEndDateList[$courseInfo['real_id']][$event['session_id']] = $event['end'];
1064
                    }
1065
                } else {
1066
                    // First time
1067
                    $eventStartDateList[$courseInfo['real_id']][$event['session_id']] = $event['start'];
1068
                    $eventEndDateList[$courseInfo['real_id']][$event['session_id']] = $event['end'];
1069
                }
1070
                $eventsToCreateFinal[] = $event;
1071
            }
1072
1073
            $eventAlreadySent = [];
1074
            foreach ($eventsToCreateFinal as $event) {
1075
                $courseInfo = $event['course_info'];
1076
                $item = $event['item'];
1077
                $update = $event['update'];
1078
                $externalEventId = $event['external_event_id'];
1079
                $info = 'Course: '.$courseInfo['real_id'].' ('.$courseInfo['code'].') - Session: '.$event['session_id'];
1080
1081
                $agenda = new Agenda(
1082
                    'course',
1083
                    $event['sender_id'],
1084
                    $courseInfo['real_id'],
1085
                    $event['session_id']
1086
                );
1087
                $agenda->set_course($courseInfo);
1088
                $agenda->setSessionId($event['session_id']);
1089
                $agenda->setSenderId($event['sender_id']);
1090
                $agenda->setIsAllowedToEdit(true);
1091
                $eventComment = $event['comment'];
1092
                $color = $event['color'];
1093
1094
                // To use the event comment you need
1095
                // ALTER TABLE c_calendar_event ADD COLUMN comment TEXT;
1096
                // add in configuration.php allow_agenda_event_comment = true
1097
                if (empty($courseInfo)) {
1098
                    $this->logger->addInfo(
1099
                        "No course found for event #$externalEventId Course #".$event['course_id']." Skipping ..."
1100
                    );
1101
                    continue;
1102
                }
1103
1104
                if (empty($event['sender_id'])) {
1105
                    $this->logger->addInfo(
1106
                        "No sender found for event #$externalEventId Send #".$event['sender_id']." Skipping ..."
1107
                    );
1108
                    continue;
1109
                }
1110
1111
                // Taking first element of course-session event
1112
                $alreadyAdded = false;
1113
                $firstDate = $eventStartDateList[$courseInfo['real_id']][$event['session_id']];
1114
                $firstEndDate = $eventEndDateList[$courseInfo['real_id']][$event['session_id']];
1115
1116
                if (isset($eventAlreadySent[$courseInfo['real_id']]) &&
1117
                    isset($eventAlreadySent[$courseInfo['real_id']][$event['session_id']])
1118
                ) {
1119
                    $alreadyAdded = true;
1120
                } else {
1121
                    $eventAlreadySent[$courseInfo['real_id']][$event['session_id']] = true;
1122
                }
1123
1124
                // Working days (Mon-Fri)see BT#12156#note-16
1125
                $days = 5;
1126
                $startDatePlusDays = api_strtotime("$days weekdays");
1127
1128
                $this->logger->addInfo(
1129
                    "startDatePlusDays: ".api_get_utc_datetime($startDatePlusDays).' - First date: '.$firstDate
1130
                );
1131
1132
                // Send
1133
                if ($startDatePlusDays > api_strtotime($firstDate)) {
1134
                    $sendMail = true;
1135
                } else {
1136
                    $sendMail = false;
1137
                }
1138
1139
                // Send announcement to users
1140
                if ($sendMail && $alreadyAdded == false) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
1141
                    $start = $firstDate;
1142
                    $end = $firstEndDate;
1143
1144
                    if (!empty($end) &&
1145
                        api_format_date($start, DATE_FORMAT_LONG) == api_format_date($end, DATE_FORMAT_LONG)
1146
                    ) {
1147
                        $date = api_format_date($start, DATE_FORMAT_LONG).' ('.
1148
                            api_format_date($start, TIME_NO_SEC_FORMAT).' '.
1149
                            api_format_date($end, TIME_NO_SEC_FORMAT).')';
1150
                    } else {
1151
                        $date = api_format_date($start, DATE_TIME_FORMAT_LONG_24H).' - '.
1152
                                api_format_date($end, DATE_TIME_FORMAT_LONG_24H);
1153
                    }
1154
1155
                    $sessionName = '';
1156
                    if (!empty($event['session_id'])) {
1157
                        $sessionName = ' ('.api_get_session_name($event['session_id']).')';
1158
                    }
1159
1160
                    $courseTitle = $courseInfo['title'].$sessionName;
1161
1162
                    $emailBody = get_lang('Dear').' ((user_firstname)) <br />'.
1163
                        sprintf(
1164
                            get_lang('YouHaveBeenSubscribedToCourseXTheStartDateXAndCommentX'),
1165
                            $courseTitle,
1166
                            $date,
1167
                            $event['comment']
1168
                        )
1169
                    ;
1170
1171
                    $subject = sprintf(
1172
                        get_lang('AgendaAvailableInCourseX'),
1173
                        $courseInfo['title']
1174
                    );
1175
1176
                    $coaches = SessionManager::getCoachesByCourseSession(
1177
                        $event['session_id'],
1178
                        $courseInfo['real_id']
1179
                    );
1180
1181
                    // Search if an announcement exists:
1182
                    $announcementsWithTitleList = AnnouncementManager::getAnnouncementsByTitle(
1183
                        $subject,
1184
                        $courseInfo['real_id'],
1185
                        $event['session_id'],
1186
                        1
1187
                    );
1188
1189
                    if (count($announcementsWithTitleList) === 0) {
1190
                        $this->logger->addInfo(
1191
                            "Mail to be sent because start date: ".$event['start']." and no announcement found."
1192
                        );
1193
                        $announcementId = AnnouncementManager::add_announcement(
1194
                            $courseInfo,
1195
                            $event['session_id'],
1196
                            $subject,
1197
                            $emailBody,
1198
                            [
1199
                                'everyone',
1200
                                'users' => $coaches
1201
                            ],
1202
                            [],
1203
                            null,
1204
                            null,
1205
                            false,
1206
                            $this->defaultAdminId
1207
                        );
1208
1209
                        if ($announcementId) {
1210
                            $this->logger->addInfo(
1211
                                "Announcement added: ".(int) ($announcementId)." in $info"
1212
                            );
1213
                            $this->logger->addInfo(
1214
                                "<<--SENDING MAIL-->>"
1215
                            );
1216
1217
                            $report['mail_sent']++;
1218
                            AnnouncementManager::sendEmail(
1219
                                $courseInfo,
1220
                                $event['session_id'],
1221
                                $announcementId,
1222
                                false
1223
                            );
1224
                        }
1225
                    } else {
1226
                        $report['mail_not_sent_announcement_exists']++;
1227
                        $this->logger->addInfo(
1228
                            "Mail NOT sent. An announcement seems to be already saved in '$info'"
1229
                        );
1230
                    }
1231
                } else {
1232
                    if ($sendMail == false) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
1233
                        $report['mail_not_sent_because_date']++;
1234
                    }
1235
                }
1236
1237
                $content = '';
1238
                if ($update && isset($item['item_id'])) {
1239
                    $eventInfo = $agenda->get_event($item['item_id']);
1240
                    if (empty($eventInfo)) {
1241
                        // Means that agenda external id exists but the event doesn't exist
1242
                        $this->logger->addInfo("external event id exists: $externalEventId");
1243
                        $this->logger->addInfo("but Chamilo event doesn't exists: ".$item['item_id']);
1244
1245
                        $eventId = $agenda->addEvent(
1246
                            $event['start'],
1247
                            $event['end'],
1248
                            false,
1249
                            $event['title'],
1250
                            $content,
1251
                            array('everyone'), // $usersToSend
1252
                            false, //$addAsAnnouncement = false
1253
                            null, //  $parentEventId
1254
                            array(), //$attachmentArray = array(),
1255
                            [], //$attachmentCommentList
1256
                            $eventComment,
1257
                            $color
1258
                        );
1259
1260
                        if (!empty($eventId)) {
1261
                            $this->logger->addInfo("Chamilo event created: ".$eventId);
1262
                            $extraFieldValueItem = $extraFieldValue->get_values_by_handler_and_field_id(
1263
                                $item['item_id'],
1264
                                $extraFieldInfo['id']
1265
                            );
1266
1267
                            if (!empty($extraFieldValueItem) && isset($extraFieldValueItem['id'])) {
1268
                                $params = [
1269
                                    'id' => $extraFieldValueItem['id'],
1270
                                    'item_id' => $eventId
1271
                                ];
1272
                                $extraFieldValue->update($params);
1273
                                $this->logger->addInfo(
1274
                                    'Updating calendar extra field #'.$extraFieldValueItem['id'].' new item_id: '.$eventId.' old item_id: '.$item['item_id']
1275
                                );
1276
                            }
1277
                        } else {
1278
                            $this->logger->addInfo("Error while creating event external id: $externalEventId");
1279
                        }
1280
                    } else {
1281
                        // The event already exists, just update
1282
                        $eventResult = $agenda->editEvent(
1283
                            $item['item_id'],
1284
                            $event['start'],
1285
                            $event['end'],
1286
                            false,
1287
                            $event['title'],
1288
                            $content,
1289
                            array('everyone'), // $usersToSend
1290
                            array(), //$attachmentArray = array(),
1291
                            [], //$attachmentCommentList
1292
                            $eventComment,
1293
                            $color,
1294
                            false,
1295
                            false,
1296
                            $this->defaultAdminId
1297
                        );
1298
1299
                        if ($eventResult !== false) {
1300
                            $this->logger->addInfo(
1301
                                "Event updated #".$item['item_id']." External cal Id: (".$externalEventId.") $info"
1302
                            );
1303
                        } else {
1304
                            $this->logger->addInfo(
1305
                                "Error while updating event with external id: $externalEventId"
1306
                            );
1307
                        }
1308
                    }
1309
                } else {
1310
                    // New event. Create it.
1311
                    $eventId = $agenda->addEvent(
1312
                        $event['start'],
1313
                        $event['end'],
1314
                        false,
1315
                        $event['title'],
1316
                        $content,
1317
                        array('everyone'), // $usersToSend
1318
                        false, //$addAsAnnouncement = false
1319
                        null, //  $parentEventId
1320
                        array(), //$attachmentArray = array(),
1321
                        [], //$attachmentCommentList
1322
                        $eventComment,
1323
                        $color
1324
                    );
1325
1326
                    if (!empty($eventId)) {
1327
                        $extraFieldValue->save(
1328
                            array(
1329
                                'value' => $externalEventId,
1330
                                'field_id' => $extraFieldInfo['id'],
1331
                                'item_id' => $eventId
1332
                            )
1333
                        );
1334
                        $this->logger->addInfo(
1335
                            "Event added: #$eventId External cal id: (".$externalEventId.") $info"
1336
                        );
1337
                    } else {
1338
                        $this->logger->addInfo(
1339
                            "Error while creating event external id: $externalEventId"
1340
                        );
1341
                    }
1342
                }
1343
1344
                if (($counter % $batchSize) === 0) {
1345
                    $em->flush();
1346
                    $em->clear(); // Detaches all objects from Doctrine!
1347
                }
1348
                $counter++;
1349
            }
1350
1351
            $em->clear(); // Detaches all objects from Doctrine!
1352
            $this->logger->addInfo('------Summary------');
1353
            foreach ($report as $title => $count) {
1354
                $this->logger->addInfo("$title: $count");
1355
            }
1356
            $this->logger->addInfo('------End Summary------');
1357
        }
1358
1359
        if ($moveFile) {
1360
            $this->moveFile($file);
1361
        }
1362
    }
1363
1364
    /**
1365
     * @param string $file
1366
     * @param bool $moveFile
1367
     * @param array $teacherBackup
1368
     * @param array $groupBackup
1369
     */
1370
    private function importCourses(
1371
        $file,
1372
        $moveFile = true,
1373
        &$teacherBackup = array(),
1374
        &$groupBackup = array()
1375
    ) {
1376
        $this->fixCSVFile($file);
1377
        $data = Import::csvToArray($file);
1378
1379
        if (!empty($data)) {
1380
            $this->logger->addInfo(count($data)." records found.");
1381
1382
            foreach ($data as $row) {
1383
                $row = $this->cleanCourseRow($row);
1384
1385
                $courseId = CourseManager::get_course_id_from_original_id(
1386
                    $row['extra_'.$this->extraFieldIdNameList['course']],
1387
                    $this->extraFieldIdNameList['course']
1388
                );
1389
1390
                $courseInfo = api_get_course_info_by_id($courseId);
1391
1392
                if (empty($courseInfo)) {
1393
                    // Create
1394
                    $params = array();
1395
                    $params['title'] = $row['title'];
1396
                    $params['exemplary_content'] = false;
1397
                    $params['wanted_code'] = $row['course_code'];
1398
                    $params['course_category'] = $row['course_category'];
1399
                    $params['course_language'] = $row['language'];
1400
                    $params['teachers'] = $row['teachers'];
1401
                    $params['visibility'] = $row['visibility'];
1402
1403
                    $courseInfo = CourseManager::create_course(
1404
                        $params,
1405
                        $this->defaultAdminId
1406
                    );
1407
1408
                    if (!empty($courseInfo)) {
1409
                        CourseManager::update_course_extra_field_value(
1410
                            $courseInfo['code'],
1411
                            'external_course_id',
1412
                            $row['extra_'.$this->extraFieldIdNameList['course']]
1413
                        );
1414
1415
                        $this->logger->addInfo("Courses - Course created ".$courseInfo['code']);
1416
                    } else {
1417
                        $this->logger->addError("Courses - Can't create course:".$row['title']);
1418
                    }
1419
                } else {
1420
                    // Update
1421
                    $params = array(
1422
                        'title' => $row['title'],
1423
                        'category_code' => $row['course_category'],
1424
                        'visibility' => $row['visibility']
1425
                    );
1426
1427
                    $result = CourseManager::update_attributes(
1428
                        $courseInfo['real_id'],
1429
                        $params
1430
                    );
1431
1432
                    $addTeacherToSession = isset($courseInfo['add_teachers_to_sessions_courses']) && !empty($courseInfo['add_teachers_to_sessions_courses']) ? true : false;
1433
1434
                    $teachers = $row['teachers'];
1435
                    if (!is_array($teachers)) {
1436
                        $teachers = array($teachers);
1437
                    }
1438
1439
                    if ($addTeacherToSession) {
1440
                        $this->logger->addInfo("Add teacher to all course sessions");
1441
                        CourseManager::updateTeachers(
1442
                            $courseInfo,
1443
                            $row['teachers'],
1444
                            false,
1445
                            true,
1446
                            false,
1447
                            $teacherBackup,
1448
                            $this->logger
1449
                        );
1450
                    } else {
1451
                        CourseManager::updateTeachers(
1452
                            $courseInfo,
1453
                            $row['teachers'],
1454
                            true,
1455
                            false,
1456
                            false,
1457
                            $teacherBackup,
1458
                            $this->logger
1459
                        );
1460
                    }
1461
1462
                    foreach ($teachers as $teacherId) {
1463
                        if (isset($groupBackup['tutor'][$teacherId]) &&
1464
                            isset($groupBackup['tutor'][$teacherId][$courseInfo['code']])
1465
                        ) {
1466
                            foreach ($groupBackup['tutor'][$teacherId][$courseInfo['code']] as $data) {
1467
                                $groupInfo = GroupManager::get_group_properties($data['group_id']);
1468
                                GroupManager::subscribe_tutors(
1469
                                    array($teacherId),
1470
                                    $groupInfo,
1471
                                    $data['c_id']
1472
                                );
1473
                            }
1474
                        }
1475
1476
                        if (isset($groupBackup['user'][$teacherId]) &&
1477
                            isset($groupBackup['user'][$teacherId][$courseInfo['code']]) &&
1478
                            !empty($groupBackup['user'][$teacherId][$courseInfo['code']])
1479
                        ) {
1480
                            foreach ($groupBackup['user'][$teacherId][$courseInfo['code']] as $data) {
1481
                                $groupInfo = GroupManager::get_group_properties($data['group_id']);
1482
                                GroupManager::subscribe_users(
1483
                                    array($teacherId),
1484
                                    $groupInfo,
1485
                                    $data['c_id']
1486
                                );
1487
                            }
1488
                        }
1489
                    }
1490
1491
                    if ($result) {
1492
                        $this->logger->addInfo("Courses - Course updated ".$courseInfo['code']);
1493
                    } else {
1494
                        $this->logger->addError("Courses - Course NOT updated ".$courseInfo['code']);
1495
                    }
1496
                }
1497
            }
1498
        }
1499
1500
        if ($moveFile) {
1501
            $this->moveFile($file);
1502
        }
1503
    }
1504
1505
    /**
1506
     * Parse filename: encora_subsessionsextid-static_31082016.csv
1507
     * @param string $file
1508
     */
1509
    private function importSubscribeUserToCourseSessionExtStatic($file, $moveFile = true)
1510
    {
1511
        $data = Import::csv_reader($file);
1512
        if (!empty($data)) {
1513
            $this->logger->addInfo(count($data)." records found.");
1514
            $userIdList = [];
1515
            foreach ($data as $row) {
1516
                $chamiloUserName = $row['UserName'];
1517
                $chamiloCourseCode = $row['CourseCode'];
1518
                $externalSessionId = $row['ExtSessionID'];
1519
                $status = $row['Status'];
1520
1521
                $chamiloSessionId = null;
1522
                if (!empty($externalSessionId)) {
1523
                    $chamiloSessionId = SessionManager::getSessionIdFromOriginalId(
1524
                        $externalSessionId,
1525
                        $this->extraFieldIdNameList['session']
1526
                    );
1527
                }
1528
1529
                $sessionInfo = api_get_session_info($chamiloSessionId);
1530
1531
                if (empty($sessionInfo)) {
1532
                    $this->logger->addError('Session does not exists: '.$chamiloSessionId);
1533
                    continue;
1534
                }
1535
1536
                $courseInfo = api_get_course_info($chamiloCourseCode);
1537
                if (empty($courseInfo)) {
1538
                    $this->logger->addError('Course does not exists: '.$courseInfo);
1539
                    continue;
1540
                }
1541
1542
                $userId = UserManager::get_user_id_from_username($chamiloUserName);
1543
1544
                if (empty($userId)) {
1545
                    $this->logger->addError('User does not exists: '.$chamiloUserName);
1546
                    continue;
1547
                }
1548
1549
                switch ($status) {
1550
                    case 'student':
1551
                        SessionManager::subscribe_users_to_session_course(
1552
                            array($userId),
1553
                            $chamiloSessionId,
1554
                            $courseInfo['code']
1555
                        );
1556
                        break;
1557
                    case 'teacher':
1558
                        SessionManager::set_coach_to_course_session(
1559
                            $userId,
1560
                            $chamiloSessionId,
1561
                            $courseInfo['code']
1562
                        );
1563
                        break;
1564
                    case 'drh':
1565
                        $removeAllSessionsFromUser = true;
1566
                        if (in_array($userId, $userIdList)) {
1567
                            $removeAllSessionsFromUser = false;
1568
                        } else {
1569
                            $userIdList[] = $userId;
1570
                        }
1571
1572
                        $userInfo = api_get_user_info($userId);
1573
                        SessionManager::subscribeSessionsToDrh(
1574
                            $userInfo,
1575
                            [$chamiloSessionId],
1576
                            false,
1577
                            $removeAllSessionsFromUser
1578
                        );
1579
                        break;
1580
                }
1581
1582
                $this->logger->addError(
1583
                    "User '$chamiloUserName' was added as '$status' to Session: #$chamiloSessionId - Course: ".$courseInfo['code']
1584
                );
1585
1586
            }
1587
        }
1588
1589
        if ($moveFile) {
1590
            $this->moveFile($file);
1591
        }
1592
    }
1593
1594
    /**
1595
     * @param $file
1596
     * @param bool $moveFile
1597
     */
1598
    private function importUnsubSessionsExtIdStatic($file, $moveFile = true)
1599
    {
1600
        $data = Import::csv_reader($file);
1601
1602
        if (!empty($data)) {
1603
            $this->logger->addInfo(count($data)." records found.");
1604
            foreach ($data as $row) {
1605
                $chamiloUserName = $row['UserName'];
1606
                $chamiloCourseCode = $row['CourseCode'];
1607
                $externalSessionId = $row['ExtSessionID'];
1608
                $dateStop = $row['DateStop'];
1609
1610
                $chamiloSessionId = null;
1611
                if (!empty($externalSessionId)) {
1612
                    $chamiloSessionId = SessionManager::getSessionIdFromOriginalId(
1613
                        $externalSessionId,
1614
                        $this->extraFieldIdNameList['session']
1615
                    );
1616
                }
1617
1618
                $sessionInfo = api_get_session_info($chamiloSessionId);
1619
1620
                if (empty($sessionInfo)) {
1621
                    $this->logger->addError('Session does not exists: '.$chamiloSessionId);
1622
                    continue;
1623
                }
1624
1625
                $courseInfo = api_get_course_info($chamiloCourseCode);
1626
                if (empty($courseInfo)) {
1627
                    $this->logger->addError('Course does not exists: '.$courseInfo);
1628
                    continue;
1629
                }
1630
1631
                $userId = UserManager::get_user_id_from_username($chamiloUserName);
1632
1633
                if (empty($userId)) {
1634
                    $this->logger->addError('User does not exists: '.$chamiloUserName);
1635
                    continue;
1636
                }
1637
1638
                SessionManager::removeUsersFromCourseSession(
1639
                    array($userId),
1640
                    $chamiloSessionId,
1641
                    $courseInfo
1642
                );
1643
1644
                $this->logger->addError(
1645
                    "User '$chamiloUserName' was remove from Session: #$chamiloSessionId - Course: ".$courseInfo['code']
1646
                );
1647
1648
            }
1649
        }
1650
1651
        if ($moveFile) {
1652
            $this->moveFile($file);
1653
        }
1654
    }
1655
1656
    /**
1657
     *
1658
     * @param string $file
1659
     */
1660
    private function importSessionsExtIdStatic($file, $moveFile = true)
1661
    {
1662
        $data = Import::csv_reader($file);
1663
1664
        if (!empty($data)) {
1665
            $this->logger->addInfo(count($data)." records found.");
1666
            foreach ($data as $row) {
1667
                $chamiloUserName = $row['UserName'];
1668
                $chamiloCourseCode = $row['CourseCode'];
1669
                $externalSessionId = $row['ExtSessionID'];
1670
                $type = $row['Type'];
1671
1672
                $chamiloSessionId = null;
1673
                if (!empty($externalSessionId)) {
1674
                    $chamiloSessionId = SessionManager::getSessionIdFromOriginalId(
1675
                        $externalSessionId,
1676
                        $this->extraFieldIdNameList['session']
1677
                    );
1678
                }
1679
1680
                $sessionInfo = api_get_session_info($chamiloSessionId);
1681
1682
                if (empty($sessionInfo)) {
1683
                    $this->logger->addError('Session does not exists: '.$chamiloSessionId);
1684
                    continue;
1685
                }
1686
1687
                $courseInfo = api_get_course_info($chamiloCourseCode);
1688
                if (empty($courseInfo)) {
1689
                    $this->logger->addError('Course does not exists: '.$courseInfo);
1690
                    continue;
1691
                }
1692
1693
                $userId = UserManager::get_user_id_from_username($chamiloUserName);
1694
1695
                if (empty($userId)) {
1696
                    $this->logger->addError('User does not exists: '.$chamiloUserName);
1697
                    continue;
1698
                }
1699
                switch ($type) {
1700
                    case 'student':
1701
                        SessionManager::subscribe_users_to_session_course(
1702
                            array($userId),
1703
                            $chamiloSessionId,
1704
                            $courseInfo['code'],
1705
                            null,
1706
                            false
1707
                        );
1708
                        break;
1709
                    case 'teacher':
1710
                        SessionManager::set_coach_to_course_session(
1711
                            $userId,
1712
                            $chamiloSessionId,
1713
                            $courseInfo['code']
1714
                        );
1715
                        break;
1716
                }
1717
1718
                $this->logger->addError(
1719
                    "User '$chamiloUserName' with status $type was added to session: #$chamiloSessionId - Course: ".$courseInfo['code']
1720
                );
1721
            }
1722
        }
1723
1724
        if ($moveFile) {
1725
            $this->moveFile($file);
1726
        }
1727
    }
1728
1729
    /**
1730
     * Updates the session synchronize with the csv file.
1731
     * @param bool $moveFile
1732
     * @param string $file
1733
     */
1734
    private function importSessionsStatic($file, $moveFile = true)
1735
    {
1736
        $content = file($file);
1737
        $sessions = array();
1738
        $tag_names = array();
1739
1740
        foreach ($content as $key => $enreg) {
1741
            $enreg = explode(';', trim($enreg));
1742
            if ($key) {
1743
                foreach ($tag_names as $tag_key => $tag_name) {
1744
                    if (isset($enreg[$tag_key])) {
1745
                        $sessions[$key - 1][$tag_name] = $enreg[$tag_key];
1746
                    }
1747
                }
1748
            } else {
1749
                foreach ($enreg as $tag_name) {
1750
                    $tag_names[] = api_preg_replace(
1751
                        '/[^a-zA-Z0-9_\-]/',
1752
                        '',
1753
                        $tag_name
1754
                    );
1755
                }
1756
                if (!in_array('SessionName', $tag_names) ||
1757
                    !in_array('DateStart', $tag_names) || !in_array('DateEnd', $tag_names)
1758
                ) {
1759
                    $error_message = get_lang('NoNeededData');
1760
                    break;
1761
                }
1762
            }
1763
        }
1764
1765
1766
        if (!empty($sessions)) {
1767
            // Looping the sessions.
1768
            foreach ($sessions as $session) {
1769
                if (!empty($session['SessionID'])) {
1770
                    $sessionId = SessionManager::getSessionIdFromOriginalId(
1771
                        $session['SessionID'],
1772
                        $this->extraFieldIdNameList['session']
1773
                    );
1774
1775
                    $coachUserName = isset($session['Coach']) ? $session['Coach'] : null;
1776
                    $categoryId = isset($session['category_id']) ? $session['category_id'] : null;
1777
1778
                    // 2014-06-30
1779
                    $dateStart = explode('/', $session['DateStart']);
1780
                    $dateEnd = explode('/', $session['DateEnd']);
1781
                    $visibility = $this->defaultSessionVisibility;
1782
1783
                    $coachId = null;
1784
                    if (!empty($coachUserName)) {
1785
                        $coachInfo = api_get_user_info_from_username($coachUserName);
1786
                        $coachId = $coachInfo['user_id'];
1787
                    }
1788
1789
                    $dateStart = $dateStart[0].'-'.$dateStart[1].'-'.$dateStart[2].' 00:00:00';
1790
                    $dateEnd = $dateEnd[0].'-'.$dateEnd[1].'-'.$dateEnd[2].' 23:59:59';
1791
1792
                    $date = new \DateTime($dateStart);
1793
                    $interval = new DateInterval('P'.$this->daysCoachAccessBeforeBeginning.'D');
1794
                    $date->sub($interval);
1795
                    $coachBefore = $date->format('Y-m-d h:i');
1796
1797
                    $date = new \DateTime($dateEnd);
1798
                    $interval = new DateInterval('P'.$this->daysCoachAccessAfterBeginning.'D');
1799
                    $date->add($interval);
1800
                    $coachAfter = $date->format('Y-m-d h:i');
1801
1802
                    /*$dateStart = api_get_utc_datetime($dateStart);
1803
                    $dateEnd = api_get_utc_datetime($dateEnd);
1804
                    $coachBefore = api_get_utc_datetime($coachBefore);
1805
                    $coachAfter = api_get_utc_datetime($coachAfter);*/
1806
1807
                    if (empty($sessionId)) {
1808
                        $result = SessionManager::create_session(
1809
                            $session['SessionName'],
1810
                            $dateStart,
1811
                            $dateEnd,
1812
                            $dateStart,
1813
                            $dateEnd,
1814
                            $coachBefore,
1815
                            $coachAfter,
1816
                            $coachId,
1817
                            $categoryId,
1818
                            $visibility
1819
                        );
1820
1821
                        if (is_numeric($result)) {
1822
                            $sessionId = $result;
1823
                            $this->logger->addInfo("Session #$sessionId created: ".$session['SessionName']);
1824
                            SessionManager::update_session_extra_field_value(
1825
                                $sessionId,
1826
                                $this->extraFieldIdNameList['session'],
1827
                                $session['SessionID']
1828
                            );
1829
                        } else {
1830
                            $this->logger->addInfo("Failed creating session: ".$session['SessionName']);
1831
                        }
1832
                    } else {
1833
                        $sessionInfo = api_get_session_info($sessionId);
1834
                        $accessBefore = null;
1835
                        $accessAfter = null;
1836
1837
                        if (empty($sessionInfo['nb_days_access_before_beginning']) ||
1838
                            (!empty($sessionInfo['nb_days_access_before_beginning']) &&
1839
                                $sessionInfo['nb_days_access_before_beginning'] < $this->daysCoachAccessBeforeBeginning)
1840
                        ) {
1841
                            $accessBefore = $coachBefore;
1842
                        }
1843
1844
                        $accessAfter = null;
1845
                        if (empty($sessionInfo['nb_days_access_after_end']) ||
1846
                            (!empty($sessionInfo['nb_days_access_after_end']) &&
1847
                                $sessionInfo['nb_days_access_after_end'] < $this->daysCoachAccessAfterBeginning)
1848
                        ) {
1849
                            $accessAfter = $coachAfter;
1850
                        }
1851
1852
                        $showDescription = isset($sessionInfo['show_description']) ? $sessionInfo['show_description'] : 1;
1853
1854
                        $result = SessionManager::edit_session(
1855
                            $sessionId,
1856
                            $session['SessionName'],
1857
                            $dateStart,
1858
                            $dateEnd,
1859
                            $dateStart,
1860
                            $dateEnd,
1861
                            $accessBefore,
1862
                            $accessAfter,
1863
                            $coachId,
1864
                            $categoryId,
1865
                            $visibility,
1866
                            null, //$description = null,
1867
                            $showDescription
1868
                        );
1869
1870
                        if (is_numeric($result)) {
1871
                            $this->logger->addInfo("Session #$sessionId updated: ".$session['SessionName']);
1872
                            $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
1873
                            $params = array(
1874
                                'description' => $session['SessionDescription']
1875
                            );
1876
                            Database::update(
1877
                                $tbl_session,
1878
                                $params,
1879
                                array('id = ?' => $sessionId)
1880
                            );
1881
                        }
1882
                    }
1883
1884
                    if (!empty($sessionId)) {
1885
                        // Courses
1886
                        $courses = explode('|', $session['Courses']);
1887
                        $courseList = [];
1888
                        $courseListWithCoach = [];
1889
                        foreach ($courses as $course) {
1890
                            $courseArray = bracketsToArray($course);
1891
                            $courseCode = $courseArray[0];
1892
                            if (CourseManager::course_exists($courseCode)) {
1893
                                $courseInfo = api_get_course_info($courseCode);
1894
                                $courseList[] = $courseInfo['real_id'];
1895
                                // Extracting course coaches
1896
                                $courseCoaches = isset($courseArray[1]) ? $courseArray[1] : null;
1897
                                $courseCoaches = explode(',', $courseCoaches);
1898
1899
                                // Extracting students
1900
                                $courseUsers = isset($courseArray[2]) ? $courseArray[2] : null;
1901
                                $courseUsers = explode(',', $courseUsers);
1902
1903
                                $courseListWithCoach[] = [
1904
                                    'course_info' => $courseInfo,
1905
                                    'coaches' => $courseCoaches,
1906
                                    'course_users' => $courseUsers
1907
                                ];
1908
                            }
1909
                        }
1910
1911
                        SessionManager::add_courses_to_session(
1912
                            $sessionId,
0 ignored issues
show
Bug introduced by
It seems like $sessionId can also be of type string; however, parameter $sessionId of SessionManager::add_courses_to_session() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

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

1912
                            /** @scrutinizer ignore-type */ $sessionId,
Loading history...
1913
                            $courseList,
1914
                            true
1915
                        );
1916
1917
                        $this->logger->addInfo("Session #$sessionId: Courses added: '".implode(', ', $courseList)."'");
1918
1919
                        if (empty($courseListWithCoach)) {
1920
                            $this->logger->addInfo("No users/coaches to update");
1921
                            continue;
1922
                        }
1923
1924
                        foreach ($courseListWithCoach as $courseData) {
1925
                            $courseInfo = $courseData['course_info'];
1926
                            $courseCode = $courseInfo['code'];
1927
                            $courseId = $courseInfo['real_id'];
1928
                            $courseCoaches = $courseData['coaches'];
1929
                            $courseUsers = $courseData['course_users'];
1930
1931
                            // Coaches
1932
                            if (!empty($courseCoaches)) {
1933
                                $coachList = array();
1934
                                foreach ($courseCoaches as $courseCoach) {
1935
                                    $courseCoachId = UserManager::get_user_id_from_username(
1936
                                        $courseCoach
1937
                                    );
1938
                                    if ($courseCoachId !== false) {
1939
                                        // Just insert new coaches
1940
                                        $coachList[] = $courseCoachId;
1941
                                    }
1942
                                }
1943
1944
                                $this->logger->addInfo("Session #$sessionId: course '$courseCode' coaches added: '".implode(', ', $coachList)."'");
1945
1946
                                SessionManager::updateCoaches(
1947
                                    $sessionId,
0 ignored issues
show
Bug introduced by
It seems like $sessionId can also be of type string; however, parameter $sessionId of SessionManager::updateCoaches() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

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

1947
                                    /** @scrutinizer ignore-type */ $sessionId,
Loading history...
1948
                                    $courseId,
1949
                                    $coachList,
1950
                                    true
1951
                                );
1952
                            } else {
1953
                                $this->logger->addInfo("No coaches added");
1954
                            }
1955
1956
                            // Students
1957
                            if (!empty($courseUsers)) {
1958
                                $userList = array();
1959
                                foreach ($courseUsers as $username) {
1960
                                    $userInfo = api_get_user_info_from_username(trim($username));
1961
                                    if (!empty($userInfo)) {
1962
                                        $userList[] = $userInfo['user_id'];
1963
                                    }
1964
                                }
1965
1966
                                $this->logger->addInfo("Session #$sessionId: course '$courseCode': Students added '".implode(', ', $userList)."'");
1967
                                SessionManager::subscribe_users_to_session_course(
1968
                                    $userList,
1969
                                    $sessionId,
0 ignored issues
show
Bug introduced by
It seems like $sessionId can also be of type string; however, parameter $session_id of SessionManager::subscrib...ers_to_session_course() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

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

1969
                                    /** @scrutinizer ignore-type */ $sessionId,
Loading history...
1970
                                    $courseCode,
1971
                                    SESSION_VISIBLE_READ_ONLY,
1972
                                    true
1973
                                );
1974
                            } else {
1975
                                $this->logger->addInfo("No users to register.");
1976
                            }
1977
                        }
1978
                    } else {
1979
                        $this->logger->addInfo(
1980
                            'SessionID not found in system.'
1981
                        );
1982
                    }
1983
                } else {
1984
                    $this->logger->addInfo('SessionID does not exists');
1985
                }
1986
            }
1987
        } else {
1988
            $this->logger->addInfo($error_message);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $error_message does not seem to be defined for all execution paths leading up to this point.
Loading history...
1989
        }
1990
1991
        if ($moveFile) {
1992
            $this->moveFile($file);
1993
        }
1994
    }
1995
1996
    /**
1997
     * @param string $file
1998
     * @param bool $moveFile
1999
     * @param array $teacherBackup
2000
     * @param array $groupBackup
2001
     */
2002
    private function importSessions(
2003
        $file,
2004
        $moveFile = true,
2005
        &$teacherBackup = array(),
2006
        &$groupBackup = array()
2007
    ) {
2008
        $avoid = null;
2009
        if (isset($this->conditions['importSessions']) &&
2010
            isset($this->conditions['importSessions']['update'])
2011
        ) {
2012
            $avoid = $this->conditions['importSessions']['update'];
2013
        }
2014
        $result = SessionManager::importCSV(
2015
            $file,
2016
            true,
2017
            $this->defaultAdminId,
2018
            $this->logger,
2019
            array(
2020
                'SessionID' => 'extra_'.$this->extraFieldIdNameList['session'],
2021
                'CareerId' => 'extra_'.$this->extraFieldIdNameList['session_career']
2022
            ),
2023
            $this->extraFieldIdNameList['session'],
2024
            $this->daysCoachAccessBeforeBeginning,
2025
            $this->daysCoachAccessAfterBeginning,
2026
            $this->defaultSessionVisibility,
2027
            $avoid,
2028
            false, // deleteUsersNotInList
2029
            false, // updateCourseCoaches
2030
            true, // sessionWithCoursesModifier
2031
            true, //$addOriginalCourseTeachersAsCourseSessionCoaches
2032
            false, //$removeAllTeachersFromCourse
2033
            1, // $showDescription,
2034
            $teacherBackup,
2035
            $groupBackup
2036
        );
2037
2038
        if (!empty($result['error_message'])) {
2039
            $this->logger->addError($result['error_message']);
2040
        }
2041
        $this->logger->addInfo("Sessions - Sessions parsed: ".$result['session_counter']);
2042
2043
        if ($moveFile) {
2044
            $this->moveFile($file);
2045
        }
2046
    }
2047
2048
    /**
2049
     * @param string $file
2050
     * @param bool $moveFile
2051
     */
2052
    private function importSubscribeStatic($file, $moveFile = true)
2053
    {
2054
        $data = Import::csv_reader($file);
2055
2056
        if (!empty($data)) {
2057
            $this->logger->addInfo(count($data)." records found.");
2058
            foreach ($data as $row) {
2059
                $chamiloUserName = $row['UserName'];
2060
                $chamiloCourseCode = $row['CourseCode'];
2061
                $chamiloSessionId = $row['SessionID'];
2062
                $type = $row['Type'];
2063
2064
                $sessionInfo = api_get_session_info($chamiloSessionId);
2065
2066
                if (empty($sessionInfo)) {
2067
                    $this->logger->addError('Session does not exists: '.$chamiloSessionId);
2068
                    continue;
2069
                }
2070
2071
                $courseInfo = api_get_course_info($chamiloCourseCode);
2072
                if (empty($courseInfo)) {
2073
                    $this->logger->addError('Course does not exists: '.$courseInfo);
2074
                    continue;
2075
                }
2076
2077
                $userId = UserManager::get_user_id_from_username($chamiloUserName);
2078
2079
                if (empty($userId)) {
2080
                    $this->logger->addError('User does not exists: '.$chamiloUserName);
2081
                    continue;
2082
                }
2083
2084
                switch ($type) {
2085
                    case 'student':
2086
                        SessionManager::subscribe_users_to_session_course(
2087
                            array($userId),
2088
                            $chamiloSessionId,
2089
                            $courseInfo['code'],
2090
                            null,
2091
                            false
2092
                        );
2093
                        break;
2094
                    case 'teacher':
2095
                        SessionManager::set_coach_to_course_session(
2096
                            $userId,
2097
                            $chamiloSessionId,
2098
                            $courseInfo['real_id']
2099
                        );
2100
                        break;
2101
                }
2102
2103
                $this->logger->addError(
2104
                    "User '$chamiloUserName' with status $type was added to session: #$chamiloSessionId - Course: ".$courseInfo['code']
2105
                );
2106
            }
2107
        }
2108
2109
        if ($moveFile) {
2110
            $this->moveFile($file);
2111
        }
2112
    }
2113
2114
    /**
2115
     * @param $file
2116
     * @param bool $moveFile
2117
     */
2118
    private function importSubscribeUserToCourse($file, $moveFile = false, &$teacherBackup = [])
2119
    {
2120
        $data = Import::csv_reader($file);
2121
2122
        if (!empty($data)) {
2123
            $this->logger->addInfo(count($data)." records found.");
2124
            foreach ($data as $row) {
2125
                $chamiloUserName = $row['UserName'];
2126
                $chamiloCourseCode = $row['CourseCode'];
2127
                $status = $row['Status'];
2128
2129
                $courseInfo = api_get_course_info($chamiloCourseCode);
2130
2131
                if (empty($courseInfo)) {
2132
                    $this->logger->addError(
2133
                        'Course does not exists: '.$chamiloCourseCode
2134
                    );
2135
                    continue;
2136
                }
2137
2138
                $userId = UserManager::get_user_id_from_username(
2139
                    $chamiloUserName
2140
                );
2141
2142
                if (empty($userId)) {
2143
                    $this->logger->addError(
2144
                        'User does not exists: '.$chamiloUserName
2145
                    );
2146
                    continue;
2147
                }
2148
2149
                $userCourseCategory = '';
2150
                if (isset($teacherBackup[$userId]) &&
2151
                    isset($teacherBackup[$userId][$courseInfo['code']])
2152
                ) {
2153
                    $courseUserData = $teacherBackup[$userId][$courseInfo['code']];
2154
                    $userCourseCategory = $courseUserData['user_course_cat'];
2155
                }
2156
2157
                CourseManager::subscribe_user(
2158
                    $userId,
2159
                    $courseInfo['code'],
2160
                    $status,
2161
                    0,
2162
                    $userCourseCategory
0 ignored issues
show
Bug introduced by
It seems like $userCourseCategory can also be of type string; however, parameter $userCourseCategoryId of CourseManager::subscribe_user() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

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

2162
                    /** @scrutinizer ignore-type */ $userCourseCategory
Loading history...
2163
                );
2164
2165
                $this->logger->addInfo(
2166
                    "User $userId added to course ".$courseInfo['code']." with status '$status' with course category: '$userCourseCategory'"
2167
                );
2168
            }
2169
        }
2170
2171
        if ($moveFile) {
2172
            $this->moveFile($file);
2173
        }
2174
    }
2175
2176
    /**
2177
     * @param $file
2178
     * @param bool $moveFile
2179
     */
2180
    public function importCare($file, $moveFile = false)
2181
    {
2182
        $data = Import::csv_reader($file);
2183
        $counter = 1;
2184
        $batchSize = $this->batchSize;
2185
        $em = Database::getManager();
2186
2187
        if (!empty($data)) {
2188
            $this->logger->addInfo(count($data)." records found.");
2189
            $items = [];
2190
            foreach ($data as $list) {
2191
                $post = [];
2192
                foreach ($list as $key => $value) {
2193
                    $key = (string) trim($key);
2194
                    // Remove utf8 bom
2195
                    $key = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $key);
2196
                    $post[$key] = $value;
2197
                }
2198
2199
                if (empty($post)) {
2200
                    continue;
2201
                }
2202
2203
                $externalId = $post['External_care_id'];
2204
                $items[$externalId] = $post;
2205
            }
2206
            ksort($items);
2207
2208
            foreach ($items as $row) {
2209
                // Insert user
2210
                //$insertUserInfo = api_get_user_info_from_username($row['Added_by']);
2211
2212
                // User about the post
2213
                $userId = UserManager::get_user_id_from_original_id(
2214
                    $row['Added_by'],
2215
                    $this->extraFieldIdNameList['user']
2216
                );
2217
2218
                $insertUserInfo = api_get_user_info($userId);
2219
2220
                if (empty($insertUserInfo)) {
2221
                    $this->logger->addInfo("User: '".$row['Added_by']."' doesn't exists. Skip this entry.");
2222
                    continue;
2223
                }
2224
                $insertUserInfo = api_get_user_entity($insertUserInfo['user_id']);
2225
2226
                // User about the post
2227
                $userId = UserManager::get_user_id_from_original_id(
2228
                    $row['External_user_id'],
2229
                    $this->extraFieldIdNameList['user']
2230
                );
2231
2232
                if (empty($userId)) {
2233
                    $this->logger->addInfo("User does '".$row['External_user_id']."' not exists skip this entry.");
2234
                    continue;
2235
                }
2236
2237
                $userInfo = api_get_user_entity($userId);
2238
2239
                if (empty($userInfo)) {
2240
                    $this->logger->addInfo("Chamilo user does not found: #".$userId."' ");
2241
                    continue;
2242
                }
2243
2244
                // Dates
2245
                $createdAt = $this->createDateTime($row['Added_On']);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $createdAt is correct as $this->createDateTime($row['Added_On']) targeting ImportCsv::createDateTime() seems to always return null.

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

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

}

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

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

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

Loading history...
2246
                $updatedAt = $this->createDateTime($row['Edited_on']);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $updatedAt is correct as $this->createDateTime($row['Edited_on']) targeting ImportCsv::createDateTime() seems to always return null.

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

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

}

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

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

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

Loading history...
2247
2248
                // Parent
2249
                $parent = null;
2250
                if (!empty($row['Parent_id'])) {
2251
                    $parentId = $items[$row['Parent_id']];
2252
                    $criteria = [
2253
                        'externalCareId' => $parentId
2254
                    ];
2255
                    $parent = $em->getRepository('ChamiloPluginBundle:StudentFollowUp\CarePost')->findOneBy($criteria);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $parent is correct as $em->getRepository('Cham...)->findOneBy($criteria) targeting Doctrine\ORM\EntityRepository::findOneBy() seems to always return null.

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

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

}

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

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

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

Loading history...
2256
                }
2257
2258
                // Tags
2259
                $tags = explode(',', $row['Tags']);
2260
2261
                // Check if post already was added:
2262
                $criteria = [
2263
                    'externalCareId' => $row['External_care_id']
2264
                ];
2265
                $post = $em->getRepository('ChamiloPluginBundle:StudentFollowUp\CarePost')->findOneBy($criteria);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $post is correct as $em->getRepository('Cham...)->findOneBy($criteria) targeting Doctrine\ORM\EntityRepository::findOneBy() seems to always return null.

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

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

}

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

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

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

Loading history...
2266
2267
                if (empty($post)) {
2268
                    $post = new CarePost();
2269
                    $this->logger->addInfo("New post will be created no match for externalCareId = ".$row['External_care_id']);
2270
                }
2271
2272
                $contentDecoded = base64_decode($row['Article']);
2273
2274
                $post
2275
                    ->setTitle($row['Title'])
2276
                    ->setContent($contentDecoded)
2277
                    ->setExternalCareId($row['External_care_id'])
2278
                    ->setCreatedAt($createdAt)
2279
                    ->setUpdatedAt($updatedAt)
2280
                    ->setPrivate((int) $row['Private'])
2281
                    ->setInsertUser($insertUserInfo)
2282
                    ->setExternalSource((int) $row['Source_is_external'])
2283
                    ->setParent($parent)
2284
                    ->setTags($tags)
2285
                    ->setUser($userInfo)
2286
                    ->setAttachment($row['Attachement'])
2287
                ;
2288
                $em->persist($post);
2289
                $em->flush();
2290
2291
                $this->logger->addInfo("Post id saved #".$post->getId());
2292
2293
2294
                if (($counter % $batchSize) === 0) {
2295
                    $em->flush();
2296
                    $em->clear(); // Detaches all objects from Doctrine!
2297
                }
2298
                $counter++;
2299
            }
2300
2301
            $em->clear(); // Detaches all objects from Doctrine!
2302
        }
2303
    }
2304
2305
    /**
2306
     * 23/4/2017 to datetime
2307
     * @param $string
2308
     * @return mixed
2309
     */
2310
    private function createDateTime($string)
2311
    {
2312
        if (empty($string)) {
2313
            return null;
2314
        }
2315
2316
        $date = DateTime::createFromFormat('j/m/Y', $string);
2317
        if ($date) {
2318
            return $date;
2319
        }
2320
2321
        return null;
2322
    }
2323
2324
    /**
2325
     * @param $file
2326
     * @param bool $moveFile
2327
     * @param array $teacherBackup
2328
     * @param array $groupBackup
2329
     * @return bool
2330
     */
2331
    private function importCareers(
2332
        $file,
2333
        $moveFile = false,
2334
        &$teacherBackup = array(),
2335
        &$groupBackup = array()
2336
    ) {
2337
        $data = Import::csv_reader($file);
2338
2339
        if (!empty($data)) {
2340
            $this->logger->addInfo(count($data)." records found.");
2341
            $extraFieldValue = new ExtraFieldValue('career');
2342
            $extraFieldName = $this->extraFieldIdNameList['career'];
2343
            $externalEventId = null;
2344
2345
            $extraField = new ExtraField('career');
2346
            $extraFieldInfo = $extraField->get_handler_field_info_by_field_variable(
2347
                $extraFieldName
2348
            );
2349
2350
            if (empty($extraFieldInfo)) {
2351
                return false;
2352
            }
2353
2354
            foreach ($data as $row) {
2355
                foreach ($row as $key => $value) {
2356
                    $key = (string)trim($key);
2357
                    // Remove utf8 bom
2358
                    $key = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $key);
2359
                    $row[$key] = $value;
2360
                }
2361
2362
                $itemId = $row['CareerId'];
2363
                $item = $extraFieldValue->get_item_id_from_field_variable_and_field_value(
2364
                    $extraFieldName,
2365
                    $itemId,
2366
                    false,
2367
                    false,
2368
                    false
2369
                );
2370
2371
                $career = new Career();
2372
                if (empty($item)) {
2373
                    $params = [
2374
                        'status' => 1,
2375
                        'name' => $row['CareerName']
2376
                    ];
2377
                    $careerId = $career->save($params);
2378
                    if ($careerId) {
2379
                        $params = [
2380
                            'item_id' => $careerId,
2381
                            'extra_'.$extraFieldName => $itemId,
2382
                        ];
2383
                        $links = isset($row['HLinks']) ? $row['HLinks'] : [];
2384
                        if (!empty($links)) {
2385
                            $extraFieldUrlName = $this->extraFieldIdNameList['career_urls'];
2386
                            $extraFieldInfo = $extraField->get_handler_field_info_by_field_variable(
2387
                                $extraFieldUrlName
2388
                            );
2389
                            if (!empty($extraFieldInfo)) {
2390
                                $params['extra_'.$extraFieldUrlName] = $links;
2391
                            }
2392
                        }
2393
                        $extraFieldValue->saveFieldValues($params);
2394
                    }
2395
                } else {
2396
                    if (isset($item['item_id'])) {
2397
                        $params = [
2398
                            'id' => $item['item_id'],
2399
                            'name' => $row['CareerName']
2400
                        ];
2401
                        $career->update($params);
2402
                        $links = isset($row['HLinks']) ? $row['HLinks'] : [];
2403
2404
                        if (!empty($links)) {
2405
                            $extraFieldUrlName = $this->extraFieldIdNameList['career_urls'];
2406
                            $extraFieldInfo = $extraField->get_handler_field_info_by_field_variable(
2407
                                $extraFieldUrlName
2408
                            );
2409
                            if (!empty($extraFieldInfo)) {
2410
                                $params = [
2411
                                    'item_id' => $item['item_id'],
2412
                                    'extra_'.$extraFieldName => $itemId,
2413
                                    'extra_'.$extraFieldUrlName => $links
2414
                                ];
2415
                                $extraFieldValue->saveFieldValues($params);
2416
                            }
2417
                        }
2418
                    }
2419
                }
2420
            }
2421
        }
2422
    }
2423
2424
    /**
2425
     * @param $file
2426
     * @param bool $moveFile
2427
     * @param array $teacherBackup
2428
     * @param array $groupBackup
2429
     */
2430
    private function importCareersDiagram(
2431
        $file,
2432
        $moveFile = false,
2433
        &$teacherBackup = array(),
2434
        &$groupBackup = array()
2435
    ) {
2436
        $data = Import::csv_reader($file);
2437
2438
        $extraFieldValue = new ExtraFieldValue('career');
2439
        $extraFieldName = $this->extraFieldIdNameList['career'];
2440
        $externalEventId = null;
2441
2442
        $extraField = new ExtraField('career');
2443
        $extraFieldInfo = $extraField->get_handler_field_info_by_field_variable(
2444
            $extraFieldName
2445
        );
2446
2447
        $careerDiagramExtraFieldName = $this->extraFieldIdNameList['career_diagram'];
2448
        $extraFieldDiagramInfo = $extraField->get_handler_field_info_by_field_variable(
2449
            $careerDiagramExtraFieldName
2450
        );
2451
2452
        if (empty($extraFieldInfo) || empty($extraFieldDiagramInfo)) {
2453
            return false;
2454
        }
2455
2456
        if (!empty($data)) {
2457
            $this->logger->addInfo(count($data)." records found.");
2458
            $values = [];
2459
            foreach ($data as $row) {
2460
                if (empty($row)) {
2461
                    continue;
2462
                }
2463
                foreach ($row as $key => $value) {
2464
                    $key = (string) trim($key);
2465
                    // Remove utf8 bom
2466
                    $key = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $key);
2467
                    $row[$key] = $value;
2468
                }
2469
                $values[$row['Column']][] = $row;
2470
            }
2471
2472
            $careerList = [];
2473
            $careerNameList = [];
2474
            ksort($values);
2475
            $careerChamiloIdList = [];
2476
            // 1. First create all items
2477
            foreach ($values as $column => $rowList) {
2478
                foreach ($rowList as $row) {
2479
                    $careerId = $row['CareerId'];
2480
                    $item = $extraFieldValue->get_item_id_from_field_variable_and_field_value(
2481
                        $extraFieldName,
2482
                        $careerId,
2483
                        false,
2484
                        false,
2485
                        false
2486
                    );
2487
2488
                    $chamiloCareerName = '';
2489
                    if (empty($item)) {
2490
                        $this->logger->addInfo("Career not found: $careerId");
2491
                        continue;
2492
                    } else {
2493
                        if (isset($item['item_id'])) {
2494
                            $careerChamiloId = $item['item_id'];
2495
                            $career = new Career();
2496
                            $career = $career->find($careerChamiloId);
2497
                            $chamiloCareerName = $career['name'];
2498
                            $careerNameList[$careerId] = $chamiloCareerName;
2499
                            $careerChamiloIdList[$careerId] = $careerChamiloId;
2500
                        } else {
2501
                            continue;
2502
                        }
2503
                    }
2504
2505
                    if (empty($chamiloCareerName)) {
2506
                        $this->logger->addInfo("Career not found: $careerId");
2507
                        continue;
2508
                    }
2509
2510
                    if (isset($careerList[$careerId])) {
2511
                        $graph = $careerList[$careerId];
2512
                    } else {
2513
                        $graph = new Graph($careerId);
2514
                        $graph->setAttribute('graphviz.graph.rankdir', 'LR');
2515
                        $careerList[$careerId] = $graph;
2516
                    }
2517
2518
                    $currentCourseId = (int) $row['CourseId'];
2519
                    $name = $row['CourseName'];
2520
                    $notes = $row['Notes'];
2521
                    $groupValue = $row['Group'];
2522
                    $rowValue = $row['Row'];
2523
                    $color = isset($row['DefinedColor']) ? $row['DefinedColor'] : '';
2524
                    $arrow = isset($row['DrawArrowFrom']) ? $row['DrawArrowFrom'] : '';
2525
                    $subGroup = isset($row['SubGroup']) ? $row['SubGroup'] : '';
2526
                    $connections = isset($row['Connections']) ? $row['Connections'] : '';
2527
                    $linkedElement = isset($row['LinkedElement']) ? $row['LinkedElement'] : '';
2528
2529
                    if ($graph->hasVertex($currentCourseId)) {
2530
                        // Avoid double insertion
2531
                        continue;
2532
                    } else {
2533
                        $current = $graph->createVertex($currentCourseId);
2534
                        $current->setAttribute('graphviz.label', $name);
2535
                        $current->setAttribute('DefinedColor', $color);
2536
                        $current->setAttribute('Notes', $notes);
2537
                        $current->setAttribute('Row', $rowValue);
2538
                        $current->setAttribute('Group', $groupValue);
2539
                        $current->setAttribute('DrawArrowFrom', $arrow);
2540
                        $current->setAttribute('SubGroup', $subGroup);
2541
                        $current->setAttribute('Connections', $connections);
2542
                        $current->setAttribute('LinkedElement', $linkedElement);
2543
2544
                        //$current->setAttribute('graphviz.color', 'blue');
2545
                        $current->setAttribute('graphviz.shape', 'box');
2546
                        $current->setGroup($column);
2547
                    }
2548
                }
2549
            }
2550
2551
            // 2. Create connections
2552
            // $column start with 1 (depending in Column row)
2553
            foreach ($values as $column => $rowList) {
2554
                foreach ($rowList as $row) {
2555
                    $careerId = $row['CareerId'];
2556
                    if (isset($careerList[$careerId])) {
2557
                        $graph = $careerList[$careerId];
2558
                    } else {
2559
                        continue;
2560
                    }
2561
2562
                    $currentCourseId = (int) $row['CourseId'];
2563
                    if ($graph->hasVertex($currentCourseId)) {
2564
                        $current = $graph->getVertex($currentCourseId);
2565
                    } else {
2566
                        continue;
2567
                    }
2568
2569
                    if (isset($row['DependedOn']) && !empty($row['DependedOn'])) {
2570
                        $parentList = explode(',', $row['DependedOn']);
2571
                        foreach ($parentList as $parentId) {
2572
                            $parentId = (int) $parentId;
2573
                            if ($graph->hasVertex($parentId)) {
2574
                                /** @var Vertex $parent */
2575
                                $parent = $graph->getVertex($parentId);
2576
                                /*$parent->setAttribute('graphviz.color', 'red');
2577
                                $parent->setAttribute('graphviz.label', $name);
2578
                                $parent->setAttribute('graphviz.shape', 'square');*/
2579
                                $parent->createEdgeTo($current);
2580
                            }
2581
                        }
2582
                    }
2583
                }
2584
            }
2585
2586
            /** @var Graph $graph */
2587
            foreach ($careerList as $id => $graph) {
2588
                if (isset($careerChamiloIdList[$id])) {
2589
                    $params = [
2590
                        'item_id' => $careerChamiloIdList[$id],
2591
                        'extra_'.$careerDiagramExtraFieldName => serialize($graph),
2592
                        'extra_'.$extraFieldName => $id,
2593
                    ];
2594
                    $extraFieldValue->saveFieldValues($params, true);
2595
                }
2596
            }
2597
        }
2598
    }
2599
2600
2601
    /**
2602
     * @param string $file
2603
     * @param bool $moveFile
2604
     * @param array $teacherBackup
2605
     * @param array $groupBackup
2606
     */
2607
    private function importUnsubscribeStatic(
2608
        $file,
2609
        $moveFile = false,
2610
        &$teacherBackup = array(),
2611
        &$groupBackup = array()
2612
    ) {
2613
        $data = Import::csv_reader($file);
2614
2615
        if (!empty($data)) {
2616
            $this->logger->addInfo(count($data)." records found.");
2617
            foreach ($data as $row) {
2618
                $chamiloUserName = $row['UserName'];
2619
                $chamiloCourseCode = $row['CourseCode'];
2620
                $chamiloSessionId = $row['SessionID'];
2621
2622
                $sessionInfo = api_get_session_info($chamiloSessionId);
2623
2624
                if (empty($sessionInfo)) {
2625
                    $this->logger->addError('Session does not exists: '.$chamiloSessionId);
2626
                    continue;
2627
                }
2628
2629
                $courseInfo = api_get_course_info($chamiloCourseCode);
2630
                if (empty($courseInfo)) {
2631
                    $this->logger->addError('Course does not exists: '.$courseInfo);
2632
                    continue;
2633
                }
2634
2635
                $userId = UserManager::get_user_id_from_username($chamiloUserName);
2636
2637
                if (empty($userId)) {
2638
                    $this->logger->addError('User does not exists: '.$chamiloUserName);
2639
                    continue;
2640
                }
2641
2642
                $sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_COURSE_USER)."
2643
                        WHERE
2644
                            user_id = ".$userId." AND
2645
                            c_id = '".$courseInfo['real_id']."'
2646
                        ";
2647
                $result = Database::query($sql);
2648
                $rows = Database::num_rows($result);
2649
                if ($rows > 0) {
2650
                    $userCourseData = Database::fetch_array($result, 'ASSOC');
2651
                    if (!empty($userCourseData)) {
2652
                        $teacherBackup[$userId][$courseInfo['code']] = $userCourseData;
2653
                    }
2654
                }
2655
2656
                $sql = "SELECT * FROM ".Database::get_course_table(TABLE_GROUP_USER)."
2657
                        WHERE
2658
                            user_id = ".$userId." AND
2659
                            c_id = '".$courseInfo['real_id']."'
2660
                        ";
2661
2662
                $result = Database::query($sql);
2663
                while ($groupData = Database::fetch_array($result, 'ASSOC')) {
2664
                    $groupBackup['user'][$userId][$courseInfo['code']][$groupData['group_id']] = $groupData;
2665
                }
2666
2667
                $sql = "SELECT * FROM ".Database::get_course_table(TABLE_GROUP_TUTOR)."
2668
                        WHERE
2669
                            user_id = ".$userId." AND
2670
                            c_id = '".$courseInfo['real_id']."'
2671
                        ";
2672
2673
                $result = Database::query($sql);
2674
                while ($groupData = Database::fetch_array($result, 'ASSOC')) {
2675
                    $groupBackup['tutor'][$userId][$courseInfo['code']][$groupData['group_id']] = $groupData;
2676
                }
2677
2678
                CourseManager::unsubscribe_user(
2679
                    $userId,
2680
                    $courseInfo['code'],
2681
                    $chamiloSessionId
2682
                );
2683
2684
                $this->logger->addError(
2685
                    "User '$chamiloUserName' was removed from session: #$chamiloSessionId, Course: ".$courseInfo['code']
2686
                );
2687
            }
2688
        }
2689
2690
        if ($moveFile) {
2691
            $this->moveFile($file);
2692
        }
2693
    }
2694
2695
    /**
2696
     *  Dump database tables
2697
     */
2698
    private function dumpDatabaseTables()
2699
    {
2700
        echo 'Dumping tables'.PHP_EOL;
2701
2702
        // User
2703
        $table = Database::get_main_table(TABLE_MAIN_USER);
2704
        $tableAdmin = Database::get_main_table(TABLE_MAIN_ADMIN);
2705
        $sql = "DELETE FROM $table
2706
                WHERE user_id not in (select user_id from $tableAdmin) and status <> ".ANONYMOUS;
2707
        Database::query($sql);
2708
        echo $sql.PHP_EOL;
2709
2710
        // Truncate tables
2711
        $truncateTables = array(
2712
            Database::get_main_table(TABLE_MAIN_COURSE),
2713
            Database::get_main_table(TABLE_MAIN_COURSE_USER),
2714
            Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE),
2715
            Database::get_main_table(TABLE_MAIN_CATEGORY),
2716
            Database::get_main_table(TABLE_MAIN_COURSE_MODULE),
2717
            Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER),
2718
            Database::get_main_table(TABLE_MAIN_SESSION),
2719
            Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY),
2720
            Database::get_main_table(TABLE_MAIN_SESSION_COURSE),
2721
            Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER),
2722
            Database::get_main_table(TABLE_MAIN_SESSION_USER),
2723
            Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION),
2724
            Database::get_main_table(TABLE_MAIN_SESSION_FIELD_VALUES),
2725
            Database::get_main_table(TABLE_MAIN_COURSE_FIELD_VALUES),
2726
            Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES),
2727
            Database::get_main_table(TABLE_MAIN_USER_FIELD),
2728
            Database::get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS),
2729
            Database::get_main_table(TABLE_MAIN_COURSE_FIELD),
2730
            Database::get_main_table(TABLE_MAIN_COURSE_FIELD_VALUES),
2731
            Database::get_main_table(TABLE_MAIN_SESSION_FIELD),
2732
            Database::get_main_table(TABLE_MAIN_SESSION_FIELD_VALUES),
2733
            Database::get_course_table(TABLE_AGENDA),
2734
            Database::get_course_table(TABLE_AGENDA_ATTACHMENT),
2735
            Database::get_course_table(TABLE_AGENDA_REPEAT),
2736
            Database::get_course_table(TABLE_AGENDA_REPEAT_NOT),
2737
            Database::get_main_table(TABLE_PERSONAL_AGENDA),
2738
            Database::get_main_table(TABLE_PERSONAL_AGENDA_REPEAT_NOT),
2739
            Database::get_main_table(TABLE_PERSONAL_AGENDA_REPEAT),
2740
            Database::get_main_table(TABLE_MAIN_CALENDAR_EVENT_VALUES),
0 ignored issues
show
Bug introduced by
The constant TABLE_MAIN_CALENDAR_EVENT_VALUES was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
2741
            Database::get_main_table(TABLE_STATISTIC_TRACK_E_LASTACCESS),
2742
            Database::get_main_table(TABLE_STATISTIC_TRACK_E_ACCESS),
2743
            Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN),
2744
            Database::get_main_table(TABLE_STATISTIC_TRACK_E_DOWNLOADS),
2745
            Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES),
0 ignored issues
show
Bug introduced by
The constant TABLE_STATISTIC_TRACK_E_EXERCICES was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
2746
            Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT),
2747
            Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT_RECORDING),
2748
            Database::get_main_table(TABLE_STATISTIC_TRACK_E_DEFAULT),
2749
            Database::get_main_table(TABLE_STATISTIC_TRACK_E_UPLOADS),
2750
            Database::get_main_table(TABLE_STATISTIC_TRACK_E_HOTSPOT),
2751
            Database::get_main_table(TABLE_STATISTIC_TRACK_E_ITEM_PROPERTY),
2752
            Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY),
2753
            Database::get_main_table(TABLE_MAIN_GRADEBOOK_EVALUATION),
2754
            Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINKEVAL_LOG),
2755
            Database::get_main_table(TABLE_MAIN_GRADEBOOK_RESULT),
2756
            Database::get_main_table(TABLE_MAIN_GRADEBOOK_RESULT_LOG),
2757
            Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINK),
2758
            Database::get_main_table(TABLE_MAIN_GRADEBOOK_SCORE_DISPLAY),
2759
            Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE),
2760
            Database::get_course_table(TABLE_STUDENT_PUBLICATION),
2761
            Database::get_course_table(TABLE_QUIZ_QUESTION),
2762
            Database::get_course_table(TABLE_QUIZ_TEST),
2763
            Database::get_course_table(TABLE_QUIZ_ORDER),
2764
            Database::get_course_table(TABLE_QUIZ_ANSWER),
2765
            Database::get_course_table(TABLE_QUIZ_TEST_QUESTION),
2766
            Database::get_course_table(TABLE_QUIZ_QUESTION_OPTION),
2767
            Database::get_course_table(TABLE_QUIZ_QUESTION_CATEGORY),
2768
            Database::get_course_table(TABLE_QUIZ_QUESTION_REL_CATEGORY),
2769
            Database::get_course_table(TABLE_LP_MAIN),
2770
            Database::get_course_table(TABLE_LP_ITEM),
2771
            Database::get_course_table(TABLE_LP_VIEW),
2772
            Database::get_course_table(TABLE_LP_ITEM_VIEW),
2773
            Database::get_course_table(TABLE_DOCUMENT),
2774
            Database::get_course_table(TABLE_ITEM_PROPERTY),
2775
            Database::get_course_table(TABLE_TOOL_LIST),
2776
            Database::get_course_table(TABLE_TOOL_INTRO),
2777
            Database::get_course_table(TABLE_COURSE_SETTING),
2778
            Database::get_course_table(TABLE_SURVEY),
2779
            Database::get_course_table(TABLE_SURVEY_QUESTION),
2780
            Database::get_course_table(TABLE_SURVEY_QUESTION_OPTION),
2781
            Database::get_course_table(TABLE_SURVEY_INVITATION),
2782
            Database::get_course_table(TABLE_SURVEY_ANSWER),
2783
            Database::get_course_table(TABLE_SURVEY_QUESTION_GROUP),
2784
            Database::get_course_table(TABLE_SURVEY_REPORT),
2785
            Database::get_course_table(TABLE_GLOSSARY),
2786
            Database::get_course_table(TABLE_LINK),
2787
            Database::get_course_table(TABLE_LINK_CATEGORY),
2788
            Database::get_course_table(TABLE_GROUP),
2789
            Database::get_course_table(TABLE_GROUP_USER),
2790
            Database::get_course_table(TABLE_GROUP_TUTOR),
2791
            Database::get_course_table(TABLE_GROUP_CATEGORY),
2792
            Database::get_course_table(TABLE_DROPBOX_CATEGORY),
2793
            Database::get_course_table(TABLE_DROPBOX_FEEDBACK),
2794
            Database::get_course_table(TABLE_DROPBOX_POST),
2795
            Database::get_course_table(TABLE_DROPBOX_FILE),
2796
            Database::get_course_table(TABLE_DROPBOX_PERSON)
2797
        );
2798
2799
        foreach ($truncateTables as $table) {
2800
            $sql = "TRUNCATE $table";
2801
            Database::query($sql);
2802
            echo $sql.PHP_EOL;
2803
        }
2804
2805
        $table = Database::get_course_table(TABLE_ITEM_PROPERTY);
2806
        $sql = "DELETE FROM $table WHERE tool = 'calendar_event'";
2807
        Database::query($sql);
2808
        echo $sql.PHP_EOL;
2809
    }
2810
2811
    /**
2812
     * If csv file ends with '"' character then a '";' is added
2813
     * @param string $file
2814
     */
2815
    private function fixCSVFile($file)
2816
    {
2817
        /*$f = fopen($file, 'r+');
2818
        $cursor = -1;
2819
2820
        fseek($f, $cursor, SEEK_END);
2821
        $char = fgetc($f);
2822
        while ($char === "\n" || $char === "\r") {
2823
            fseek($f, $cursor--, SEEK_END);
2824
            $char = fgetc($f);
2825
        }
2826
2827
        if ($char === "\"") {
2828
            fseek($f, -1, SEEK_CUR);
2829
            fwrite($f, '";');
2830
        }*/
2831
    }
2832
2833
    /**
2834
     * @return mixed
2835
     */
2836
    public function getUpdateEmailToDummy()
2837
    {
2838
        return $this->updateEmailToDummy;
2839
    }
2840
2841
    /**
2842
     * @param mixed $updateEmailToDummy
2843
     */
2844
    public function setUpdateEmailToDummy($updateEmailToDummy)
2845
    {
2846
        $this->updateEmailToDummy = $updateEmailToDummy;
2847
    }
2848
2849
    /**
2850
     * Change emails of all users except admins
2851
     *
2852
     */
2853
    public function updateUsersEmails()
2854
    {
2855
        if ($this->getUpdateEmailToDummy() === true) {
2856
            $sql = "UPDATE user SET email = CONCAT(username,'@example.com') WHERE id NOT IN (SELECT user_id FROM admin)";
2857
            Database::query($sql);
2858
        }
2859
    }
2860
}
2861
2862
$logger = new Logger('cron');
2863
$emails = isset($_configuration['cron_notification_mails']) ? $_configuration['cron_notification_mails'] : null;
2864
2865
$minLevel = Logger::DEBUG;
2866
2867
if (!is_array($emails)) {
2868
    $emails = array($emails);
2869
}
2870
$subject = "Cron main/cron/import_csv.php ".date('Y-m-d h:i:s');
2871
$from = api_get_setting('emailAdministrator');
2872
/*
2873
if (!empty($emails)) {
2874
    foreach ($emails as $email) {
2875
        $stream = new NativeMailerHandler($email, $subject, $from, $minLevel);
2876
        $logger->pushHandler(new BufferHandler($stream, 0, $minLevel));
2877
    }
2878
}*/
2879
2880
$stream = new StreamHandler(
2881
    api_get_path(SYS_ARCHIVE_PATH).'import_csv.log',
2882
    $minLevel
2883
);
2884
$logger->pushHandler(new BufferHandler($stream, 0, $minLevel));
2885
$logger->pushHandler(new RotatingFileHandler('import_csv', 5, $minLevel));
2886
2887
$cronImportCSVConditions = isset($_configuration['cron_import_csv_conditions']) ? $_configuration['cron_import_csv_conditions'] : null;
2888
2889
echo 'See the error log here: '.api_get_path(SYS_ARCHIVE_PATH).'import_csv.log'."\n";
2890
2891
$import = new ImportCsv($logger, $cronImportCSVConditions);
2892
2893
if (isset($_configuration['default_admin_user_id_for_cron'])) {
2894
    $import->defaultAdminId = $_configuration['default_admin_user_id_for_cron'];
2895
}
2896
// @todo in production disable the dump option
2897
$dump = false;
2898
2899
if (isset($argv[1]) && $argv[1] = '--dump') {
2900
    $dump = true;
2901
}
2902
2903
if (isset($_configuration['import_csv_disable_dump']) &&
2904
    $_configuration['import_csv_disable_dump'] == true
2905
) {
2906
    $import->setDumpValues(false);
2907
} else {
2908
    $import->setDumpValues($dump);
2909
}
2910
2911
$import->setUpdateEmailToDummy(api_get_configuration_value('update_users_email_to_dummy_except_admins'));
2912
2913
// Do not moves the files to treated
2914
if (isset($_configuration['import_csv_test'])) {
2915
    $import->test = $_configuration['import_csv_test'];
2916
} else {
2917
    $import->test = true;
2918
}
2919
2920
$timeStart = microtime(true);
2921
$import->run();
2922
2923
$timeEnd = microtime(true);
2924
$executionTime = round(($timeEnd - $timeStart) / 60, 2);
2925
$logger->addInfo("Total execution Time $executionTime Min");
2926
2927
if (isset($_configuration['import_csv_fix_permissions']) &&
2928
    $_configuration['import_csv_fix_permissions'] == true
2929
) {
2930
    $command = "sudo find ".api_get_path(SYS_COURSE_PATH)." -type d -exec chmod 777 {} \; ";
2931
    echo "Executing: ".$command.PHP_EOL;
2932
    system($command);
2933
2934
    $command = "sudo find ".api_get_path(SYS_CODE_PATH)."upload/users  -type d -exec chmod 777 {} \;";
2935
    echo "Executing: ".$command.PHP_EOL;
2936
    system($command);
2937
}
2938