Passed
Push — master ( 41c16d...815f8a )
by Julito
09:55
created

AddCourse::insertDocument()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 9
c 0
b 0
f 0
nc 1
nop 4
dl 0
loc 15
rs 9.9666
1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
use Chamilo\CoreBundle\Entity\Course;
6
use Chamilo\CoreBundle\Entity\CourseRelUser;
7
use Chamilo\CoreBundle\Framework\Container;
8
use Chamilo\CourseBundle\Entity\CGroupCategory;
9
use Chamilo\CourseBundle\Entity\CToolIntro;
10
11
/**
12
 * Class AddCourse.
13
 */
14
class AddCourse
15
{
16
    public const FIRST_EXPIRATION_DATE = 31536000; // 365 days in seconds
17
18
    /**
19
     * Defines the four needed keys to create a course based on several parameters.
20
     *
21
     * @param string    The code you want for this course
22
     * @param string    Prefix added for ALL keys
23
     * @param string    Prefix added for databases only
24
     * @param string    Prefix added for paths only
25
     * @param bool      Add unique prefix
26
     * @param bool      Use code-independent keys
27
     *
28
     * @return array An array with the needed keys ['currentCourseCode'], ['currentCourseId'], ['currentCourseDbName'],
29
     *               ['currentCourseRepository']
30
     *
31
     * @todo Eliminate the global variables.
32
     * @assert (null) === false
33
     */
34
    public static function define_course_keys(
35
        $wanted_code,
36
        $prefix_for_all = '',
37
        $prefix_for_base_name = '',
38
        $prefix_for_path = '',
39
        $add_unique_prefix = false,
40
        $use_code_indepedent_keys = true
41
    ) {
42
        $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
43
        $wanted_code = CourseManager::generate_course_code($wanted_code);
44
        $keys_course_code = $wanted_code;
45
        if (!$use_code_indepedent_keys) {
46
            $wanted_code = '';
47
        }
48
49
        $unique_prefix = '';
50
        if ($add_unique_prefix) {
51
            $unique_prefix = substr(md5(uniqid(rand())), 0, 10);
52
        }
53
54
        $keys = [];
55
        $final_suffix = ['CourseId' => '', 'CourseDb' => '', 'CourseDir' => ''];
56
        $limit_numb_try = 100;
57
        $keys_are_unique = false;
58
        $try_new_fsc_id = $try_new_fsc_db = $try_new_fsc_dir = 0;
59
60
        while (!$keys_are_unique) {
61
            $keys_course_id = $prefix_for_all.$unique_prefix.$wanted_code.$final_suffix['CourseId'];
62
            $keys_course_repository = $prefix_for_path.$unique_prefix.$wanted_code.$final_suffix['CourseDir'];
63
            $keys_are_unique = true;
64
65
            // Check whether they are unique.
66
            $query = "SELECT 1 FROM $course_table
67
                      WHERE code='".$keys_course_id."'
68
                      LIMIT 0, 1";
69
            $result = Database::query($query);
70
71
            if (Database::num_rows($result)) {
72
                $keys_are_unique = false;
73
                $try_new_fsc_id++;
74
                $final_suffix['CourseId'] = substr(md5(uniqid(rand())), 0, 4);
75
            }
76
77
            if (($try_new_fsc_id + $try_new_fsc_db + $try_new_fsc_dir) > $limit_numb_try) {
78
                return $keys;
79
            }
80
        }
81
82
        $keys['currentCourseCode'] = $keys_course_code;
83
        $keys['currentCourseId'] = $keys_course_id;
84
        $keys['currentCourseRepository'] = $keys_course_repository;
85
86
        return $keys;
87
    }
88
89
    /**
90
     * Gets an array with all the course tables (deprecated?).
91
     *
92
     * @return array
93
     *
94
     * @assert (null) !== null
95
     */
96
    public static function get_course_tables()
97
    {
98
        $tables = [];
99
        //$tables[] = 'item_property';
100
        $tables[] = 'tool';
101
        $tables[] = 'tool_intro';
102
        $tables[] = 'group_info';
103
        $tables[] = 'group_category';
104
        $tables[] = 'group_rel_user';
105
        $tables[] = 'group_rel_tutor';
106
        $tables[] = 'userinfo_content';
107
        $tables[] = 'userinfo_def';
108
        $tables[] = 'course_description';
109
        $tables[] = 'calendar_event';
110
        $tables[] = 'calendar_event_repeat';
111
        $tables[] = 'calendar_event_repeat_not';
112
        $tables[] = 'calendar_event_attachment';
113
        $tables[] = 'announcement';
114
        $tables[] = 'announcement_attachment';
115
        //$tables[] = 'resource';
116
        $tables[] = 'student_publication';
117
        $tables[] = 'student_publication_assignment';
118
        $tables[] = 'document';
119
        /*$tables[] = 'forum_category';
120
        $tables[] = 'forum_forum';
121
        $tables[] = 'forum_thread';
122
        $tables[] = 'forum_post';
123
        $tables[] = 'forum_mailcue';
124
        $tables[] = 'forum_attachment';
125
        $tables[] = 'forum_notification';
126
        $tables[] = 'forum_thread_qualify';
127
        $tables[] = 'forum_thread_qualify_log';*/
128
        $tables[] = 'link';
129
        $tables[] = 'link_category';
130
        $tables[] = 'online_connected';
131
        $tables[] = 'online_link';
132
        $tables[] = 'chat_connected';
133
        $tables[] = 'quiz';
134
        $tables[] = 'quiz_rel_question';
135
        $tables[] = 'quiz_question';
136
        $tables[] = 'quiz_answer';
137
        $tables[] = 'quiz_question_option';
138
        $tables[] = 'quiz_question_category';
139
        $tables[] = 'quiz_question_rel_category';
140
        $tables[] = 'dropbox_post';
141
        $tables[] = 'dropbox_file';
142
        $tables[] = 'dropbox_person';
143
        $tables[] = 'dropbox_category';
144
        $tables[] = 'dropbox_feedback';
145
        $tables[] = 'lp';
146
        $tables[] = 'lp_item';
147
        $tables[] = 'lp_view';
148
        $tables[] = 'lp_item_view';
149
        $tables[] = 'lp_iv_interaction';
150
        $tables[] = 'lp_iv_objective';
151
        $tables[] = 'blog';
152
        $tables[] = 'blog_comment';
153
        $tables[] = 'blog_post';
154
        $tables[] = 'blog_rating';
155
        $tables[] = 'blog_rel_user';
156
        $tables[] = 'blog_task';
157
        $tables[] = 'blog_task_rel_user';
158
        $tables[] = 'blog_attachment';
159
        $tables[] = 'permission_group';
160
        $tables[] = 'permission_user';
161
        $tables[] = 'permission_task';
162
        $tables[] = 'role';
163
        $tables[] = 'role_group';
164
        $tables[] = 'role_permissions';
165
        $tables[] = 'role_user';
166
        $tables[] = 'survey';
167
        $tables[] = 'survey_question';
168
        $tables[] = 'survey_question_option';
169
        $tables[] = 'survey_invitation';
170
        $tables[] = 'survey_answer';
171
        $tables[] = 'survey_group';
172
        $tables[] = 'wiki';
173
        $tables[] = 'wiki_conf';
174
        $tables[] = 'wiki_discuss';
175
        $tables[] = 'wiki_mailcue';
176
        $tables[] = 'course_setting';
177
        $tables[] = 'glossary';
178
        $tables[] = 'notebook';
179
        $tables[] = 'attendance';
180
        $tables[] = 'attendance_sheet';
181
        $tables[] = 'attendance_calendar';
182
        $tables[] = 'attendance_result';
183
        $tables[] = 'attendance_sheet_log';
184
        $tables[] = 'thematic';
185
        $tables[] = 'thematic_plan';
186
        $tables[] = 'thematic_advance';
187
188
        return $tables;
189
    }
190
191
    /**
192
     * Executed only before create_course_tables().
193
     *
194
     * @assert (null) === null
195
     */
196
    public static function drop_course_tables()
197
    {
198
        $list = self::get_course_tables();
199
        foreach ($list as $table) {
200
            $sql = "DROP TABLE IF EXISTS ".DB_COURSE_PREFIX.$table;
201
            Database::query($sql);
202
        }
203
    }
204
205
    /**
206
     * Sorts pictures by type (used?).
207
     *
208
     * @param array List of files (sthg like array(0=>array('png'=>1)))
209
     * @param string $type
210
     *
211
     * @return array The received array without files not matching type
212
     * @assert (array(),null) === array()
213
     */
214
    public static function sort_pictures($files, $type)
215
    {
216
        $pictures = [];
217
        foreach ($files as $value) {
218
            if (isset($value[$type]) && '' != $value[$type]) {
219
                $pictures[][$type] = $value[$type];
220
            }
221
        }
222
223
        return $pictures;
224
    }
225
226
    /**
227
     * Fills the course database with some required content and example content.
228
     *
229
     * @param array $courseInfo
230
     * @param bool Whether to fill the course with example content
231
     * @param int $authorId
232
     *
233
     * @return bool False on error, true otherwise
234
     *
235
     * @version 1.2
236
     * @assert (null, '', '', null) === false
237
     * @assert (1, 'ABC', null, null) === false
238
     * @assert (1, 'TEST', 'spanish', true) === true
239
     */
240
    public static function fillCourse(
241
        $courseInfo,
242
        $fill_with_exemplary_content = null,
243
        $authorId = 0
244
    ) {
245
        if (is_null($fill_with_exemplary_content)) {
246
            $fill_with_exemplary_content = 'false' !== api_get_setting('example_material_course_creation');
247
        }
248
249
        $course_id = (int) $courseInfo['real_id'];
250
251
        if (empty($courseInfo)) {
252
            return false;
253
        }
254
        $authorId = empty($authorId) ? api_get_user_id() : (int) $authorId;
255
256
        $TABLEGROUPCATEGORIES = Database::get_course_table(TABLE_GROUP_CATEGORY);
257
        $TABLESETTING = Database::get_course_table(TABLE_COURSE_SETTING);
258
        $TABLEGRADEBOOK = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
259
        $TABLEGRADEBOOKLINK = Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
260
        $course = api_get_course_entity($course_id);
261
        $settingsManager = Container::getCourseSettingsManager();
262
        $settingsManager->setCourse($course);
263
264
        $alert = api_get_setting('email_alert_manager_on_new_quiz');
265
        $defaultEmailExerciseAlert = 0;
266
        if ('true' === $alert) {
267
            $defaultEmailExerciseAlert = 1;
268
        }
269
270
        /* course_setting table (courseinfo tool)   */
271
        $settings = [
272
            'email_alert_manager_on_new_doc' => ['title' => '', 'default' => 0, 'category' => 'work'],
273
            'email_alert_on_new_doc_dropbox' => ['default' => 0, 'category' => 'dropbox'],
274
            'allow_user_edit_agenda' => ['default' => 0, 'category' => 'agenda'],
275
            'allow_user_edit_announcement' => ['default' => 0, 'category' => 'announcement'],
276
            'email_alert_manager_on_new_quiz' => ['default' => $defaultEmailExerciseAlert, 'category' => 'quiz'],
277
            'allow_user_image_forum' => ['default' => 1, 'category' => 'forum'],
278
            'course_theme' => ['default' => '', 'category' => 'theme'],
279
            'allow_learning_path_theme' => ['default' => 1, 'category' => 'theme'],
280
            'allow_open_chat_window' => ['default' => 1, 'category' => 'chat'],
281
            'email_alert_to_teacher_on_new_user_in_course' => ['default' => 0, 'category' => 'registration'],
282
            'allow_user_view_user_list' => ['default' => 1, 'category' => 'user'],
283
            'display_info_advance_inside_homecourse' => ['default' => 1, 'category' => 'thematic_advance'],
284
            'email_alert_students_on_new_homework' => ['default' => 0, 'category' => 'work'],
285
            'enable_lp_auto_launch' => ['default' => 0, 'category' => 'learning_path'],
286
            'enable_exercise_auto_launch' => ['default' => 0, 'category' => 'exercise'],
287
            'enable_document_auto_launch' => ['default' => 0, 'category' => 'document'],
288
            'pdf_export_watermark_text' => ['default' => '', 'category' => 'learning_path'],
289
            'allow_public_certificates' => [
290
                'default' => 'true' === api_get_setting('allow_public_certificates') ? 1 : '',
291
                'category' => 'certificates',
292
            ],
293
            'documents_default_visibility' => ['default' => 'visible', 'category' => 'document'],
294
            'show_course_in_user_language' => ['default' => 2, 'category' => null],
295
            'email_to_teachers_on_new_work_feedback' => ['default' => 1, 'category' => null],
296
        ];
297
298
        $counter = 1;
299
        foreach ($settings as $variable => $setting) {
300
            $title = $setting['title'] ?? '';
301
            Database::query(
302
                "INSERT INTO $TABLESETTING (c_id, title, variable, value, category)
303
                      VALUES ($course_id, '".$title."', '".$variable."', '".$setting['default']."', '".$setting['category']."')"
304
            );
305
            $counter++;
306
        }
307
308
        /* Course homepage tools for platform admin only */
309
        /* Group tool */
310
        $groupCategory = new CGroupCategory();
311
        $groupCategory
312
            ->setTitle(get_lang('Default groups'))
313
            ->setParent($course)
314
            ->addCourseLink($course)
315
        ;
316
        Database::getManager()->persist($groupCategory);
317
318
        $now = api_get_utc_datetime();
319
        /*$files = [
320
            ['path' => '/shared_folder', 'title' => get_lang('Folders of users'), 'filetype' => 'folder', 'size' => 0],
321
            [
322
                'path' => '/chat_files',
323
                'title' => get_lang('Chat conversations history'),
324
                'filetype' => 'folder',
325
                'size' => 0,
326
            ],
327
            ['path' => '/certificates', 'title' => get_lang('Certificates'), 'filetype' => 'folder', 'size' => 0],
328
        ];
329
330
        $counter = 1;
331
        foreach ($files as $file) {
332
            self::insertDocument($courseInfo, $counter, $file, $authorId);
333
            $counter++;
334
        }*/
335
336
        $certificateId = 'NULL';
337
        /*    Documents   */
338
        if ($fill_with_exemplary_content) {
339
            $files = [
340
                ['path' => '/audio', 'title' => get_lang('Audio'), 'filetype' => 'folder', 'size' => 0],
341
                //['path' => '/flash', 'title' => get_lang('Flash'), 'filetype' => 'folder', 'size' => 0],
342
                ['path' => '/images', 'title' => get_lang('Images'), 'filetype' => 'folder', 'size' => 0],
343
                ['path' => '/images/gallery', 'title' => get_lang('Gallery'), 'filetype' => 'folder', 'size' => 0],
344
                ['path' => '/video', 'title' => get_lang('Video'), 'filetype' => 'folder', 'size' => 0],
345
                //['path' => '/video/flv', 'title' => 'flv', 'filetype' => 'folder', 'size' => 0],
346
            ];
347
            $paths = [];
348
            foreach ($files as $file) {
349
                $doc = self::insertDocument($courseInfo, $counter, $file, $authorId);
350
                $paths[$file['path']] = $doc->getIid();
351
                $counter++;
352
            }
353
354
            $finder = new Symfony\Component\Finder\Finder();
355
            $defaultPath = api_get_path(SYS_PUBLIC_PATH).'img/document';
356
            $finder->in($defaultPath);
357
358
            /** @var SplFileInfo $file */
359
            foreach ($finder as $file) {
360
                $parentName = dirname(str_replace($defaultPath, '', $file->getRealPath()));
361
                if ('/' === $parentName || '/certificates' === $parentName) {
362
                    continue;
363
                }
364
365
                $title = $file->getFilename();
366
                $parentId = $paths[$parentName];
367
368
                if ($file->isDir()) {
369
                    $realPath = str_replace($defaultPath, '', $file->getRealPath());
370
                    $document = DocumentManager::addDocument(
371
                        $courseInfo,
372
                        $realPath,
373
                        'folder',
374
                        null,
375
                        $title,
376
                        '',
377
                        null,
378
                        null,
379
                        null,
380
                        null,
381
                        null,
382
                        false,
383
                        null,
384
                        $parentId,
385
                        $file->getRealPath()
386
                    );
387
                    $paths[$realPath] = $document->getIid();
388
                } else {
389
                    $realPath = str_replace($defaultPath, '', $file->getRealPath());
390
                    $document = DocumentManager::addDocument(
391
                        $courseInfo,
392
                        $realPath,
393
                        'file',
394
                        $file->getSize(),
395
                        $title,
396
                        '',
397
                        null,
398
                        null,
399
                        null,
400
                        null,
401
                        null,
402
                        false,
403
                        null,
404
                        $parentId,
405
                        $file->getRealPath()
406
                    );
407
408
                    if ($document && 'default.html' === $document->getTitle()) {
409
                        $certificateId = $document->getIid();
410
                    }
411
                }
412
            }
413
414
            $agenda = new Agenda('course');
415
            $agenda->set_course($courseInfo);
416
            $agenda->addEvent(
417
                $now,
418
                $now,
419
                0,
420
                get_lang('Course creation'),
421
                get_lang('This course was created at this time')
422
            );
423
424
            /*  Links tool */
425
            $link = new Link();
426
            $link->setCourse($courseInfo);
427
            $links = [
428
                [
429
                    'c_id' => $course_id,
430
                    'url' => 'http://www.google.com',
431
                    'title' => 'Quick and powerful search engine',
432
                    'description' => get_lang('Quick and powerful search engine'),
433
                    'category_id' => 0,
434
                    'on_homepage' => 0,
435
                    'target' => '_self',
436
                    'session_id' => 0,
437
                ],
438
                [
439
                    'c_id' => $course_id,
440
                    'url' => 'http://www.wikipedia.org',
441
                    'title' => 'Free online encyclopedia',
442
                    'description' => get_lang('Free online encyclopedia'),
443
                    'category_id' => 0,
444
                    'on_homepage' => 0,
445
                    'target' => '_self',
446
                    'session_id' => 0,
447
                ],
448
            ];
449
450
            foreach ($links as $params) {
451
                $link->save($params, false, false);
452
            }
453
454
            /* Announcement tool */
455
            AnnouncementManager::add_announcement(
456
                $courseInfo,
457
                0,
458
                get_lang('This is an announcement example'),
459
                get_lang('This is an announcement example. Only trainers are allowed to publish announcements.'),
460
                ['everyone' => 'everyone'],
461
                null,
462
                null,
463
                $now
464
            );
465
466
            $manager = Database::getManager();
467
468
            /* Introduction text */
469
            $intro_text = '<p style="text-align: center;">
470
                            <img src="'.api_get_path(REL_CODE_PATH).'img/mascot.png" alt="Mr. Chamilo" title="Mr. Chamilo" />
471
                            <h2>'.get_lang('Introduction text').'</h2>
472
                         </p>';
473
474
            $toolIntro = new CToolIntro();
475
            $toolIntro
476
                ->setCId($course_id)
477
                ->setSessionId(0)
478
                ->setIntroText($intro_text);
479
            $manager->persist($toolIntro);
480
481
            $toolIntro = new CToolIntro();
482
            $toolIntro
483
                ->setCId($course_id)
484
                ->setSessionId(0)
485
                ->setIntroText(get_lang('This page allows users and groups to publish documents.'));
486
            $manager->persist($toolIntro);
487
488
            $toolIntro = new CToolIntro();
489
            $toolIntro
490
                ->setCId($course_id)
491
                ->setSessionId(0)
492
                ->setIntroText(get_lang('The word Wiki is short for WikiWikiWeb. Wikiwiki is a Hawaiian word, meaning "fast" or "speed". In a wiki, people write pages together. If one person writes something wrong, the next person can correct it. The next person can also add something new to the page. Because of this, the pages improve continuously.'));
493
            $manager->persist($toolIntro);
494
495
            $manager->flush();
496
497
            /*  Exercise tool */
498
            $exercise = new Exercise($course_id);
499
            $exercise->exercise = get_lang('Sample test');
500
            $html = '<table width="100%" border="0" cellpadding="0" cellspacing="0">
501
                        <tr>
502
                        <td width="220" valign="top" align="left">
503
                            <img src="'.api_get_path(WEB_PUBLIC_PATH).'img/document/images/mr_chamilo/doubts.png">
504
                        </td>
505
                        <td valign="top" align="left">'.get_lang('Irony').'</td></tr>
506
                    </table>';
507
            $exercise->type = 1;
508
            $exercise->setRandom(0);
509
            $exercise->active = 1;
510
            $exercise->results_disabled = 0;
511
            $exercise->description = $html;
512
            $exercise->save();
513
514
            $exercise_id = $exercise->id;
515
516
            $question = new MultipleAnswer();
517
            $question->course = $courseInfo;
518
            $question->question = get_lang('Socratic irony is...');
519
            $question->description = get_lang('(more than one answer can be true)');
520
            $question->weighting = 10;
521
            $question->position = 1;
522
            $question->course = $courseInfo;
523
            $question->save($exercise);
524
            $questionId = $question->id;
525
526
            $answer = new Answer($questionId, $courseInfo['real_id']);
527
            $answer->createAnswer(get_lang('Ridiculise one\'s interlocutor in order to have him concede he is wrong.'), 0, get_lang('No. Socratic irony is not a matter of psychology, it concerns argumentation.'), -5, 1);
528
            $answer->createAnswer(get_lang('Admit one\'s own errors to invite one\'s interlocutor to do the same.'), 0, get_lang('No. Socratic irony is not a seduction strategy or a method based on the example.'), -5, 2);
529
            $answer->createAnswer(get_lang('Compell one\'s interlocutor, by a series of questions and sub-questions, to admit he doesn\'t know what he claims to know.'), 1, get_lang('Indeed'), 5, 3);
530
            $answer->createAnswer(get_lang('Use the Principle of Non Contradiction to force one\'s interlocutor into a dead end.'), 1, get_lang('This answer is not false. It is true that the revelation of the interlocutor\'s ignorance means showing the contradictory conclusions where lead his premisses.'), 5, 4);
531
            $answer->save();
532
            // Forums.
533
            $params = [
534
                'forum_category_title' => get_lang('Example Forum Category'),
535
                'forum_category_comment' => '',
536
            ];
537
538
            $forumCategoryId = store_forumcategory($params, $courseInfo, false);
539
540
            $params = [
541
                'forum_category' => $forumCategoryId,
542
                'forum_title' => get_lang('Example Forum'),
543
                'forum_comment' => '',
544
                'default_view_type_group' => ['default_view_type' => 'flat'],
545
            ];
546
547
            $forumId = store_forum($params, $courseInfo, true);
548
            $repo = Container::getForumRepository();
549
            $forumEntity = $repo->find($forumId);
550
551
            $params = [
552
                'post_title' => get_lang('Example Thread'),
553
                'forum_id' => $forumId,
554
                'post_text' => get_lang('Example ThreadContent'),
555
                'calification_notebook_title' => '',
556
                'numeric_calification' => '',
557
                'weight_calification' => '',
558
                'forum_category' => $forumCategoryId,
559
                'thread_peer_qualify' => 0,
560
            ];
561
562
            saveThread($forumEntity, $params, $courseInfo, false);
563
564
            /* Gradebook tool */
565
            $course_code = $courseInfo['code'];
566
            // father gradebook
567
            Database::query(
568
                "INSERT INTO $TABLEGRADEBOOK (name, locked, generate_certificates, description, user_id, c_id, parent_id, weight, visible, certif_min_score, session_id, document_id)
569
                VALUES ('$course_code','0',0,'',1,$course_id,0,100,0,75,NULL,$certificateId)"
570
            );
571
            $gbid = Database::insert_id();
572
            Database::query(
573
                "INSERT INTO $TABLEGRADEBOOK (name, locked, generate_certificates, description, user_id, c_id, parent_id, weight, visible, certif_min_score, session_id, document_id)
574
                VALUES ('$course_code','0',0,'',1,$course_id,$gbid,100,1,75,NULL,$certificateId)"
575
            );
576
            $gbid = Database:: insert_id();
577
            Database::query(
578
                "INSERT INTO $TABLEGRADEBOOKLINK (type, ref_id, user_id, c_id, category_id, created_at, weight, visible, locked)
579
                VALUES (1,$exercise_id,1,$course_id,$gbid,'$now',100,1,0)"
580
            );
581
        }
582
583
        // Installing plugins in course
584
        $app_plugin = new AppPlugin();
585
        $app_plugin->install_course_plugins($course_id);
586
587
        return true;
588
    }
589
590
    /**
591
     * @param array $courseInfo
592
     * @param int   $counter
593
     * @param array $file
594
     * @param int   $authorId
595
     */
596
    public static function insertDocument($courseInfo, $counter, $file, $authorId = 0)
597
    {
598
        return DocumentManager::addDocument(
599
            $courseInfo,
600
            $file['path'],
601
            $file['filetype'],
602
            $file['size'],
603
            $file['title'],
604
            null,
605
            0,
606
            null,
607
            0,
608
            0,
609
            0,
610
            false
611
        );
612
    }
613
614
    /**
615
     * string2binary converts the string "true" or "false" to the boolean true false (0 or 1)
616
     * This is used for the Chamilo Config Settings as these store true or false as string
617
     * and the api_get_setting('course_create_active_tools') should be 0 or 1 (used for
618
     * the visibility of the tool).
619
     *
620
     * @param string $variable
621
     *
622
     * @return bool
623
     *
624
     * @author Patrick Cool, [email protected]
625
     * @assert ('true') === true
626
     * @assert ('false') === false
627
     */
628
    public static function string2binary($variable)
629
    {
630
        if ('true' == $variable) {
631
            return true;
632
        }
633
        if ('false' == $variable) {
634
            return false;
635
        }
636
    }
637
638
    /**
639
     * Function register_course to create a record in the course table of the main database.
640
     *
641
     * @param array $params      Course details (see code for details).
642
     * @param int   $accessUrlId Optional.
643
     *
644
     * @return int Created course ID
645
     *
646
     * @todo use an array called $params instead of lots of params
647
     * @assert (null) === false
648
     */
649
    public static function register_course($params, $accessUrlId = 1)
650
    {
651
        global $error_msg;
652
        $title = $params['title'];
653
        // Fix amp
654
        $title = str_replace('&amp;', '&', $title);
655
        $code = $params['code'];
656
        $visual_code = $params['visual_code'];
657
        $directory = $params['directory'];
658
        $tutor_name = isset($params['tutor_name']) ? $params['tutor_name'] : null;
659
        $course_language = isset($params['course_language']) && !empty($params['course_language']) ? $params['course_language'] : api_get_setting(
660
            'platformLanguage'
661
        );
662
        $department_name = isset($params['department_name']) ? $params['department_name'] : null;
663
        $department_url = isset($params['department_url']) ? $params['department_url'] : null;
664
        $disk_quota = isset($params['disk_quota']) ? $params['disk_quota'] : null;
665
666
        if (!isset($params['visibility'])) {
667
            $default_course_visibility = api_get_setting('courses_default_creation_visibility');
668
            if (isset($default_course_visibility)) {
669
                $visibility = $default_course_visibility;
670
            } else {
671
                $visibility = COURSE_VISIBILITY_OPEN_PLATFORM;
672
            }
673
        } else {
674
            $visibility = $params['visibility'];
675
        }
676
677
        $subscribe = false;
678
        if (isset($params['subscribe'])) {
679
            $subscribe = 1 === (int) $params['subscribe'];
680
        } else {
681
            if (COURSE_VISIBILITY_OPEN_PLATFORM == $visibility) {
682
                $subscribe = true;
683
            }
684
        }
685
686
        //$subscribe = isset($params['subscribe']) ? (int) $params['subscribe'] : COURSE_VISIBILITY_OPEN_PLATFORM == $visibility ? 1 : 0;
687
        $unsubscribe = isset($params['unsubscribe']) ? (int) $params['unsubscribe'] : 0;
688
        $expiration_date = isset($params['expiration_date']) ? $params['expiration_date'] : null;
689
        $teachers = isset($params['teachers']) ? $params['teachers'] : null;
690
        $categories = isset($params['course_categories']) ? $params['course_categories'] : null;
691
        $ok_to_register_course = true;
692
693
        // Check whether all the needed parameters are present.
694
        if (empty($code)) {
695
            $error_msg[] = 'courseSysCode is missing';
696
            $ok_to_register_course = false;
697
        }
698
        if (empty($visual_code)) {
699
            $error_msg[] = 'courseScreenCode is missing';
700
            $ok_to_register_course = false;
701
        }
702
        if (empty($directory)) {
703
            $error_msg[] = 'courseRepository is missing';
704
            $ok_to_register_course = false;
705
        }
706
707
        if (empty($title)) {
708
            $error_msg[] = 'title is missing';
709
            $ok_to_register_course = false;
710
        }
711
712
        if (empty($expiration_date)) {
713
            $expiration_date = api_get_utc_datetime(
714
                time() + self::FIRST_EXPIRATION_DATE
715
            );
716
        } else {
717
            $expiration_date = api_get_utc_datetime($expiration_date);
718
        }
719
720
        if ($visibility < 0 || $visibility > 4) {
721
            $error_msg[] = 'visibility is invalid';
722
            $ok_to_register_course = false;
723
        }
724
725
        if (empty($disk_quota)) {
726
            $disk_quota = api_get_setting('default_document_quotum');
727
        }
728
729
        if (false === stripos($department_url, 'http://') && false === stripos(
730
                $department_url,
731
                'https://'
732
            )
733
        ) {
734
            $department_url = 'http://'.$department_url;
735
        }
736
737
        // just in case
738
        if ('http://' === $department_url) {
739
            $department_url = '';
740
        }
741
        $course_id = 0;
742
743
        $userId = empty($params['user_id']) ? api_get_user_id() : (int) $params['user_id'];
744
        $user = api_get_user_entity($userId);
745
        if (null === $user) {
746
            error_log(sprintf('user_id "%s" is invalid', $userId));
747
748
            return 0;
749
        }
750
751
        $em = Database::getManager();
752
        if ($ok_to_register_course) {
753
            $repo = Container::getCourseRepository();
754
            $categoryRepo = Container::getCourseCategoryRepository();
755
756
            $course = new Course();
757
            $course
758
                ->setCode($code)
759
                ->setCourseLanguage($course_language)
760
                ->setTitle($title)
761
                ->setDescription(get_lang('Course Description'))
762
                ->setVisibility($visibility)
763
                ->setShowScore(1)
764
                ->setDiskQuota($disk_quota)
765
                ->setExpirationDate(new \DateTime($expiration_date))
766
                ->setDepartmentName($department_name)
767
                ->setDepartmentUrl($department_url)
768
                ->setSubscribe($subscribe)
769
                ->setUnsubscribe($unsubscribe)
770
                ->setVisualCode($visual_code)
771
            ;
772
773
            if (!empty($categories)) {
774
                if (!is_array($categories)) {
775
                    $categories = [$categories];
776
                }
777
778
                foreach ($categories as $key) {
779
                    if (empty($key)) {
780
                        continue;
781
                    }
782
783
                    $category = $categoryRepo->find($key);
784
                    $course->addCategory($category);
785
                }
786
            }
787
788
            $repo->create($course);
789
790
            $course_id = $course->getId();
791
            if ($course_id) {
792
                $sort = api_max_sort_value('0', api_get_user_id());
793
                // Default true
794
                $addTeacher = isset($params['add_user_as_teacher']) ? $params['add_user_as_teacher'] : true;
795
                if ($addTeacher) {
796
                    $iCourseSort = CourseManager::userCourseSort($userId, $code);
797
                    $courseRelTutor = (new CourseRelUser())
798
                        ->setCourse($course)
799
                        ->setUser($user)
800
                        ->setStatus(true)
801
                        ->setTutor(true)
802
                        ->setSort($iCourseSort)
803
                        ->setRelationType(0)
804
                        ->setUserCourseCat(0)
805
                    ;
806
                    $em->persist($courseRelTutor);
807
                }
808
809
                if (!empty($teachers)) {
810
                    $sort = $user->getMaxSortValue();
811
                    if (!is_array($teachers)) {
812
                        $teachers = [$teachers];
813
                    }
814
                    foreach ($teachers as $key) {
815
                        // Just in case.
816
                        if ($key == $userId) {
817
                            continue;
818
                        }
819
                        if (empty($key)) {
820
                            continue;
821
                        }
822
                        $teacher = api_get_user_entity($key);
823
                        if (is_null($teacher)) {
824
                            continue;
825
                        }
826
                        $courseRelTeacher = (new CourseRelUser())
827
                            ->setCourse($course)
828
                            ->setUser($teacher)
829
                            ->setStatus(true)
830
                            ->setTutor(false)
831
                            ->setSort($sort + 1)
832
                            ->setRelationType(0)
833
                            ->setUserCourseCat(0)
834
                        ;
835
                        $em->persist($courseRelTeacher);
836
                    }
837
                }
838
839
                $em->flush();
840
841
                // Adding the course to an URL.
842
                //UrlManager::add_course_to_url($course_id, $accessUrlId);
843
844
                // Add event to the system log.
845
                Event::addEvent(
846
                    LOG_COURSE_CREATE,
847
                    LOG_COURSE_CODE,
848
                    $code,
849
                    api_get_utc_datetime(),
850
                    $userId,
851
                    $course_id
852
                );
853
854
                $send_mail_to_admin = api_get_setting('send_email_to_admin_when_create_course');
855
856
                // @todo Improve code to send to all current portal administrators.
857
                if ('true' === $send_mail_to_admin) {
858
                    $siteName = api_get_setting('siteName');
859
                    $recipient_email = api_get_setting('emailAdministrator');
860
                    $recipient_name = api_get_person_name(
861
                        api_get_setting('administratorName'),
862
                        api_get_setting('administratorSurname')
863
                    );
864
                    $iname = api_get_setting('Institution');
865
                    $subject = get_lang(
866
                            'NewCourseCreatedIn'
867
                        ).' '.$siteName.' - '.$iname;
868
                    $message = get_lang(
869
                            'Dear'
870
                        ).' '.$recipient_name.",\n\n".get_lang(
871
                            'MessageOfNewCourseToAdmin'
872
                        ).' '.$siteName.' - '.$iname."\n";
873
                    $message .= get_lang('Course name').' '.$title."\n";
874
875
                    if ($course->getCategories()->count() > 0) {
876
                        foreach ($course->getCategories() as $category) {
877
                            $message .= get_lang('Category').': '.$category->getCode()."\n";
878
                        }
879
                    }
880
                    $message .= get_lang('Coach').' '.$tutor_name."\n";
881
                    $message .= get_lang('Language').' '.$course_language;
882
883
                    $additionalParameters = [
884
                        'smsType' => SmsPlugin::NEW_COURSE_BEEN_CREATED,
885
                        'userId' => $userId,
886
                        'courseName' => $title,
887
                        'creatorUsername' => $user->getUsername(),
888
                    ];
889
890
                    api_mail_html(
891
                        $recipient_name,
892
                        $recipient_email,
893
                        $subject,
894
                        $message,
895
                        $siteName,
896
                        $recipient_email,
897
                        null,
898
                        null,
899
                        null,
900
                        $additionalParameters
901
                    );
902
                }
903
            }
904
        }
905
906
        return $course_id;
907
    }
908
909
    /**
910
     * Generate a new id for c_tool table.
911
     *
912
     * @param int $courseId The course id
913
     *
914
     * @return int the new id
915
     */
916
    public static function generateToolId($courseId)
917
    {
918
        $newIdResultData = Database::select(
919
            'id + 1 AS new_id',
920
            Database::get_course_table(TABLE_TOOL_LIST),
921
            [
922
                'where' => ['c_id = ?' => intval($courseId)],
923
                'order' => 'id',
924
                'limit' => 1,
925
            ],
926
            'first'
927
        );
928
929
        if (false === $newIdResultData) {
930
            return 1;
931
        }
932
933
        return $newIdResultData['new_id'] > 0 ? $newIdResultData['new_id'] : 1;
934
    }
935
}
936