Passed
Push — master ( f2a413...87c0a1 )
by Julito
09:14
created

AddCourse::fill_db_course()   D

Complexity

Conditions 14
Paths 130

Size

Total Lines 353
Code Lines 248

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 14
eloc 248
nc 130
nop 5
dl 0
loc 353
rs 4.8133
c 1
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
/* For licensing terms, see /license.txt */
3
4
use Chamilo\CoreBundle\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
     * Returns a list of all files in the given course directory. The requested
324
     * directory will be checked against a "checker" directory to avoid access to
325
     * protected/unauthorized files.
326
     *
327
     * @param string Complete path to directory we want to list
328
     * @param array A list of files to which we want to add the files found
329
     * @param string Type of base directory from which we want to recover the files
330
     * @param string $path
331
     * @param string $media
332
     *
333
     * @return array
334
     * @assert (null,null,null) === false
335
     * @assert ('abc',array(),'') === array()
336
     */
337
    public static function browse_folders($path, $files, $media)
338
    {
339
        if ($media == 'images') {
340
            $code_path = api_get_path(SYS_CODE_PATH).'default_course_document/images/';
341
        }
342
        if ($media == 'audio') {
343
            $code_path = api_get_path(SYS_CODE_PATH).'default_course_document/audio/';
344
        }
345
        if ($media == 'flash') {
346
            $code_path = api_get_path(SYS_CODE_PATH).'default_course_document/flash/';
347
        }
348
        if ($media == 'video') {
349
            $code_path = api_get_path(SYS_CODE_PATH).'default_course_document/video/';
350
        }
351
        if ($media == 'certificates') {
352
            $code_path = api_get_path(SYS_CODE_PATH).'default_course_document/certificates/';
353
        }
354
        if (is_dir($path)) {
355
            $handle = opendir($path);
356
            while (false !== ($file = readdir($handle))) {
357
                if (is_dir($path.$file) && strpos($file, '.') !== 0) {
358
                    $files[]['dir'] = str_replace(
359
                        $code_path,
360
                        '',
361
                        $path.$file.'/'
362
                    );
363
                    $files = self::browse_folders(
364
                        $path.$file.'/',
365
                        $files,
366
                        $media
367
                    );
368
                } elseif (is_file($path.$file) && strpos($file, '.') !== 0) {
369
                    $files[]['file'] = str_replace(
370
                        $code_path,
371
                        '',
372
                        $path.$file
373
                    );
374
                }
375
            }
376
        }
377
378
        return $files;
379
    }
380
381
    /**
382
     * Sorts pictures by type (used?).
383
     *
384
     * @param array List of files (sthg like array(0=>array('png'=>1)))
385
     * @param string $type
386
     *
387
     * @return array The received array without files not matching type
388
     * @assert (array(),null) === array()
389
     */
390
    public static function sort_pictures($files, $type)
391
    {
392
        $pictures = [];
393
        foreach ($files as $value) {
394
            if (isset($value[$type]) && $value[$type] != '') {
395
                $pictures[][$type] = $value[$type];
396
            }
397
        }
398
399
        return $pictures;
400
    }
401
402
    /**
403
     * Fills the course database with some required content and example content.
404
     *
405
     * @param int Course (int) ID
406
     * @param string Course directory name (e.g. 'ABC')
407
     * @param string Language used for content (e.g. 'spanish')
408
     * @param bool Whether to fill the course with example content
409
     * @param int $authorId
410
     *
411
     * @return bool False on error, true otherwise
412
     *
413
     * @version 1.2
414
     * @assert (null, '', '', null) === false
415
     * @assert (1, 'ABC', null, null) === false
416
     * @assert (1, 'TEST', 'spanish', true) === true
417
     */
418
    public static function fill_db_course(
419
        $course_id,
420
        $course_repository,
421
        $language,
422
        $fill_with_exemplary_content = null,
423
        $authorId = 0
424
    ) {
425
        if (is_null($fill_with_exemplary_content)) {
426
            $fill_with_exemplary_content = api_get_setting('example_material_course_creation') !== 'false';
427
        }
428
        $course_id = (int) $course_id;
429
        $courseInfo = api_get_course_info_by_id($course_id);
430
431
        if (empty($courseInfo)) {
432
            return false;
433
        }
434
        $authorId = empty($authorId) ? api_get_user_id() : (int) $authorId;
435
436
        $TABLEGROUPCATEGORIES = Database::get_course_table(TABLE_GROUP_CATEGORY);
437
        $TABLESETTING = Database::get_course_table(TABLE_COURSE_SETTING);
438
        $TABLEGRADEBOOK = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
439
        $TABLEGRADEBOOKLINK = Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
440
        $visible_for_course_admin = 0;
441
        $em = Database::getManager();
442
        $course = api_get_course_entity($course_id);
443
        $settingsManager = CourseManager::getCourseSettingsManager();
444
        $settingsManager->setCourse($course);
445
446
        $alert = api_get_setting('email_alert_manager_on_new_quiz');
447
        $defaultEmailExerciseAlert = 0;
448
        if ($alert === 'true') {
449
            $defaultEmailExerciseAlert = 1;
450
        }
451
452
        /* course_setting table (courseinfo tool)   */
453
        $settings = [
454
            'email_alert_manager_on_new_doc' => ['title' => '', 'default' => 0, 'category' => 'work'],
455
            'email_alert_on_new_doc_dropbox' => ['default' => 0, 'category' => 'dropbox'],
456
            'allow_user_edit_agenda' => ['default' => 0, 'category' => 'agenda'],
457
            'allow_user_edit_announcement' => ['default' => 0, 'category' => 'announcement'],
458
            'email_alert_manager_on_new_quiz' => ['default' => $defaultEmailExerciseAlert, 'category' => 'quiz'],
459
            'allow_user_image_forum' => ['default' => 1, 'category' => 'forum'],
460
            'course_theme' => ['default' => '', 'category' => 'theme'],
461
            'allow_learning_path_theme' => ['default' => 1, 'category' => 'theme'],
462
            'allow_open_chat_window' => ['default' => 1, 'category' => 'chat'],
463
            'email_alert_to_teacher_on_new_user_in_course' => ['default' => 0, 'category' => 'registration'],
464
            'allow_user_view_user_list' => ['default' => 1, 'category' => 'user'],
465
            'display_info_advance_inside_homecourse' => ['default' => 1, 'category' => 'thematic_advance'],
466
            'email_alert_students_on_new_homework' => ['default' => 0, 'category' => 'work'],
467
            'enable_lp_auto_launch' => ['default' => 0, 'category' => 'learning_path'],
468
            'enable_exercise_auto_launch' => ['default' => 0, 'category' => 'exercise'],
469
            'enable_document_auto_launch' => ['default' => 0, 'category' => 'document'],
470
            'pdf_export_watermark_text' => ['default' => '', 'category' => 'learning_path'],
471
            'allow_public_certificates' => [
472
                'default' => api_get_setting('allow_public_certificates') === 'true' ? 1 : '',
473
                'category' => 'certificates',
474
            ],
475
            'documents_default_visibility' => ['default' => 'visible', 'category' => 'document'],
476
            'show_course_in_user_language' => ['default' => 2, 'category' => null],
477
            'email_to_teachers_on_new_work_feedback' => ['default' => 1, 'category' => null],
478
        ];
479
480
        $counter = 1;
481
        foreach ($settings as $variable => $setting) {
482
            $title = $setting['title'] ?? '';
483
            Database::query(
484
                "INSERT INTO $TABLESETTING (id, c_id, title, variable, value, category)
485
                      VALUES ($counter, $course_id, '".$title."', '".$variable."', '".$setting['default']."', '".$setting['category']."')"
486
            );
487
            $counter++;
488
        }
489
490
        /* Course homepage tools for platform admin only */
491
492
        /* Group tool */
493
        Database::insert(
494
            $TABLEGROUPCATEGORIES,
495
            [
496
                'c_id' => $course_id,
497
                'id' => 2,
498
                'title' => get_lang('DefaultGroupCategory'),
499
                'description' => '',
500
                'max_student' => 8,
501
                'self_reg_allowed' => 0,
502
                'self_unreg_allowed' => 0,
503
                'groups_per_user' => 0,
504
                'display_order' => 0,
505
                'doc_state' => 1,
506
                'calendar_state' => 1,
507
                'work_state' => 1,
508
                'announcements_state' => 1,
509
                'forum_state' => 1,
510
                'wiki_state' => 1,
511
                'chat_state' => 1,
512
            ]
513
        );
514
515
        $now = api_get_utc_datetime();
516
517
        $files = [
518
            ['path' => '/shared_folder', 'title' => get_lang('UserFolders'), 'filetype' => 'folder', 'size' => 0],
519
            ['path' => '/chat_files', 'title' => get_lang('ChatFiles'), 'filetype' => 'folder', 'size' => 0],
520
        ];
521
522
        $counter = 1;
523
        foreach ($files as $file) {
524
            self::insertDocument($courseInfo, $counter, $file, $authorId);
525
            $counter++;
526
        }
527
528
        /*    Documents   */
529
        if ($fill_with_exemplary_content) {
530
            $files = [
531
                ['path' => '/images', 'title' => get_lang('Images'), 'filetype' => 'folder', 'size' => 0],
532
                ['path' => '/images/gallery', 'title' => get_lang('DefaultCourseImages'), 'filetype' => 'folder', 'size' => 0],
533
                ['path' => '/audio', 'title' => get_lang('Audio'), 'filetype' => 'folder', 'size' => 0],
534
                ['path' => '/flash', 'title' => get_lang('Flash'), 'filetype' => 'folder', 'size' => 0],
535
                ['path' => '/video', 'title' => get_lang('Video'), 'filetype' => 'folder', 'size' => 0],
536
                ['path' => '/certificates', 'title' => get_lang('Certificates'), 'filetype' => 'folder', 'size' => 0],
537
            ];
538
539
            foreach ($files as $file) {
540
                self::insertDocument($courseInfo, $counter, $file, $authorId);
541
                $counter++;
542
            }
543
544
            $finder = new Symfony\Component\Finder\Finder();
545
            $defaultPath = api_get_path(SYS_CODE_PATH).'default_course_document';
546
            $finder->in($defaultPath);
547
            /** @var SplFileInfo $file */
548
            foreach ($finder as $file) {
549
                $path = str_replace($defaultPath, '', $file->getRealPath());
550
                $parentName = dirname(str_replace($defaultPath, '', $file->getRealPath()));
551
                $title = $file->getFilename();
552
                if ($file->isDir()) {
553
                    create_unexisting_directory(
554
                        $courseInfo,
555
                        api_get_user_id(),
556
                        0,
557
                        0,
558
                        0,
559
                        $path,
560
                        $title,
561
                        $title
562
                    );
563
                } else {
564
                    $parent = DocumentManager::getDocumentByPathInCourse($courseInfo, $parentName);
565
                    $parentId = 0;
566
                    if (!empty($parent)) {
567
                        $parent = $parent[0];
568
                        $parentId = $parent['iid'];
569
                    }
570
571
                    DocumentManager::addDocument(
572
                        $courseInfo,
573
                        $file->getRealPath(),
574
                        'file',
575
                        $file->getSize(),
576
                        $title,
577
                        '',
578
                        null,
579
                        null,
580
                        null,
581
                        null,
582
                        null,
583
                        false,
584
                        null,
585
                        $parentId
586
                    );
587
                }
588
            }
589
590
            $agenda = new Agenda('course');
591
            $agenda->set_course($courseInfo);
592
            $agenda->addEvent(
593
                $now,
594
                $now,
595
                0,
596
                get_lang('AgendaCreationTitle'),
597
                get_lang('AgendaCreationContenu')
598
            );
599
600
            /*  Links tool */
601
            $link = new Link();
602
            $link->setCourse($courseInfo);
603
            $links = [
604
                [
605
                    'c_id' => $course_id,
606
                    'url' => 'http://www.google.com',
607
                    'title' => 'Google',
608
                    'description' => get_lang('Google'),
609
                    'category_id' => 0,
610
                    'on_homepage' => 0,
611
                    'target' => '_self',
612
                    'session_id' => 0,
613
                ],
614
                [
615
                    'c_id' => $course_id,
616
                    'url' => 'http://www.wikipedia.org',
617
                    'title' => 'Wikipedia',
618
                    'description' => get_lang('Wikipedia'),
619
                    'category_id' => 0,
620
                    'on_homepage' => 0,
621
                    'target' => '_self',
622
                    'session_id' => 0,
623
                ],
624
            ];
625
626
            foreach ($links as $params) {
627
                $link->save($params);
628
            }
629
630
            /* Announcement tool */
631
            AnnouncementManager::add_announcement(
632
                $courseInfo,
633
                0,
634
                get_lang('AnnouncementExampleTitle'),
635
                get_lang('AnnouncementEx'),
636
                ['everyone' => 'everyone'],
637
                null,
638
                null,
639
                $now
640
            );
641
642
            $manager = Database::getManager();
643
644
            /* Introduction text */
645
            $intro_text = '<p style="text-align: center;">
646
                            <img src="'.api_get_path(REL_CODE_PATH).'img/mascot.png" alt="Mr. Chamilo" title="Mr. Chamilo" />
647
                            <h2>'.get_lang('IntroductionText').'</h2>
648
                         </p>';
649
650
            $toolIntro = new CToolIntro();
651
            $toolIntro
652
                ->setCId($course_id)
653
                ->setId(TOOL_COURSE_HOMEPAGE)
654
                ->setSessionId(0)
655
                ->setIntroText($intro_text);
656
            $manager->persist($toolIntro);
657
658
            $toolIntro = new CToolIntro();
659
            $toolIntro
660
                ->setCId($course_id)
661
                ->setId(TOOL_STUDENTPUBLICATION)
662
                ->setSessionId(0)
663
                ->setIntroText(get_lang('IntroductionTwo'));
664
            $manager->persist($toolIntro);
665
666
            $toolIntro = new CToolIntro();
667
            $toolIntro
668
                ->setCId($course_id)
669
                ->setId(TOOL_WIKI)
670
                ->setSessionId(0)
671
                ->setIntroText(get_lang('IntroductionWiki'));
672
            $manager->persist($toolIntro);
673
674
            $manager->flush();
675
676
            /*  Exercise tool */
677
            $exercise = new Exercise($course_id);
678
            $exercise->exercise = get_lang('ExerciceEx');
679
            $html = '<table width="100%" border="0" cellpadding="0" cellspacing="0">
680
                        <tr>
681
                        <td width="220" valign="top" align="left">
682
                            <img src="'.api_get_path(WEB_CODE_PATH).'default_course_document/images/mr_chamilo/doubts.png">
683
                        </td>
684
                        <td valign="top" align="left">'.get_lang('Antique').'</td></tr>
685
                    </table>';
686
            $exercise->type = 1;
687
            $exercise->setRandom(0);
688
            $exercise->active = 1;
689
            $exercise->results_disabled = 0;
690
            $exercise->description = $html;
691
            $exercise->save();
692
693
            $exercise_id = $exercise->id;
694
695
            $question = new MultipleAnswer();
696
            $question->question = get_lang('SocraticIrony');
697
            $question->description = get_lang('ManyAnswers');
698
            $question->weighting = 10;
699
            $question->position = 1;
700
            $question->course = $courseInfo;
701
            $question->save($exercise);
702
            $questionId = $question->id;
703
704
            $answer = new Answer($questionId, $courseInfo['real_id']);
705
706
            $answer->createAnswer(get_lang('Ridiculise'), 0, get_lang('NoPsychology'), -5, 1);
707
            $answer->createAnswer(get_lang('AdmitError'), 0, get_lang('NoSeduction'), -5, 2);
708
            $answer->createAnswer(get_lang('Force'), 1, get_lang('Indeed'), 5, 3);
709
            $answer->createAnswer(get_lang('Contradiction'), 1, get_lang('NotFalse'), 5, 4);
710
            $answer->save();
711
712
            /* Forum tool */
713
714
            require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
715
716
            $params = [
717
                'forum_category_title' => get_lang('ExampleForumCategory'),
718
                'forum_category_comment' => '',
719
            ];
720
721
            $forumCategoryId = store_forumcategory($params, $courseInfo, false);
722
723
            $params = [
724
                'forum_category' => $forumCategoryId,
725
                'forum_title' => get_lang('ExampleForum'),
726
                'forum_comment' => '',
727
                'default_view_type_group' => ['default_view_type' => 'flat'],
728
            ];
729
730
            $forumId = store_forum($params, $courseInfo, true);
731
732
            $forumInfo = get_forum_information($forumId, $courseInfo['real_id']);
733
734
            $params = [
735
                'post_title' => get_lang('ExampleThread'),
736
                'forum_id' => $forumId,
737
                'post_text' => get_lang('ExampleThreadContent'),
738
                'calification_notebook_title' => '',
739
                'numeric_calification' => '',
740
                'weight_calification' => '',
741
                'forum_category' => $forumCategoryId,
742
                'thread_peer_qualify' => 0,
743
            ];
744
745
            store_thread($forumInfo, $params, $courseInfo, false);
746
747
            /* Gradebook tool */
748
            $course_code = $courseInfo['code'];
749
            // father gradebook
750
            Database::query(
751
                "INSERT INTO $TABLEGRADEBOOK (name, locked, generate_certificates, description, user_id, c_id, parent_id, weight, visible, certif_min_score, session_id, document_id)
752
                VALUES ('$course_code','0',0,'',1,$course_id,0,100,0,75,NULL,$example_cert_id)"
753
            );
754
            $gbid = Database:: insert_id();
755
            Database::query(
756
                "INSERT INTO $TABLEGRADEBOOK (name, locked, generate_certificates, description, user_id, c_id, parent_id, weight, visible, certif_min_score, session_id, document_id)
757
                VALUES ('$course_code','0',0,'',1,$course_id,$gbid,100,1,75,NULL,$example_cert_id)"
758
            );
759
            $gbid = Database:: insert_id();
760
            Database::query(
761
                "INSERT INTO $TABLEGRADEBOOKLINK (type, ref_id, user_id, c_id, category_id, created_at, weight, visible, locked)
762
                VALUES (1,$exercise_id,1,$course_id,$gbid,'$now',100,1,0)"
763
            );
764
        }
765
766
        // Installing plugins in course
767
        $app_plugin = new AppPlugin();
768
        $app_plugin->install_course_plugins($course_id);
769
770
        return true;
771
    }
772
773
    /**
774
     * @param array $courseInfo
775
     * @param int   $counter
776
     * @param array $file
777
     * @param int   $authorId
778
     */
779
    public static function insertDocument($courseInfo, $counter, $file, $authorId = 0)
780
    {
781
        DocumentManager::addDocument(
782
            $courseInfo,
783
            $file['path'],
784
            $file['filetype'],
785
            $file['size'],
786
            $file['title'],
787
            null,
788
            0,
789
            null,
790
            0,
791
            0,
792
            0,
793
            false
794
        );
795
    }
796
797
    /**
798
     * string2binary converts the string "true" or "false" to the boolean true false (0 or 1)
799
     * This is used for the Chamilo Config Settings as these store true or false as string
800
     * and the api_get_setting('course_create_active_tools') should be 0 or 1 (used for
801
     * the visibility of the tool).
802
     *
803
     * @param string $variable
804
     *
805
     * @return bool
806
     *
807
     * @author Patrick Cool, [email protected]
808
     * @assert ('true') === true
809
     * @assert ('false') === false
810
     */
811
    public static function string2binary($variable)
812
    {
813
        if ($variable == 'true') {
814
            return true;
815
        }
816
        if ($variable == 'false') {
817
            return false;
818
        }
819
    }
820
821
    /**
822
     * Function register_course to create a record in the course table of the main database.
823
     *
824
     * @param array Course details (see code for details)
825
     *
826
     * @return int Created course ID
827
     *
828
     * @todo use an array called $params instead of lots of params
829
     * @assert (null) === false
830
     */
831
    public static function register_course($params)
832
    {
833
        global $error_msg;
834
        $title = $params['title'];
835
        // Fix amp
836
        $title = str_replace('&amp;', '&', $title);
837
        $code = $params['code'];
838
        $visual_code = $params['visual_code'];
839
        $directory = $params['directory'];
840
        $tutor_name = isset($params['tutor_name']) ? $params['tutor_name'] : null;
841
        $category_code = isset($params['course_category']) ? $params['course_category'] : '';
842
        $course_language = isset($params['course_language']) && !empty($params['course_language']) ? $params['course_language'] : api_get_setting(
843
            'platformLanguage'
844
        );
845
        $user_id = empty($params['user_id']) ? api_get_user_id() : intval($params['user_id']);
846
        $department_name = isset($params['department_name']) ? $params['department_name'] : null;
847
        $department_url = isset($params['department_url']) ? $params['department_url'] : null;
848
        $disk_quota = isset($params['disk_quota']) ? $params['disk_quota'] : null;
849
850
        if (!isset($params['visibility'])) {
851
            $default_course_visibility = api_get_setting(
852
                'courses_default_creation_visibility'
853
            );
854
            if (isset($default_course_visibility)) {
855
                $visibility = $default_course_visibility;
856
            } else {
857
                $visibility = COURSE_VISIBILITY_OPEN_PLATFORM;
858
            }
859
        } else {
860
            $visibility = $params['visibility'];
861
        }
862
863
        $subscribe = isset($params['subscribe']) ? (int) $params['subscribe'] : $visibility == COURSE_VISIBILITY_OPEN_PLATFORM ? 1 : 0;
864
        $unsubscribe = isset($params['unsubscribe']) ? (int) $params['unsubscribe'] : 0;
865
        $expiration_date = isset($params['expiration_date']) ? $params['expiration_date'] : null;
866
        $teachers = isset($params['teachers']) ? $params['teachers'] : null;
867
        $status = isset($params['status']) ? $params['status'] : null;
868
869
        $TABLECOURSUSER = Database::get_main_table(TABLE_MAIN_COURSE_USER);
870
        $ok_to_register_course = true;
871
872
        // Check whether all the needed parameters are present.
873
        if (empty($code)) {
874
            $error_msg[] = 'courseSysCode is missing';
875
            $ok_to_register_course = false;
876
        }
877
        if (empty($visual_code)) {
878
            $error_msg[] = 'courseScreenCode is missing';
879
            $ok_to_register_course = false;
880
        }
881
        if (empty($directory)) {
882
            $error_msg[] = 'courseRepository is missing';
883
            $ok_to_register_course = false;
884
        }
885
886
        if (empty($title)) {
887
            $error_msg[] = 'title is missing';
888
            $ok_to_register_course = false;
889
        }
890
891
        if (empty($expiration_date)) {
892
            $expiration_date = api_get_utc_datetime(
893
                time() + self::FIRST_EXPIRATION_DATE
894
            );
895
        } else {
896
            $expiration_date = api_get_utc_datetime($expiration_date);
897
        }
898
899
        if ($visibility < 0 || $visibility > 4) {
900
            $error_msg[] = 'visibility is invalid';
901
            $ok_to_register_course = false;
902
        }
903
904
        if (empty($disk_quota)) {
905
            $disk_quota = api_get_setting('default_document_quotum');
906
        }
907
908
        if (stripos($department_url, 'http://') === false && stripos(
909
                $department_url,
910
                'https://'
911
            ) === false
912
        ) {
913
            $department_url = 'http://'.$department_url;
914
        }
915
916
        // just in case
917
        if ($department_url == 'http://') {
918
            $department_url = '';
919
        }
920
        $course_id = 0;
921
922
        if ($ok_to_register_course) {
923
            $courseManager = Container::$container->get('chamilo_core.entity.manager.course_manager');
924
            /** @var \Chamilo\CoreBundle\Entity\Course $course */
925
            $course = $courseManager->create();
926
927
            // Here we must add 2 fields.
928
            /*$course_id = Database::insert(
929
                $TABLECOURSE,
930
                [
931
                    'code' => $code,
932
                    'directory' => $directory,
933
                    'course_language' => $course_language,
934
                    'title' => $title,
935
                    'description' => get_lang('CourseDescription'),
936
                    'category_code' => $category_code,
937
                    'visibility' => $visibility,
938
                    'show_score' => 1,
939
                    'disk_quota' => intval($disk_quota),
940
                    'creation_date' => $time,
941
                    'expiration_date' => $expiration_date,
942
                    'last_edit' => $time,
943
                    'last_visit' => null,
944
                    'tutor_name' => $tutor_name,
945
                    'department_name' => $department_name,
946
                    'department_url' => $department_url,
947
                    'subscribe' => intval($subscribe),
948
                    'unsubscribe' => intval($unsubscribe),
949
                    'visual_code' => $visual_code,
950
                ]
951
            );*/
952
953
            $urlId = 1;
954
            if (api_get_current_access_url_id() !== -1) {
955
                $urlId = api_get_current_access_url_id();
956
            }
957
958
            $url = api_get_url_entity($urlId);
959
            $course
960
                ->setCode($code)
961
                ->setDirectory($directory)
962
                ->setCourseLanguage($course_language)
963
                ->setTitle($title)
964
                ->setDescription(get_lang('CourseDescription'))
965
                ->setCategoryCode($category_code)
966
                ->setVisibility($visibility)
967
                ->setShowScore(1)
968
                ->setDiskQuota($disk_quota)
969
                ->setCreationDate(new \DateTime())
970
                ->setExpirationDate(new \DateTime($expiration_date))
971
                //->setLastEdit()
972
                ->setDepartmentName($department_name)
973
                ->setDepartmentUrl($department_url)
974
                ->setSubscribe($subscribe)
975
                ->setUnsubscribe($unsubscribe)
976
                ->setVisualCode($visual_code)
977
                ->addUrl($url)
978
            ;
979
980
            $courseManager->save($course, true);
981
            $course_id = $course->getId();
982
983
            if ($course_id) {
984
                $sort = api_max_sort_value('0', api_get_user_id());
985
                // Default true
986
                $addTeacher = isset($params['add_user_as_teacher']) ? $params['add_user_as_teacher'] : true;
987
                if ($addTeacher) {
988
                    $i_course_sort = CourseManager::userCourseSort(
989
                        $user_id,
990
                        $code
991
                    );
992
                    if (!empty($user_id)) {
993
                        $sql = "INSERT INTO ".$TABLECOURSUSER." SET
994
                                c_id     = '".$course_id."',
995
                                user_id         = '".intval($user_id)."',
996
                                status          = '1',
997
                                is_tutor        = '0',
998
                                sort            = '".($i_course_sort)."',
999
                                relation_type = 0,
1000
                                user_course_cat = '0'";
1001
                        Database::query($sql);
1002
                    }
1003
                }
1004
1005
                if (!empty($teachers)) {
1006
                    if (!is_array($teachers)) {
1007
                        $teachers = [$teachers];
1008
                    }
1009
                    foreach ($teachers as $key) {
1010
                        //just in case
1011
                        if ($key == $user_id) {
1012
                            continue;
1013
                        }
1014
                        if (empty($key)) {
1015
                            continue;
1016
                        }
1017
                        $sql = "INSERT INTO ".$TABLECOURSUSER." SET
1018
                            c_id     = '".Database::escape_string($course_id)."',
1019
                            user_id         = '".Database::escape_string($key)."',
1020
                            status          = '1',
1021
                            is_tutor        = '0',
1022
                            sort            = '".($sort + 1)."',
1023
                            relation_type = 0,
1024
                            user_course_cat = '0'";
1025
                        Database::query($sql);
1026
                    }
1027
                }
1028
1029
                // Adding the course to an URL.
1030
                // Already added by when saving the entity
1031
                /*if (api_is_multiple_url_enabled()) {
1032
                    $url_id = 1;
1033
                    if (api_get_current_access_url_id() != -1) {
1034
                        $url_id = api_get_current_access_url_id();
1035
                    }
1036
                    UrlManager::add_course_to_url($course_id, $url_id);
1037
                } else {
1038
                    UrlManager::add_course_to_url($course_id, 1);
1039
                }*/
1040
1041
                // Add event to the system log.
1042
                $user_id = api_get_user_id();
1043
                Event::addEvent(
1044
                    LOG_COURSE_CREATE,
1045
                    LOG_COURSE_CODE,
1046
                    $code,
1047
                    api_get_utc_datetime(),
1048
                    $user_id,
1049
                    $course_id
1050
                );
1051
1052
                $send_mail_to_admin = api_get_setting('send_email_to_admin_when_create_course');
1053
1054
                // @todo Improve code to send to all current portal administrators.
1055
                if ($send_mail_to_admin === 'true') {
1056
                    $siteName = api_get_setting('siteName');
1057
                    $recipient_email = api_get_setting('emailAdministrator');
1058
                    $recipient_name = api_get_person_name(
1059
                        api_get_setting('administratorName'),
1060
                        api_get_setting('administratorSurname')
1061
                    );
1062
                    $iname = api_get_setting('Institution');
1063
                    $subject = get_lang(
1064
                            'NewCourseCreatedIn'
1065
                        ).' '.$siteName.' - '.$iname;
1066
                    $message = get_lang(
1067
                            'Dear'
1068
                        ).' '.$recipient_name.",\n\n".get_lang(
1069
                            'MessageOfNewCourseToAdmin'
1070
                        ).' '.$siteName.' - '.$iname."\n";
1071
                    $message .= get_lang('CourseName').' '.$title."\n";
1072
                    $message .= get_lang(
1073
                            'Category'
1074
                        ).' '.$category_code."\n";
1075
                    $message .= get_lang('Tutor').' '.$tutor_name."\n";
1076
                    $message .= get_lang('Language').' '.$course_language;
1077
1078
                    $userInfo = api_get_user_info($user_id);
1079
1080
                    $additionalParameters = [
1081
                        'smsType' => SmsPlugin::NEW_COURSE_BEEN_CREATED,
1082
                        'userId' => $user_id,
1083
                        'courseName' => $title,
1084
                        'creatorUsername' => $userInfo['username'],
1085
                    ];
1086
1087
                    api_mail_html(
1088
                        $recipient_name,
1089
                        $recipient_email,
1090
                        $subject,
1091
                        $message,
1092
                        $siteName,
1093
                        $recipient_email,
1094
                        null,
1095
                        null,
1096
                        null,
1097
                        $additionalParameters
1098
                    );
1099
                }
1100
            }
1101
        }
1102
1103
        return $course_id;
1104
    }
1105
1106
    /**
1107
     * Generate a new id for c_tool table.
1108
     *
1109
     * @param int $courseId The course id
1110
     *
1111
     * @return int the new id
1112
     */
1113
    public static function generateToolId($courseId)
1114
    {
1115
        $newIdResultData = Database::select(
1116
            'id + 1 AS new_id',
1117
            Database::get_course_table(TABLE_TOOL_LIST),
1118
            [
1119
                'where' => ['c_id = ?' => intval($courseId)],
1120
                'order' => 'id',
1121
                'limit' => 1,
1122
            ],
1123
            'first'
1124
        );
1125
1126
        if ($newIdResultData === false) {
1127
            return 1;
1128
        }
1129
1130
        return $newIdResultData['new_id'] > 0 ? $newIdResultData['new_id'] : 1;
1131
    }
1132
}
1133