Passed
Push — master ( 2ffb1a...5c126f )
by Julito
11:51
created

AddCourse::define_course_keys()   B

Complexity

Conditions 7
Paths 36

Size

Total Lines 59
Code Lines 35

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 35
nc 36
nop 6
dl 0
loc 59
rs 8.4266
c 0
b 0
f 0

How to fix   Long Method   

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