Passed
Push — master ( 4447ca...2d5548 )
by Julito
09:52
created

AddCourse   F

Complexity

Total Complexity 78

Size/Duplication

Total Lines 1038
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 632
c 1
b 0
f 0
dl 0
loc 1038
rs 2.128
wmc 78

10 Methods

Rating   Name   Duplication   Size   Complexity  
B define_course_keys() 0 59 7
B get_course_tables() 0 93 1
A drop_course_tables() 0 6 2
B prepare_course_repository() 0 105 1
A generateToolId() 0 18 3
A sort_pictures() 0 10 4
A insertDocument() 0 15 1
A string2binary() 0 7 3
F register_course() 0 246 40
D fillCourse() 0 358 16

How to fix   Complexity   

Complex Class

Complex classes like AddCourse often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use AddCourse, and based on these observations, apply Extract Interface, too.

1
<?php
2
/* For licensing terms, see /license.txt */
3
4
use Chamilo\CoreBundle\Framework\Container;
5
use Chamilo\CourseBundle\Entity\CToolIntro;
6
7
/**
8
 * Class AddCourse.
9
 */
10
class AddCourse
11
{
12
    public const FIRST_EXPIRATION_DATE = 31536000; // 365 days in seconds
13
14
    /**
15
     * Defines the four needed keys to create a course based on several parameters.
16
     *
17
     * @param string    The code you want for this course
18
     * @param string    Prefix added for ALL keys
19
     * @param string    Prefix added for databases only
20
     * @param string    Prefix added for paths only
21
     * @param bool      Add unique prefix
22
     * @param bool      Use code-independent keys
23
     *
24
     * @return array An array with the needed keys ['currentCourseCode'], ['currentCourseId'], ['currentCourseDbName'],
25
     *               ['currentCourseRepository']
26
     *
27
     * @todo Eliminate the global variables.
28
     * @assert (null) === false
29
     */
30
    public static function define_course_keys(
31
        $wanted_code,
32
        $prefix_for_all = '',
33
        $prefix_for_base_name = '',
34
        $prefix_for_path = '',
35
        $add_unique_prefix = false,
36
        $use_code_indepedent_keys = true
37
    ) {
38
        $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
39
        $wanted_code = CourseManager::generate_course_code($wanted_code);
40
        $keys_course_code = $wanted_code;
41
        if (!$use_code_indepedent_keys) {
42
            $wanted_code = '';
43
        }
44
45
        if ($add_unique_prefix) {
46
            $unique_prefix = substr(md5(uniqid(rand())), 0, 10);
47
        } else {
48
            $unique_prefix = '';
49
        }
50
51
        $keys = [];
52
        $final_suffix = ['CourseId' => '', 'CourseDb' => '', 'CourseDir' => ''];
53
        $limit_numb_try = 100;
54
        $keys_are_unique = false;
55
        $try_new_fsc_id = $try_new_fsc_db = $try_new_fsc_dir = 0;
56
57
        while (!$keys_are_unique) {
58
            $keys_course_id = $prefix_for_all.$unique_prefix.$wanted_code.$final_suffix['CourseId'];
59
            $keys_course_repository = $prefix_for_path.$unique_prefix.$wanted_code.$final_suffix['CourseDir'];
60
            $keys_are_unique = true;
61
62
            // Check whether they are unique.
63
            $query = "SELECT 1 FROM $course_table 
64
                      WHERE code='".$keys_course_id."' 
65
                      LIMIT 0, 1";
66
            $result = Database::query($query);
67
68
            if (Database::num_rows($result)) {
69
                $keys_are_unique = false;
70
                $try_new_fsc_id++;
71
                $final_suffix['CourseId'] = substr(md5(uniqid(rand())), 0, 4);
72
            }
73
            if (file_exists(api_get_path(SYS_COURSE_PATH).$keys_course_repository)) {
74
                $keys_are_unique = false;
75
                $try_new_fsc_dir++;
76
                $final_suffix['CourseDir'] = substr(md5(uniqid(rand())), 0, 4);
77
            }
78
79
            if (($try_new_fsc_id + $try_new_fsc_db + $try_new_fsc_dir) > $limit_numb_try) {
80
                return $keys;
81
            }
82
        }
83
84
        $keys['currentCourseCode'] = $keys_course_code;
85
        $keys['currentCourseId'] = $keys_course_id;
86
        $keys['currentCourseRepository'] = $keys_course_repository;
87
88
        return $keys;
89
    }
90
91
    /**
92
     * Initializes a file repository for a newly created course.
93
     *
94
     * @param string Course repository
95
     * @param string Course code
96
     *
97
     * @return int
98
     * @assert (null,null) === false
99
     */
100
    public static function prepare_course_repository($course_repository)
101
    {
102
        $perm = api_get_permissions_for_new_directories();
103
        $perm_file = api_get_permissions_for_new_files();
104
        $htmlpage = "<!DOCTYPE html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"utf-8\">\n    <title>Not authorized</title>\n  </head>\n  <body>\n  </body>\n</html>";
105
        $cp = api_get_path(SYS_COURSE_PATH).$course_repository;
106
107
        //Creating document folder
108
        mkdir($cp, $perm);
109
        mkdir($cp.'/document', $perm);
110
        $cpt = $cp.'/document/index.html';
111
        $fd = fopen($cpt, 'w');
112
        fwrite($fd, $htmlpage);
113
        fclose($fd);
114
115
        /*
116
        @chmod($cpt, $perm_file);
117
        @copy($cpt, $cp . '/document/index.html');
118
        mkdir($cp . '/document/images', $perm);
119
        @copy($cpt, $cp . '/document/images/index.html');
120
        mkdir($cp . '/document/images/gallery/', $perm);
121
        @copy($cpt, $cp . '/document/images/gallery/index.html');
122
        mkdir($cp . '/document/shared_folder/', $perm);
123
        @copy($cpt, $cp . '/document/shared_folder/index.html');
124
        mkdir($cp . '/document/audio', $perm);
125
        @copy($cpt, $cp . '/document/audio/index.html');
126
        mkdir($cp . '/document/flash', $perm);
127
        @copy($cpt, $cp . '/document/flash/index.html');
128
        mkdir($cp . '/document/video', $perm);
129
        @copy($cpt, $cp . '/document/video/index.html');    */
130
131
        //Creatind dropbox folder
132
        mkdir($cp.'/dropbox', $perm);
133
        $cpt = $cp.'/dropbox/index.html';
134
        $fd = fopen($cpt, 'w');
135
        fwrite($fd, $htmlpage);
136
        fclose($fd);
137
        @chmod($cpt, $perm_file);
138
        mkdir($cp.'/group', $perm);
139
        @copy($cpt, $cp.'/group/index.html');
140
        mkdir($cp.'/page', $perm);
141
        @copy($cpt, $cp.'/page/index.html');
142
        mkdir($cp.'/scorm', $perm);
143
        @copy($cpt, $cp.'/scorm/index.html');
144
        mkdir($cp.'/upload', $perm);
145
        @copy($cpt, $cp.'/upload/index.html');
146
        mkdir($cp.'/upload/forum', $perm);
147
        @copy($cpt, $cp.'/upload/forum/index.html');
148
        mkdir($cp.'/upload/forum/images', $perm);
149
        @copy($cpt, $cp.'/upload/forum/images/index.html');
150
        mkdir($cp.'/upload/test', $perm);
151
        @copy($cpt, $cp.'/upload/test/index.html');
152
        mkdir($cp.'/upload/blog', $perm);
153
        @copy($cpt, $cp.'/upload/blog/index.html');
154
        mkdir($cp.'/upload/learning_path', $perm);
155
        @copy($cpt, $cp.'/upload/learning_path/index.html');
156
        mkdir($cp.'/upload/learning_path/images', $perm);
157
        @copy($cpt, $cp.'/upload/learning_path/images/index.html');
158
        mkdir($cp.'/upload/calendar', $perm);
159
        @copy($cpt, $cp.'/upload/calendar/index.html');
160
        mkdir($cp.'/upload/calendar/images', $perm);
161
        @copy($cpt, $cp.'/upload/calendar/images/index.html');
162
        mkdir($cp.'/work', $perm);
163
        @copy($cpt, $cp.'/work/index.html');
164
        mkdir($cp.'/upload/announcements', $perm);
165
        @copy($cpt, $cp.'/upload/announcements/index.html');
166
        mkdir($cp.'/upload/announcements/images', $perm);
167
        @copy($cpt, $cp.'/upload/announcements/images/index.html');
168
169
        //Oral expression question type
170
        mkdir($cp.'/exercises', $perm);
171
        @copy($cpt, $cp.'/exercises/index.html');
172
173
        // Create .htaccess in the dropbox directory.
174
        $fp = fopen($cp.'/dropbox/.htaccess', 'w');
175
        fwrite(
176
            $fp,
177
            "AuthName AllowLocalAccess
178
                       AuthType Basic
179
180
                       order deny,allow
181
                       deny from all
182
183
                       php_flag zlib.output_compression off"
184
        );
185
        fclose($fp);
186
187
        // Build index.php of the course.
188
        /*$fd = fopen($cp . '/index.php', 'w');
189
190
        // str_replace() removes \r that cause squares to appear at the end of each line
191
        //@todo fix the harcoded include
192
        $string = str_replace(
193
            "\r",
194
            "",
195
            "<?" . "php
196
        \$cidReq = \"$course_code\";
197
        \$dbname = \"$course_code\";
198
199
        include(\"" . api_get_path(SYS_CODE_PATH) . "course_home/course_home.php\");
200
        ?>"
201
        );
202
        fwrite($fd, $string);
203
        @chmod($cp . '/index.php', $perm_file);*/
204
        return 0;
205
    }
206
207
    /**
208
     * Gets an array with all the course tables (deprecated?).
209
     *
210
     * @return string[]
211
     * @assert (null) !== null
212
     */
213
    public static function get_course_tables()
214
    {
215
        $tables = [];
216
        $tables[] = 'item_property';
217
        $tables[] = 'tool';
218
        $tables[] = 'tool_intro';
219
        $tables[] = 'group_info';
220
        $tables[] = 'group_category';
221
        $tables[] = 'group_rel_user';
222
        $tables[] = 'group_rel_tutor';
223
        $tables[] = 'userinfo_content';
224
        $tables[] = 'userinfo_def';
225
        $tables[] = 'course_description';
226
        $tables[] = 'calendar_event';
227
        $tables[] = 'calendar_event_repeat';
228
        $tables[] = 'calendar_event_repeat_not';
229
        $tables[] = 'calendar_event_attachment';
230
        $tables[] = 'announcement';
231
        $tables[] = 'announcement_attachment';
232
        $tables[] = 'resource';
233
        $tables[] = 'student_publication';
234
        $tables[] = 'student_publication_assignment';
235
        $tables[] = 'document';
236
        $tables[] = 'forum_post';
237
        $tables[] = 'forum_thread';
238
        $tables[] = 'forum_mailcue';
239
        $tables[] = 'forum_attachment';
240
        $tables[] = 'forum_notification';
241
        $tables[] = 'forum_thread_qualify';
242
        $tables[] = 'forum_thread_qualify_log';
243
        $tables[] = 'forum_forum';
244
        $tables[] = 'forum_category';
245
        $tables[] = 'link';
246
        $tables[] = 'link_category';
247
        $tables[] = 'online_connected';
248
        $tables[] = 'online_link';
249
        $tables[] = 'chat_connected';
250
        $tables[] = 'quiz';
251
        $tables[] = 'quiz_rel_question';
252
        $tables[] = 'quiz_question';
253
        $tables[] = 'quiz_answer';
254
        $tables[] = 'quiz_question_option';
255
        $tables[] = 'quiz_question_category';
256
        $tables[] = 'quiz_question_rel_category';
257
        $tables[] = 'dropbox_post';
258
        $tables[] = 'dropbox_file';
259
        $tables[] = 'dropbox_person';
260
        $tables[] = 'dropbox_category';
261
        $tables[] = 'dropbox_feedback';
262
        $tables[] = 'lp';
263
        $tables[] = 'lp_item';
264
        $tables[] = 'lp_view';
265
        $tables[] = 'lp_item_view';
266
        $tables[] = 'lp_iv_interaction';
267
        $tables[] = 'lp_iv_objective';
268
        $tables[] = 'blog';
269
        $tables[] = 'blog_comment';
270
        $tables[] = 'blog_post';
271
        $tables[] = 'blog_rating';
272
        $tables[] = 'blog_rel_user';
273
        $tables[] = 'blog_task';
274
        $tables[] = 'blog_task_rel_user';
275
        $tables[] = 'blog_attachment';
276
        $tables[] = 'permission_group';
277
        $tables[] = 'permission_user';
278
        $tables[] = 'permission_task';
279
        $tables[] = 'role';
280
        $tables[] = 'role_group';
281
        $tables[] = 'role_permissions';
282
        $tables[] = 'role_user';
283
        $tables[] = 'survey';
284
        $tables[] = 'survey_question';
285
        $tables[] = 'survey_question_option';
286
        $tables[] = 'survey_invitation';
287
        $tables[] = 'survey_answer';
288
        $tables[] = 'survey_group';
289
        $tables[] = 'wiki';
290
        $tables[] = 'wiki_conf';
291
        $tables[] = 'wiki_discuss';
292
        $tables[] = 'wiki_mailcue';
293
        $tables[] = 'course_setting';
294
        $tables[] = 'glossary';
295
        $tables[] = 'notebook';
296
        $tables[] = 'attendance';
297
        $tables[] = 'attendance_sheet';
298
        $tables[] = 'attendance_calendar';
299
        $tables[] = 'attendance_result';
300
        $tables[] = 'attendance_sheet_log';
301
        $tables[] = 'thematic';
302
        $tables[] = 'thematic_plan';
303
        $tables[] = 'thematic_advance';
304
305
        return $tables;
306
    }
307
308
    /**
309
     * Executed only before create_course_tables().
310
     *
311
     * @assert (null) === null
312
     */
313
    public static function drop_course_tables()
314
    {
315
        $list = self::get_course_tables();
316
        foreach ($list as $table) {
317
            $sql = "DROP TABLE IF EXISTS ".DB_COURSE_PREFIX.$table;
318
            Database::query($sql);
319
        }
320
    }
321
322
    /**
323
     * Sorts pictures by type (used?).
324
     *
325
     * @param array List of files (sthg like array(0=>array('png'=>1)))
326
     * @param string $type
327
     *
328
     * @return array The received array without files not matching type
329
     * @assert (array(),null) === array()
330
     */
331
    public static function sort_pictures($files, $type)
332
    {
333
        $pictures = [];
334
        foreach ($files as $value) {
335
            if (isset($value[$type]) && $value[$type] != '') {
336
                $pictures[][$type] = $value[$type];
337
            }
338
        }
339
340
        return $pictures;
341
    }
342
343
    /**
344
     * Fills the course database with some required content and example content.
345
     *
346
     * @param array $courseInfo
347
     * @param bool Whether to fill the course with example content
348
     * @param int $authorId
349
     *
350
     * @return bool False on error, true otherwise
351
     *
352
     * @version 1.2
353
     * @assert (null, '', '', null) === false
354
     * @assert (1, 'ABC', null, null) === false
355
     * @assert (1, 'TEST', 'spanish', true) === true
356
     */
357
    public static function fillCourse(
358
        $courseInfo,
359
        $fill_with_exemplary_content = null,
360
        $authorId = 0
361
    ) {
362
        if (is_null($fill_with_exemplary_content)) {
363
            $fill_with_exemplary_content = api_get_setting('example_material_course_creation') !== 'false';
364
        }
365
366
        $course_id = (int) $courseInfo['real_id'];
367
368
        if (empty($courseInfo)) {
369
            return false;
370
        }
371
        $authorId = empty($authorId) ? api_get_user_id() : (int) $authorId;
372
373
        $TABLEGROUPCATEGORIES = Database::get_course_table(TABLE_GROUP_CATEGORY);
374
        $TABLESETTING = Database::get_course_table(TABLE_COURSE_SETTING);
375
        $TABLEGRADEBOOK = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
376
        $TABLEGRADEBOOKLINK = Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
377
        $visible_for_course_admin = 0;
378
        $em = Database::getManager();
379
        $course = api_get_course_entity($course_id);
380
        $settingsManager = CourseManager::getCourseSettingsManager();
381
        $settingsManager->setCourse($course);
382
383
        $alert = api_get_setting('email_alert_manager_on_new_quiz');
384
        $defaultEmailExerciseAlert = 0;
385
        if ($alert === 'true') {
386
            $defaultEmailExerciseAlert = 1;
387
        }
388
389
        /* course_setting table (courseinfo tool)   */
390
        $settings = [
391
            'email_alert_manager_on_new_doc' => ['title' => '', 'default' => 0, 'category' => 'work'],
392
            'email_alert_on_new_doc_dropbox' => ['default' => 0, 'category' => 'dropbox'],
393
            'allow_user_edit_agenda' => ['default' => 0, 'category' => 'agenda'],
394
            'allow_user_edit_announcement' => ['default' => 0, 'category' => 'announcement'],
395
            'email_alert_manager_on_new_quiz' => ['default' => $defaultEmailExerciseAlert, 'category' => 'quiz'],
396
            'allow_user_image_forum' => ['default' => 1, 'category' => 'forum'],
397
            'course_theme' => ['default' => '', 'category' => 'theme'],
398
            'allow_learning_path_theme' => ['default' => 1, 'category' => 'theme'],
399
            'allow_open_chat_window' => ['default' => 1, 'category' => 'chat'],
400
            'email_alert_to_teacher_on_new_user_in_course' => ['default' => 0, 'category' => 'registration'],
401
            'allow_user_view_user_list' => ['default' => 1, 'category' => 'user'],
402
            'display_info_advance_inside_homecourse' => ['default' => 1, 'category' => 'thematic_advance'],
403
            'email_alert_students_on_new_homework' => ['default' => 0, 'category' => 'work'],
404
            'enable_lp_auto_launch' => ['default' => 0, 'category' => 'learning_path'],
405
            'enable_exercise_auto_launch' => ['default' => 0, 'category' => 'exercise'],
406
            'enable_document_auto_launch' => ['default' => 0, 'category' => 'document'],
407
            'pdf_export_watermark_text' => ['default' => '', 'category' => 'learning_path'],
408
            'allow_public_certificates' => [
409
                'default' => api_get_setting('allow_public_certificates') === 'true' ? 1 : '',
410
                'category' => 'certificates',
411
            ],
412
            'documents_default_visibility' => ['default' => 'visible', 'category' => 'document'],
413
            'show_course_in_user_language' => ['default' => 2, 'category' => null],
414
            'email_to_teachers_on_new_work_feedback' => ['default' => 1, 'category' => null],
415
        ];
416
417
        $counter = 1;
418
        foreach ($settings as $variable => $setting) {
419
            $title = $setting['title'] ?? '';
420
            Database::query(
421
                "INSERT INTO $TABLESETTING (id, c_id, title, variable, value, category)
422
                      VALUES ($counter, $course_id, '".$title."', '".$variable."', '".$setting['default']."', '".$setting['category']."')"
423
            );
424
            $counter++;
425
        }
426
427
        /* Course homepage tools for platform admin only */
428
        /* Group tool */
429
        Database::insert(
430
            $TABLEGROUPCATEGORIES,
431
            [
432
                'c_id' => $course_id,
433
                'id' => 2,
434
                'title' => get_lang('DefaultGroupCategory'),
435
                'description' => '',
436
                'max_student' => 8,
437
                'self_reg_allowed' => 0,
438
                'self_unreg_allowed' => 0,
439
                'groups_per_user' => 0,
440
                'display_order' => 0,
441
                'doc_state' => 1,
442
                'calendar_state' => 1,
443
                'work_state' => 1,
444
                'announcements_state' => 1,
445
                'forum_state' => 1,
446
                'wiki_state' => 1,
447
                'chat_state' => 1,
448
            ]
449
        );
450
451
        $now = api_get_utc_datetime();
452
453
        $files = [
454
            ['path' => '/shared_folder', 'title' => get_lang('UserFolders'), 'filetype' => 'folder', 'size' => 0],
455
            ['path' => '/chat_files', 'title' => get_lang('ChatFiles'), 'filetype' => 'folder', 'size' => 0],
456
        ];
457
458
        $counter = 1;
459
        foreach ($files as $file) {
460
            self::insertDocument($courseInfo, $counter, $file, $authorId);
461
            $counter++;
462
        }
463
464
        $certificateId = 'NULL';
465
466
        /*    Documents   */
467
        if ($fill_with_exemplary_content) {
468
            $files = [
469
                ['path' => '/images', 'title' => get_lang('Images'), 'filetype' => 'folder', 'size' => 0],
470
                ['path' => '/images/gallery', 'title' => get_lang('DefaultCourseImages'), 'filetype' => 'folder', 'size' => 0],
471
                ['path' => '/audio', 'title' => get_lang('Audio'), 'filetype' => 'folder', 'size' => 0],
472
                ['path' => '/flash', 'title' => get_lang('Flash'), 'filetype' => 'folder', 'size' => 0],
473
                ['path' => '/video', 'title' => get_lang('Video'), 'filetype' => 'folder', 'size' => 0],
474
                ['path' => '/certificates', 'title' => get_lang('Certificates'), 'filetype' => 'folder', 'size' => 0],
475
            ];
476
477
            foreach ($files as $file) {
478
                self::insertDocument($courseInfo, $counter, $file, $authorId);
479
                $counter++;
480
            }
481
482
            $finder = new Symfony\Component\Finder\Finder();
483
            $defaultPath = api_get_path(SYS_PUBLIC_PATH).'img/document';
484
            $finder->in($defaultPath);
485
            /** @var SplFileInfo $file */
486
            foreach ($finder as $file) {
487
                $path = str_replace($defaultPath, '', $file->getRealPath());
488
                $parentName = dirname(str_replace($defaultPath, '', $file->getRealPath()));
489
                $title = $file->getFilename();
490
                if ($file->isDir()) {
491
                    create_unexisting_directory(
492
                        $courseInfo,
493
                        api_get_user_id(),
494
                        0,
495
                        0,
496
                        0,
497
                        $path,
498
                        $path,
499
                        $title
500
                    );
501
                } else {
502
                    $parent = DocumentManager::getDocumentByPathInCourse($courseInfo, $parentName);
503
                    $parentId = 0;
504
                    if (!empty($parent)) {
505
                        $parent = $parent[0];
506
                        $parentId = $parent['iid'];
507
                    }
508
509
                    $realPath = str_replace($defaultPath, '', $file->getRealPath());
510
                    $document = DocumentManager::addDocument(
511
                        $courseInfo,
512
                        $realPath,
513
                        'file',
514
                        $file->getSize(),
515
                        $title,
516
                        '',
517
                        null,
518
                        null,
519
                        null,
520
                        null,
521
                        null,
522
                        false,
523
                        null,
524
                        $parentId,
525
                        $file->getRealPath()
526
                    );
527
528
                    if ($document && $document->getTitle() === 'default.html') {
529
                        $certificateId = $document->getIid();
530
                    }
531
                }
532
            }
533
534
            $agenda = new Agenda('course');
535
            $agenda->set_course($courseInfo);
536
            $agenda->addEvent(
537
                $now,
538
                $now,
539
                0,
540
                get_lang('AgendaCreationTitle'),
541
                get_lang('AgendaCreationContenu')
542
            );
543
544
            /*  Links tool */
545
            $link = new Link();
546
            $link->setCourse($courseInfo);
547
            $links = [
548
                [
549
                    'c_id' => $course_id,
550
                    'url' => 'http://www.google.com',
551
                    'title' => 'Google',
552
                    'description' => get_lang('Google'),
553
                    'category_id' => 0,
554
                    'on_homepage' => 0,
555
                    'target' => '_self',
556
                    'session_id' => 0,
557
                ],
558
                [
559
                    'c_id' => $course_id,
560
                    'url' => 'http://www.wikipedia.org',
561
                    'title' => 'Wikipedia',
562
                    'description' => get_lang('Wikipedia'),
563
                    'category_id' => 0,
564
                    'on_homepage' => 0,
565
                    'target' => '_self',
566
                    'session_id' => 0,
567
                ],
568
            ];
569
570
            foreach ($links as $params) {
571
                $link->save($params);
572
            }
573
574
            /* Announcement tool */
575
            AnnouncementManager::add_announcement(
576
                $courseInfo,
577
                0,
578
                get_lang('AnnouncementExampleTitle'),
579
                get_lang('AnnouncementEx'),
580
                ['everyone' => 'everyone'],
581
                null,
582
                null,
583
                $now
584
            );
585
586
            $manager = Database::getManager();
587
588
            /* Introduction text */
589
            $intro_text = '<p style="text-align: center;">
590
                            <img src="'.api_get_path(REL_CODE_PATH).'img/mascot.png" alt="Mr. Chamilo" title="Mr. Chamilo" />
591
                            <h2>'.get_lang('IntroductionText').'</h2>
592
                         </p>';
593
594
            $toolIntro = new CToolIntro();
595
            $toolIntro
596
                ->setCId($course_id)
597
                ->setId(TOOL_COURSE_HOMEPAGE)
598
                ->setSessionId(0)
599
                ->setIntroText($intro_text);
600
            $manager->persist($toolIntro);
601
602
            $toolIntro = new CToolIntro();
603
            $toolIntro
604
                ->setCId($course_id)
605
                ->setId(TOOL_STUDENTPUBLICATION)
606
                ->setSessionId(0)
607
                ->setIntroText(get_lang('IntroductionTwo'));
608
            $manager->persist($toolIntro);
609
610
            $toolIntro = new CToolIntro();
611
            $toolIntro
612
                ->setCId($course_id)
613
                ->setId(TOOL_WIKI)
614
                ->setSessionId(0)
615
                ->setIntroText(get_lang('IntroductionWiki'));
616
            $manager->persist($toolIntro);
617
618
            $manager->flush();
619
620
            /*  Exercise tool */
621
            $exercise = new Exercise($course_id);
622
            $exercise->exercise = get_lang('ExerciceEx');
623
            $html = '<table width="100%" border="0" cellpadding="0" cellspacing="0">
624
                        <tr>
625
                        <td width="220" valign="top" align="left">
626
                            <img src="'.api_get_path(WEB_PUBLIC_PATH).'img/document/images/mr_chamilo/doubts.png">
627
                        </td>
628
                        <td valign="top" align="left">'.get_lang('Antique').'</td></tr>
629
                    </table>';
630
            $exercise->type = 1;
631
            $exercise->setRandom(0);
632
            $exercise->active = 1;
633
            $exercise->results_disabled = 0;
634
            $exercise->description = $html;
635
            $exercise->save();
636
637
            $exercise_id = $exercise->id;
638
639
            $question = new MultipleAnswer();
640
            $question->question = get_lang('SocraticIrony');
641
            $question->description = get_lang('ManyAnswers');
642
            $question->weighting = 10;
643
            $question->position = 1;
644
            $question->course = $courseInfo;
645
            $question->save($exercise);
646
            $questionId = $question->id;
647
648
            $answer = new Answer($questionId, $courseInfo['real_id']);
649
650
            $answer->createAnswer(get_lang('Ridiculise'), 0, get_lang('NoPsychology'), -5, 1);
651
            $answer->createAnswer(get_lang('AdmitError'), 0, get_lang('NoSeduction'), -5, 2);
652
            $answer->createAnswer(get_lang('Force'), 1, get_lang('Indeed'), 5, 3);
653
            $answer->createAnswer(get_lang('Contradiction'), 1, get_lang('NotFalse'), 5, 4);
654
            $answer->save();
655
656
            /* Forum tool */
657
658
            require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
659
660
            $params = [
661
                'forum_category_title' => get_lang('ExampleForumCategory'),
662
                'forum_category_comment' => '',
663
            ];
664
665
            $forumCategoryId = store_forumcategory($params, $courseInfo, false);
666
667
            $params = [
668
                'forum_category' => $forumCategoryId,
669
                'forum_title' => get_lang('ExampleForum'),
670
                'forum_comment' => '',
671
                'default_view_type_group' => ['default_view_type' => 'flat'],
672
            ];
673
674
            $forumId = store_forum($params, $courseInfo, true);
675
676
            $forumInfo = get_forum_information($forumId, $courseInfo['real_id']);
677
678
            $params = [
679
                'post_title' => get_lang('ExampleThread'),
680
                'forum_id' => $forumId,
681
                'post_text' => get_lang('ExampleThreadContent'),
682
                'calification_notebook_title' => '',
683
                'numeric_calification' => '',
684
                'weight_calification' => '',
685
                'forum_category' => $forumCategoryId,
686
                'thread_peer_qualify' => 0,
687
            ];
688
689
            store_thread($forumInfo, $params, $courseInfo, false);
690
691
            /* Gradebook tool */
692
            $course_code = $courseInfo['code'];
693
            // father gradebook
694
            Database::query(
695
                "INSERT INTO $TABLEGRADEBOOK (name, locked, generate_certificates, description, user_id, c_id, parent_id, weight, visible, certif_min_score, session_id, document_id)
696
                VALUES ('$course_code','0',0,'',1,$course_id,0,100,0,75,NULL,$certificateId)"
697
            );
698
            $gbid = Database:: insert_id();
699
            Database::query(
700
                "INSERT INTO $TABLEGRADEBOOK (name, locked, generate_certificates, description, user_id, c_id, parent_id, weight, visible, certif_min_score, session_id, document_id)
701
                VALUES ('$course_code','0',0,'',1,$course_id,$gbid,100,1,75,NULL,$certificateId)"
702
            );
703
            $gbid = Database:: insert_id();
704
            Database::query(
705
                "INSERT INTO $TABLEGRADEBOOKLINK (type, ref_id, user_id, c_id, category_id, created_at, weight, visible, locked)
706
                VALUES (1,$exercise_id,1,$course_id,$gbid,'$now',100,1,0)"
707
            );
708
        }
709
710
        // Installing plugins in course
711
        $app_plugin = new AppPlugin();
712
        $app_plugin->install_course_plugins($course_id);
713
714
        return true;
715
    }
716
717
    /**
718
     * @param array $courseInfo
719
     * @param int   $counter
720
     * @param array $file
721
     * @param int   $authorId
722
     */
723
    public static function insertDocument($courseInfo, $counter, $file, $authorId = 0)
724
    {
725
        DocumentManager::addDocument(
726
            $courseInfo,
727
            $file['path'],
728
            $file['filetype'],
729
            $file['size'],
730
            $file['title'],
731
            null,
732
            0,
733
            null,
734
            0,
735
            0,
736
            0,
737
            false
738
        );
739
    }
740
741
    /**
742
     * string2binary converts the string "true" or "false" to the boolean true false (0 or 1)
743
     * This is used for the Chamilo Config Settings as these store true or false as string
744
     * and the api_get_setting('course_create_active_tools') should be 0 or 1 (used for
745
     * the visibility of the tool).
746
     *
747
     * @param string $variable
748
     *
749
     * @return bool
750
     *
751
     * @author Patrick Cool, [email protected]
752
     * @assert ('true') === true
753
     * @assert ('false') === false
754
     */
755
    public static function string2binary($variable)
756
    {
757
        if ($variable == 'true') {
758
            return true;
759
        }
760
        if ($variable == 'false') {
761
            return false;
762
        }
763
    }
764
765
    /**
766
     * Function register_course to create a record in the course table of the main database.
767
     *
768
     * @param array Course details (see code for details)
769
     *
770
     * @return int Created course ID
771
     *
772
     * @todo use an array called $params instead of lots of params
773
     * @assert (null) === false
774
     */
775
    public static function register_course($params)
776
    {
777
        global $error_msg;
778
        $title = $params['title'];
779
        // Fix amp
780
        $title = str_replace('&amp;', '&', $title);
781
        $code = $params['code'];
782
        $visual_code = $params['visual_code'];
783
        $directory = $params['directory'];
784
        $tutor_name = isset($params['tutor_name']) ? $params['tutor_name'] : null;
785
        $category_code = isset($params['course_category']) ? $params['course_category'] : '';
786
        $course_language = isset($params['course_language']) && !empty($params['course_language']) ? $params['course_language'] : api_get_setting(
787
            'platformLanguage'
788
        );
789
        $user_id = empty($params['user_id']) ? api_get_user_id() : intval($params['user_id']);
790
        $department_name = isset($params['department_name']) ? $params['department_name'] : null;
791
        $department_url = isset($params['department_url']) ? $params['department_url'] : null;
792
        $disk_quota = isset($params['disk_quota']) ? $params['disk_quota'] : null;
793
794
        if (!isset($params['visibility'])) {
795
            $default_course_visibility = api_get_setting(
796
                'courses_default_creation_visibility'
797
            );
798
            if (isset($default_course_visibility)) {
799
                $visibility = $default_course_visibility;
800
            } else {
801
                $visibility = COURSE_VISIBILITY_OPEN_PLATFORM;
802
            }
803
        } else {
804
            $visibility = $params['visibility'];
805
        }
806
807
        $subscribe = isset($params['subscribe']) ? (int) $params['subscribe'] : $visibility == COURSE_VISIBILITY_OPEN_PLATFORM ? 1 : 0;
808
        $unsubscribe = isset($params['unsubscribe']) ? (int) $params['unsubscribe'] : 0;
809
        $expiration_date = isset($params['expiration_date']) ? $params['expiration_date'] : null;
810
        $teachers = isset($params['teachers']) ? $params['teachers'] : null;
811
        $status = isset($params['status']) ? $params['status'] : null;
812
813
        $TABLECOURSUSER = Database::get_main_table(TABLE_MAIN_COURSE_USER);
814
        $ok_to_register_course = true;
815
816
        // Check whether all the needed parameters are present.
817
        if (empty($code)) {
818
            $error_msg[] = 'courseSysCode is missing';
819
            $ok_to_register_course = false;
820
        }
821
        if (empty($visual_code)) {
822
            $error_msg[] = 'courseScreenCode is missing';
823
            $ok_to_register_course = false;
824
        }
825
        if (empty($directory)) {
826
            $error_msg[] = 'courseRepository is missing';
827
            $ok_to_register_course = false;
828
        }
829
830
        if (empty($title)) {
831
            $error_msg[] = 'title is missing';
832
            $ok_to_register_course = false;
833
        }
834
835
        if (empty($expiration_date)) {
836
            $expiration_date = api_get_utc_datetime(
837
                time() + self::FIRST_EXPIRATION_DATE
838
            );
839
        } else {
840
            $expiration_date = api_get_utc_datetime($expiration_date);
841
        }
842
843
        if ($visibility < 0 || $visibility > 4) {
844
            $error_msg[] = 'visibility is invalid';
845
            $ok_to_register_course = false;
846
        }
847
848
        if (empty($disk_quota)) {
849
            $disk_quota = api_get_setting('default_document_quotum');
850
        }
851
852
        if (stripos($department_url, 'http://') === false && stripos(
853
                $department_url,
854
                'https://'
855
            ) === false
856
        ) {
857
            $department_url = 'http://'.$department_url;
858
        }
859
860
        // just in case
861
        if ($department_url == 'http://') {
862
            $department_url = '';
863
        }
864
        $course_id = 0;
865
866
        if ($ok_to_register_course) {
867
            $courseManager = Container::$container->get('chamilo_core.entity.manager.course_manager');
868
            /** @var \Chamilo\CoreBundle\Entity\Course $course */
869
            $course = $courseManager->create();
870
            $urlId = 1;
871
            if (api_get_current_access_url_id() !== -1) {
872
                $urlId = api_get_current_access_url_id();
873
            }
874
875
            $url = api_get_url_entity($urlId);
876
            $course
877
                ->setCode($code)
878
                ->setDirectory($directory)
879
                ->setCourseLanguage($course_language)
880
                ->setTitle($title)
881
                ->setDescription(get_lang('CourseDescription'))
882
                ->setCategoryCode($category_code)
883
                ->setVisibility($visibility)
884
                ->setShowScore(1)
885
                ->setDiskQuota($disk_quota)
886
                ->setCreationDate(new \DateTime())
887
                ->setExpirationDate(new \DateTime($expiration_date))
888
                //->setLastEdit()
889
                ->setDepartmentName($department_name)
890
                ->setDepartmentUrl($department_url)
891
                ->setSubscribe($subscribe)
892
                ->setUnsubscribe($unsubscribe)
893
                ->setVisualCode($visual_code)
894
                ->addUrl($url)
895
            ;
896
897
            $courseManager->save($course, true);
898
            $course_id = $course->getId();
899
900
            if ($course_id) {
901
                $sort = api_max_sort_value('0', api_get_user_id());
902
                // Default true
903
                $addTeacher = isset($params['add_user_as_teacher']) ? $params['add_user_as_teacher'] : true;
904
                if ($addTeacher) {
905
                    $i_course_sort = CourseManager::userCourseSort(
906
                        $user_id,
907
                        $code
908
                    );
909
                    if (!empty($user_id)) {
910
                        $sql = "INSERT INTO ".$TABLECOURSUSER." SET
911
                                c_id     = '".$course_id."',
912
                                user_id         = '".intval($user_id)."',
913
                                status          = '1',
914
                                is_tutor        = '0',
915
                                sort            = '".($i_course_sort)."',
916
                                relation_type = 0,
917
                                user_course_cat = '0'";
918
                        Database::query($sql);
919
                    }
920
                }
921
922
                if (!empty($teachers)) {
923
                    if (!is_array($teachers)) {
924
                        $teachers = [$teachers];
925
                    }
926
                    foreach ($teachers as $key) {
927
                        //just in case
928
                        if ($key == $user_id) {
929
                            continue;
930
                        }
931
                        if (empty($key)) {
932
                            continue;
933
                        }
934
                        $sql = "INSERT INTO ".$TABLECOURSUSER." SET
935
                            c_id     = '".Database::escape_string($course_id)."',
936
                            user_id         = '".Database::escape_string($key)."',
937
                            status          = '1',
938
                            is_tutor        = '0',
939
                            sort            = '".($sort + 1)."',
940
                            relation_type = 0,
941
                            user_course_cat = '0'";
942
                        Database::query($sql);
943
                    }
944
                }
945
946
                // Adding the course to an URL.
947
                // Already added by when saving the entity
948
                /*if (api_is_multiple_url_enabled()) {
949
                    $url_id = 1;
950
                    if (api_get_current_access_url_id() != -1) {
951
                        $url_id = api_get_current_access_url_id();
952
                    }
953
                    UrlManager::add_course_to_url($course_id, $url_id);
954
                } else {
955
                    UrlManager::add_course_to_url($course_id, 1);
956
                }*/
957
958
                // Add event to the system log.
959
                $user_id = api_get_user_id();
960
                Event::addEvent(
961
                    LOG_COURSE_CREATE,
962
                    LOG_COURSE_CODE,
963
                    $code,
964
                    api_get_utc_datetime(),
965
                    $user_id,
966
                    $course_id
967
                );
968
969
                $send_mail_to_admin = api_get_setting('send_email_to_admin_when_create_course');
970
971
                // @todo Improve code to send to all current portal administrators.
972
                if ($send_mail_to_admin === 'true') {
973
                    $siteName = api_get_setting('siteName');
974
                    $recipient_email = api_get_setting('emailAdministrator');
975
                    $recipient_name = api_get_person_name(
976
                        api_get_setting('administratorName'),
977
                        api_get_setting('administratorSurname')
978
                    );
979
                    $iname = api_get_setting('Institution');
980
                    $subject = get_lang(
981
                            'NewCourseCreatedIn'
982
                        ).' '.$siteName.' - '.$iname;
983
                    $message = get_lang(
984
                            'Dear'
985
                        ).' '.$recipient_name.",\n\n".get_lang(
986
                            'MessageOfNewCourseToAdmin'
987
                        ).' '.$siteName.' - '.$iname."\n";
988
                    $message .= get_lang('CourseName').' '.$title."\n";
989
                    $message .= get_lang(
990
                            'Category'
991
                        ).' '.$category_code."\n";
992
                    $message .= get_lang('Tutor').' '.$tutor_name."\n";
993
                    $message .= get_lang('Language').' '.$course_language;
994
995
                    $userInfo = api_get_user_info($user_id);
996
997
                    $additionalParameters = [
998
                        'smsType' => SmsPlugin::NEW_COURSE_BEEN_CREATED,
999
                        'userId' => $user_id,
1000
                        'courseName' => $title,
1001
                        'creatorUsername' => $userInfo['username'],
1002
                    ];
1003
1004
                    api_mail_html(
1005
                        $recipient_name,
1006
                        $recipient_email,
1007
                        $subject,
1008
                        $message,
1009
                        $siteName,
1010
                        $recipient_email,
1011
                        null,
1012
                        null,
1013
                        null,
1014
                        $additionalParameters
1015
                    );
1016
                }
1017
            }
1018
        }
1019
1020
        return $course_id;
1021
    }
1022
1023
    /**
1024
     * Generate a new id for c_tool table.
1025
     *
1026
     * @param int $courseId The course id
1027
     *
1028
     * @return int the new id
1029
     */
1030
    public static function generateToolId($courseId)
1031
    {
1032
        $newIdResultData = Database::select(
1033
            'id + 1 AS new_id',
1034
            Database::get_course_table(TABLE_TOOL_LIST),
1035
            [
1036
                'where' => ['c_id = ?' => intval($courseId)],
1037
                'order' => 'id',
1038
                'limit' => 1,
1039
            ],
1040
            'first'
1041
        );
1042
1043
        if ($newIdResultData === false) {
1044
            return 1;
1045
        }
1046
1047
        return $newIdResultData['new_id'] > 0 ? $newIdResultData['new_id'] : 1;
1048
    }
1049
}
1050