Passed
Push — master ( 26ffea...1a7924 )
by Julito
09:14
created

Certificate::check_certificate_path()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 17
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 11
c 0
b 0
f 0
nc 5
nop 0
dl 0
loc 17
rs 9.6111
1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
use Chamilo\CoreBundle\Framework\Container;
6
use Endroid\QrCode\ErrorCorrectionLevel;
7
use Endroid\QrCode\QrCode;
8
9
/**
10
 * Certificate Class
11
 * Generate certificates based in the gradebook tool.
12
 */
13
class Certificate extends Model
14
{
15
    public $table;
16
    public $columns = [
17
        'id',
18
        'cat_id',
19
        'score_certificate',
20
        'created_at',
21
        'path_certificate',
22
    ];
23
    /**
24
     * Certification data.
25
     */
26
    public $certificate_data = [];
27
28
    /**
29
     * Student's certification path.
30
     */
31
    public $certification_user_path = null;
32
    public $certification_web_user_path = null;
33
    public $html_file = null;
34
    public $qr_file = null;
35
    public $user_id;
36
37
    /** If true every time we enter to the certificate URL
38
     * we would generate a new certificate (good thing because we can edit the
39
     * certificate and all users will have the latest certificate bad because we.
40
     * load the certificate every time */
41
    public $force_certificate_generation = true;
42
43
    /**
44
     * Constructor.
45
     *
46
     * @param int  $certificate_id        ID of the certificate
47
     * @param int  $userId
48
     * @param bool $sendNotification      send message to student
49
     * @param bool $updateCertificateData
50
     *
51
     * If no ID given, take user_id and try to generate one
52
     */
53
    public function __construct(
54
        $certificate_id = 0,
55
        $userId = 0,
56
        $sendNotification = false,
57
        $updateCertificateData = true
58
    ) {
59
        $this->table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
60
        $this->user_id = !empty($userId) ? $userId : api_get_user_id();
61
62
        if (!empty($certificate_id)) {
63
            $certificate = $this->get($certificate_id);
64
            if (!empty($certificate) && is_array($certificate)) {
65
                $this->certificate_data = $certificate;
66
                $this->user_id = $this->certificate_data['user_id'];
67
            }
68
        }
69
70
        if ($this->user_id) {
71
            // To force certification generation
72
            if ($this->force_certificate_generation) {
73
                $this->generate([], $sendNotification);
74
            }
75
            if (isset($this->certificate_data) && $this->certificate_data) {
76
                if (empty($this->certificate_data['path_certificate'])) {
77
                    $this->generate([], $sendNotification);
78
                }
79
            }
80
        }
81
82
        // Setting the qr and html variables
83
        if (isset($certificate_id) &&
84
            !empty($this->certification_user_path) &&
85
            isset($this->certificate_data['path_certificate'])
86
        ) {
87
            $pathinfo = pathinfo($this->certificate_data['path_certificate']);
88
            $this->html_file = $this->certification_user_path.basename($this->certificate_data['path_certificate']);
89
            $this->qr_file = $this->certification_user_path.$pathinfo['filename'].'_qr.png';
90
        } else {
91
            if (api_get_configuration_value('allow_general_certificate')) {
92
                // General certificate
93
                $name = md5($this->user_id).'.html';
94
                $my_path_certificate = $this->certification_user_path.$name;
95
                $path_certificate = '/'.$name;
96
97
                // Getting QR filename
98
                $file_info = pathinfo($path_certificate);
99
                $content = $this->generateCustomCertificate();
100
101
                $my_new_content_html = str_replace(
102
                    '((certificate_barcode))',
103
                    Display::img(
104
                        $this->certification_web_user_path.$file_info['filename'].'_qr.png',
105
                        'QR'
106
                    ),
107
                    $content
108
                );
109
110
                $my_new_content_html = mb_convert_encoding(
111
                    $my_new_content_html,
112
                    'UTF-8',
113
                    api_get_system_encoding()
114
                );
115
116
                $this->html_file = $my_path_certificate;
117
                $result = @file_put_contents($my_path_certificate, $my_new_content_html);
118
119
                if ($result) {
120
                    // Updating the path
121
                    self::updateUserCertificateInfo(
122
                        0,
123
                        $this->user_id,
124
                        $path_certificate,
125
                        $updateCertificateData
126
                    );
127
                    $this->certificate_data['path_certificate'] = $path_certificate;
128
                }
129
            }
130
        }
131
    }
132
133
    /**
134
     * Deletes the current certificate object. This is generally triggered by
135
     * the teacher from the gradebook tool to re-generate the certificate because
136
     * the original version wa flawed.
137
     *
138
     * @param bool $force_delete
139
     *
140
     * @return bool
141
     */
142
    public function delete($force_delete = false)
143
    {
144
        $delete_db = false;
145
        if (!empty($this->certificate_data)) {
146
            if (!is_null($this->html_file) || '' != $this->html_file || strlen($this->html_file)) {
147
                // Deleting HTML file
148
                if (is_file($this->html_file)) {
149
                    @unlink($this->html_file);
150
                    if (false === is_file($this->html_file)) {
151
                        $delete_db = true;
152
                    } else {
153
                        $delete_db = false;
154
                    }
155
                }
156
                // Deleting QR code PNG image file
157
                if (is_file($this->qr_file)) {
158
                    @unlink($this->qr_file);
159
                }
160
                if ($delete_db || $force_delete) {
161
                    return parent::delete($this->certificate_data['id']);
162
                }
163
            } else {
164
                return parent::delete($this->certificate_data['id']);
165
            }
166
        }
167
168
        return false;
169
    }
170
171
    /**
172
     *  Generates an HTML Certificate and fills the path_certificate field in the DB.
173
     *
174
     * @param array $params
175
     * @param bool  $sendNotification
176
     *
177
     * @return bool|int
178
     */
179
    public function generate($params = [], $sendNotification = false)
180
    {
181
        // The user directory should be set
182
        if (empty($this->certification_user_path) &&
183
            false === $this->force_certificate_generation
184
        ) {
185
            return false;
186
        }
187
188
        $params['hide_print_button'] = isset($params['hide_print_button']) ? true : false;
189
        $categoryId = 0;
190
        $my_category = [];
191
        if (isset($this->certificate_data) && isset($this->certificate_data['cat_id'])) {
192
            $categoryId = $this->certificate_data['cat_id'];
193
            $my_category = Category::load($categoryId);
194
        }
195
196
        if (isset($my_category[0]) && !empty($categoryId) &&
197
            $my_category[0]->is_certificate_available($this->user_id)
198
        ) {
199
            /** @var Category $category */
200
            $category = $my_category[0];
201
202
            $courseInfo = api_get_course_info($category->get_course_code());
203
            $courseId = $courseInfo['real_id'];
204
            $sessionId = $category->get_session_id();
205
206
            $skill = new SkillModel();
207
            $skill->addSkillToUser(
208
                $this->user_id,
209
                $category,
210
                $courseId,
211
                $sessionId
212
            );
213
214
            if (is_dir($this->certification_user_path)) {
215
                if (!empty($this->certificate_data)) {
216
                    $new_content_html = GradebookUtils::get_user_certificate_content(
217
                        $this->user_id,
218
                        $category->get_course_code(),
219
                        $category->get_session_id(),
220
                        false,
221
                        $params['hide_print_button']
222
                    );
223
224
                    if ($category->get_id() == $categoryId) {
225
                        $name = $this->certificate_data['path_certificate'];
226
                        $myPathCertificate = $this->certification_user_path.basename($name);
227
228
                        if (file_exists($myPathCertificate) &&
229
                            !empty($name) &&
230
                            !is_dir($myPathCertificate) &&
231
                            false == $this->force_certificate_generation
232
                        ) {
233
                            // Seems that the file was already generated
234
                            return true;
235
                        } else {
236
                            // Creating new name
237
                            $name = md5($this->user_id.$this->certificate_data['cat_id']).'.html';
238
                            $myPathCertificate = $this->certification_user_path.$name;
239
                            $path_certificate = '/'.$name;
240
241
                            // Getting QR filename
242
                            $file_info = pathinfo($path_certificate);
243
                            $qr_code_filename = $this->certification_user_path.$file_info['filename'].'_qr.png';
244
245
                            $newContent = str_replace(
246
                                '((certificate_barcode))',
247
                                Display::img(
248
                                    $this->certification_web_user_path.$file_info['filename'].'_qr.png',
249
                                    'QR'
250
                                ),
251
                                $new_content_html['content']
252
                            );
253
254
                            $newContent = api_convert_encoding(
255
                                $newContent,
256
                                'UTF-8',
257
                                api_get_system_encoding()
258
                            );
259
260
                            $result = @file_put_contents($myPathCertificate, $newContent);
261
                            if ($result) {
262
                                // Updating the path
263
                                $this->updateUserCertificateInfo(
264
                                    $this->certificate_data['cat_id'],
265
                                    $this->user_id,
266
                                    $path_certificate
267
                                );
268
                                $this->certificate_data['path_certificate'] = $path_certificate;
269
270
                                if ($this->isHtmlFileGenerated()) {
271
                                    if (!empty($file_info)) {
272
                                        $text = $this->parseCertificateVariables(
273
                                            $new_content_html['variables']
274
                                        );
275
                                        $this->generateQRImage(
276
                                            $text,
277
                                            $qr_code_filename
278
                                        );
279
280
                                        if ($sendNotification) {
281
                                            $subject = get_lang('Certificate notification');
282
                                            $message = nl2br(get_lang('((user_first_name)),'));
283
                                            $score = $this->certificate_data['score_certificate'];
284
                                            self::sendNotification(
285
                                                $subject,
286
                                                $message,
287
                                                api_get_user_info($this->user_id),
288
                                                $courseInfo,
289
                                                [
290
                                                    'score_certificate' => $score,
291
                                                ]
292
                                            );
293
                                        }
294
                                    }
295
                                }
296
                            }
297
298
                            return $result;
299
                        }
300
                    }
301
                }
302
            }
303
        } else {
304
            // General certificate
305
            $name = md5($this->user_id).'.html';
306
            $my_path_certificate = $this->certification_user_path.$name;
307
            $path_certificate = '/'.$name;
308
309
            // Getting QR filename
310
            $file_info = pathinfo($path_certificate);
311
            $content = $this->generateCustomCertificate();
312
313
            $my_new_content_html = str_replace(
314
                '((certificate_barcode))',
315
                Display::img(
316
                    $this->certification_web_user_path.$file_info['filename'].'_qr.png',
317
                    'QR'
318
                ),
319
                $content
320
            );
321
322
            $my_new_content_html = mb_convert_encoding(
323
                $my_new_content_html,
324
                'UTF-8',
325
                api_get_system_encoding()
326
            );
327
328
            $result = @file_put_contents($my_path_certificate, $my_new_content_html);
329
330
            if ($result) {
331
                // Updating the path
332
                self::updateUserCertificateInfo(
333
                    0,
334
                    $this->user_id,
335
                    $path_certificate
336
                );
337
                $this->certificate_data['path_certificate'] = $path_certificate;
338
            }
339
340
            return $result;
341
        }
342
343
        return false;
344
    }
345
346
    /**
347
     * @return array
348
     */
349
    public static function notificationTags()
350
    {
351
        $tags = [
352
            '((course_title))',
353
            '((user_first_name))',
354
            '((user_last_name))',
355
            '((author_first_name))',
356
            '((author_last_name))',
357
            '((score))',
358
            '((portal_name))',
359
            '((certificate_link))',
360
        ];
361
362
        return $tags;
363
    }
364
365
    /**
366
     * @param string $subject
367
     * @param string $message
368
     * @param array  $userInfo
369
     * @param array  $courseInfo
370
     * @param array  $certificateInfo
371
     *
372
     * @return bool
373
     */
374
    public static function sendNotification(
375
        $subject,
376
        $message,
377
        $userInfo,
378
        $courseInfo,
379
        $certificateInfo
380
    ) {
381
        if (empty($userInfo) || empty($courseInfo)) {
382
            return false;
383
        }
384
385
        $currentUserInfo = api_get_user_info();
386
        $url = api_get_path(WEB_PATH).
387
            'certificates/index.php?id='.$certificateInfo['id'].'&user_id='.$certificateInfo['user_id'];
388
        $link = Display::url($url, $url);
389
390
        $replace = [
391
            $courseInfo['title'],
392
            $userInfo['firstname'],
393
            $userInfo['lastname'],
394
            $currentUserInfo['firstname'],
395
            $currentUserInfo['lastname'],
396
            $certificateInfo['score_certificate'],
397
            api_get_setting('Institution'),
398
            $link,
399
        ];
400
401
        $message = str_replace(self::notificationTags(), $replace, $message);
402
        MessageManager::send_message(
403
            $userInfo['id'],
404
            $subject,
405
            $message,
406
            [],
407
            [],
408
            0,
409
            0,
410
            0,
411
            0,
412
            $currentUserInfo['id']
413
        );
414
415
        $plugin = new AppPlugin();
416
        $smsPlugin = $plugin->getSMSPluginLibrary();
417
        if ($smsPlugin) {
0 ignored issues
show
introduced by
$smsPlugin is of type SmsPluginLibraryInterface, thus it always evaluated to true.
Loading history...
418
            $additionalParameters = [
419
                'smsType' => SmsPlugin::CERTIFICATE_NOTIFICATION,
420
                'userId' => $userInfo['id'],
421
                'direct_message' => $message,
422
            ];
423
            $smsPlugin->send($additionalParameters);
424
        }
425
    }
426
427
    /**
428
     * Update user info about certificate.
429
     *
430
     * @param int    $categoryId            category id
431
     * @param int    $user_id               user id
432
     * @param string $path_certificate      the path name of the certificate
433
     * @param bool   $updateCertificateData
434
     */
435
    public function updateUserCertificateInfo(
436
        $categoryId,
437
        $user_id,
438
        $path_certificate,
439
        $updateCertificateData = true
440
    ) {
441
        $categoryId = (int) $categoryId;
442
        $user_id = (int) $user_id;
443
444
        if ($updateCertificateData &&
445
            !UserManager::is_user_certified($categoryId, $user_id)
446
        ) {
447
            $table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
448
            $now = api_get_utc_datetime();
449
            $sql = 'UPDATE '.$table.' SET
450
                        path_certificate="'.Database::escape_string($path_certificate).'",
451
                        created_at = "'.$now.'"
452
                    WHERE cat_id = "'.$categoryId.'" AND user_id="'.$user_id.'" ';
453
            Database::query($sql);
454
        }
455
    }
456
457
    /**
458
     * Check if the file was generated.
459
     *
460
     * @return bool
461
     */
462
    public function isHtmlFileGenerated()
463
    {
464
        if (empty($this->certification_user_path)) {
465
            return false;
466
        }
467
        if (!empty($this->certificate_data) &&
468
            isset($this->certificate_data['path_certificate']) &&
469
            !empty($this->certificate_data['path_certificate'])
470
        ) {
471
            return true;
472
        }
473
474
        return false;
475
    }
476
477
    /**
478
     * Generates a QR code for the certificate. The QR code embeds the text given.
479
     *
480
     * @param string $text Text to be added in the QR code
481
     * @param string $path file path of the image
482
     *
483
     * @return bool
484
     */
485
    public function generateQRImage($text, $path)
486
    {
487
        if (!empty($text) && !empty($path)) {
488
            $qrCode = new QrCode($text);
489
            //$qrCode->setEncoding('UTF-8');
490
            $qrCode->setSize(120);
491
            $qrCode->setMargin(5);
492
            $qrCode->setWriterByName('png');
493
            $qrCode->setErrorCorrectionLevel(ErrorCorrectionLevel::MEDIUM());
494
            $qrCode->setForegroundColor(['r' => 0, 'g' => 0, 'b' => 0, 'a' => 0]);
495
            $qrCode->setBackgroundColor(['r' => 255, 'g' => 255, 'b' => 255, 'a' => 0]);
496
            $qrCode->setValidateResult(false);
497
            $qrCode->writeFile($path);
498
499
            return true;
500
        }
501
502
        return false;
503
    }
504
505
    /**
506
     * Transforms certificate tags into text values. This function is very static
507
     * (it doesn't allow for much flexibility in terms of what tags are printed).
508
     *
509
     * @param array $array Contains two array entries: first are the headers,
510
     *                     second is an array of contents
511
     *
512
     * @return string The translated string
513
     */
514
    public function parseCertificateVariables($array)
515
    {
516
        $headers = $array[0];
517
        $content = $array[1];
518
        $final_content = [];
519
520
        if (!empty($content)) {
521
            foreach ($content as $key => $value) {
522
                $my_header = str_replace(['((', '))'], '', $headers[$key]);
523
                $final_content[$my_header] = $value;
524
            }
525
        }
526
527
        /* Certificate tags
528
         *
529
          0 => string '((user_firstname))' (length=18)
530
          1 => string '((user_lastname))' (length=17)
531
          2 => string '((gradebook_institution))' (length=25)
532
          3 => string '((gradebook_sitename))' (length=22)
533
          4 => string '((teacher_firstname))' (length=21)
534
          5 => string '((teacher_lastname))' (length=20)
535
          6 => string '((official_code))' (length=17)
536
          7 => string '((date_certificate))' (length=20)
537
          8 => string '((course_code))' (length=15)
538
          9 => string '((course_title))' (length=16)
539
          10 => string '((gradebook_grade))' (length=19)
540
          11 => string '((certificate_link))' (length=20)
541
          12 => string '((certificate_link_html))' (length=25)
542
          13 => string '((certificate_barcode))' (length=23)
543
         */
544
545
        $break_space = " \n\r ";
546
        $text =
547
            $final_content['gradebook_institution'].' - '.
548
            $final_content['gradebook_sitename'].' - '.
549
            get_lang('Certification').$break_space.
550
            get_lang('Learner').': '.$final_content['user_firstname'].' '.$final_content['user_lastname'].$break_space.
551
            get_lang('Trainer').': '.$final_content['teacher_firstname'].' '.$final_content['teacher_lastname'].$break_space.
552
            get_lang('Date').': '.$final_content['date_certificate'].$break_space.
553
            get_lang('Score').': '.$final_content['gradebook_grade'].$break_space.
554
            'URL'.': '.$final_content['certificate_link'];
555
556
        return $text;
557
    }
558
559
    /**
560
     * Check if the certificate is visible for the current user
561
     * If the global setting allow_public_certificates is set to 'false', no certificate can be printed.
562
     * If the global allow_public_certificates is set to 'true' and the course setting allow_public_certificates
563
     * is set to 0, no certificate *in this course* can be printed (for anonymous users).
564
     * Connected users can always print them.
565
     *
566
     * @return bool
567
     */
568
    public function isVisible()
569
    {
570
        if (!api_is_anonymous()) {
571
            return true;
572
        }
573
574
        if ('true' != api_get_setting('allow_public_certificates')) {
575
            // The "non-public" setting is set, so do not print
576
            return false;
577
        }
578
579
        if (!isset($this->certificate_data, $this->certificate_data['cat_id'])) {
580
            return false;
581
        }
582
583
        $gradeBook = new Gradebook();
584
        $gradeBookInfo = $gradeBook->get($this->certificate_data['cat_id']);
585
586
        if (empty($gradeBookInfo['course_code'])) {
587
            return false;
588
        }
589
590
        $setting = api_get_course_setting(
591
            'allow_public_certificates',
592
            api_get_course_info($gradeBookInfo['course_code'])
593
        );
594
595
        if (0 == $setting) {
596
            // Printing not allowed
597
            return false;
598
        }
599
600
        return true;
601
    }
602
603
    /**
604
     * Check if the certificate is available.
605
     *
606
     * @return bool
607
     */
608
    public function isAvailable()
609
    {
610
        if (empty($this->certificate_data['path_certificate'])) {
611
            return false;
612
        }
613
614
        $userCertificate = $this->certification_user_path.basename($this->certificate_data['path_certificate']);
615
616
        if (!file_exists($userCertificate)) {
617
            return false;
618
        }
619
620
        return true;
621
    }
622
623
    /**
624
     * Shows the student's certificate (HTML file).
625
     */
626
    public function show()
627
    {
628
        $user_certificate = $this->certification_user_path.basename($this->certificate_data['path_certificate']);
629
        if (file_exists($user_certificate)) {
630
            // Needed in order to browsers don't add custom CSS
631
            $certificateContent = '<!DOCTYPE html>';
632
            $certificateContent .= (string) file_get_contents($user_certificate);
633
634
            // Remove media=screen to be available when printing a document
635
            $certificateContent = str_replace(
636
                ' media="screen"',
637
                '',
638
                $certificateContent
639
            );
640
641
            if ($this->user_id == api_get_user_id() &&
642
                !empty($this->certificate_data) &&
643
                isset($this->certificate_data['id'])
644
            ) {
645
                $certificateId = $this->certificate_data['id'];
646
                $extraFieldValue = new ExtraFieldValue('user_certificate');
647
                $value = $extraFieldValue->get_values_by_handler_and_field_variable(
648
                    $certificateId,
649
                    'downloaded_at'
650
                );
651
                if (empty($value)) {
652
                    $params = [
653
                        'item_id' => $this->certificate_data['id'],
654
                        'extra_downloaded_at' => api_get_utc_datetime(),
655
                    ];
656
                    $extraFieldValue->saveFieldValues($params);
657
                }
658
            }
659
660
            header('Content-Type: text/html; charset='.api_get_system_encoding());
661
            echo $certificateContent;
662
663
            return;
664
        }
665
        api_not_allowed(true);
666
    }
667
668
    /**
669
     * @return string
670
     */
671
    public function generateCustomCertificate()
672
    {
673
        $myCertificate = GradebookUtils::get_certificate_by_user_id(
674
            0,
675
            $this->user_id
676
        );
677
        if (empty($myCertificate)) {
678
            GradebookUtils::registerUserInfoAboutCertificate(
679
                0,
680
                $this->user_id,
681
                100,
682
                api_get_utc_datetime()
683
            );
684
        }
685
686
        $userInfo = api_get_user_info($this->user_id);
687
        $extraFieldValue = new ExtraFieldValue('user');
688
        $value = $extraFieldValue->get_values_by_handler_and_field_variable($this->user_id, 'legal_accept');
689
        $termsValidationDate = '';
690
        if (isset($value) && !empty($value['value'])) {
691
            [$id, $id2, $termsValidationDate] = explode(':', $value['value']);
692
        }
693
694
        $sessions = SessionManager::get_sessions_by_user($this->user_id, false, true);
695
        $totalTimeInLearningPaths = 0;
696
        $sessionsApproved = [];
697
        $coursesApproved = [];
698
        $courseList = [];
699
700
        $gradeBookRepo = Container::getGradeBookCategoryRepository();
701
        if ($sessions) {
702
            foreach ($sessions as $session) {
703
                $allCoursesApproved = [];
704
                foreach ($session['courses'] as $course) {
705
                    $course = api_get_course_entity($course['real_id']);
706
                    $courseId = $course->getId();
707
                    $category = $gradeBookRepo->findOneBy(['course' => $course, 'session' => $session['session_id']]);
708
709
                    /*$gradebookCategories = Category::load(
710
                        null,
711
                        null,
712
                        $courseCode,
713
                        null,
714
                        false,
715
                        $session['session_id']
716
                    );*/
717
718
                    if (null !== $category) {
719
                        $result = Category::userFinishedCourse(
720
                            $this->user_id,
721
                            $category,
722
                            true
723
                        );
724
725
                        // Find time spent in LP
726
                        $timeSpent = Tracking::get_time_spent_in_lp(
727
                            $this->user_id,
728
                            $course,
729
                            [],
730
                            $session['session_id']
731
                        );
732
733
                        if (!isset($courseList[$courseId])) {
734
                            $courseList[$courseId]['approved'] = false;
735
                            $courseList[$courseId]['time_spent'] = 0;
736
                        }
737
738
                        if ($result) {
739
                            $courseList[$courseId]['approved'] = true;
740
                            $coursesApproved[$courseId] = $course->getTitle();
741
742
                            // Find time spent in LP
743
                            //$totalTimeInLearningPaths += $timeSpent;
744
                            $allCoursesApproved[] = true;
745
                        }
746
                        $courseList[$courseId]['time_spent'] += $timeSpent;
747
                    }
748
                }
749
750
                if (count($allCoursesApproved) == count($session['courses'])) {
751
                    $sessionsApproved[] = $session;
752
                }
753
            }
754
        }
755
756
        $totalTimeInLearningPaths = 0;
757
        foreach ($courseList as $courseId => $courseData) {
758
            if (true === $courseData['approved']) {
759
                $totalTimeInLearningPaths += $courseData['time_spent'];
760
            }
761
        }
762
763
        $skill = new SkillModel();
764
        // Ofaj
765
        $skills = $skill->getStudentSkills($this->user_id, 2);
766
        $timeInSeconds = Tracking::get_time_spent_on_the_platform(
767
            $this->user_id,
768
            'ever'
769
        );
770
        $time = api_time_to_hms($timeInSeconds);
771
772
        $tplContent = new Template(null, false, false, false, false, false);
773
774
        // variables for the default template
775
        $tplContent->assign('complete_name', $userInfo['complete_name']);
776
        $tplContent->assign('time_in_platform', $time);
777
        $tplContent->assign('certificate_generated_date', api_get_local_time($myCertificate['created_at']));
778
        if (!empty($termsValidationDate)) {
779
            $termsValidationDate = api_get_local_time($termsValidationDate);
780
        }
781
        $tplContent->assign('terms_validation_date', $termsValidationDate);
782
783
        // Ofaj
784
        $tplContent->assign('time_in_platform_in_hours', round($timeInSeconds / 3600, 1));
785
        $tplContent->assign(
786
            'certificate_generated_date_no_time',
787
            api_get_local_time(
788
                $myCertificate['created_at'],
789
                null,
790
                null,
791
                false,
792
                false,
793
                false,
794
                'd-m-Y'
795
            )
796
        );
797
        $tplContent->assign(
798
            'terms_validation_date_no_time',
799
            api_get_local_time(
800
                $termsValidationDate,
801
                null,
802
                null,
803
                false,
804
                false,
805
                false,
806
                'd-m-Y'
807
            )
808
        );
809
        $tplContent->assign('skills', $skills);
810
        $tplContent->assign('sessions', $sessionsApproved);
811
        $tplContent->assign('courses', $coursesApproved);
812
        $tplContent->assign('time_spent_in_lps', api_time_to_hms($totalTimeInLearningPaths));
813
        $tplContent->assign('time_spent_in_lps_in_hours', round($totalTimeInLearningPaths / 3600, 1));
814
815
        $layoutContent = $tplContent->get_template('gradebook/custom_certificate.tpl');
816
        $content = $tplContent->fetch($layoutContent);
817
818
        return $content;
819
    }
820
821
    /**
822
     * Ofaj.
823
     */
824
    public function generatePdfFromCustomCertificate()
825
    {
826
        $orientation = api_get_configuration_value('certificate_pdf_orientation');
827
828
        $params['orientation'] = 'landscape';
829
        if (!empty($orientation)) {
830
            $params['orientation'] = $orientation;
831
        }
832
833
        $params['left'] = 0;
834
        $params['right'] = 0;
835
        $params['top'] = 0;
836
        $params['bottom'] = 0;
837
        $page_format = 'landscape' == $params['orientation'] ? 'A4-L' : 'A4';
838
        $pdf = new PDF($page_format, $params['orientation'], $params);
839
840
        $pdf->html_to_pdf(
841
            $this->html_file,
842
            get_lang('Certificates'),
843
            null,
844
            false,
845
            false
846
        );
847
    }
848
849
    /**
850
     * @param int $userId
851
     *
852
     * @return array
853
     */
854
    public static function getCertificateByUser($userId)
855
    {
856
        $userId = (int) $userId;
857
        if (empty($userId)) {
858
            return [];
859
        }
860
861
        $table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
862
        $sql = "SELECT * FROM $table
863
                WHERE user_id= $userId";
864
        $rs = Database::query($sql);
865
866
        return Database::store_result($rs, 'ASSOC');
867
    }
868
869
    /**
870
     * @param int $userId
871
     */
872
    public static function generateUserSkills($userId)
873
    {
874
        $controller = new IndexManager(get_lang('My courses'));
875
        $courseAndSessions = $controller->returnCoursesAndSessions($userId, true, null, true, false);
876
        $repo = Container::getGradeBookCategoryRepository();
877
        if (isset($courseAndSessions['courses']) && !empty($courseAndSessions['courses'])) {
878
            foreach ($courseAndSessions['courses'] as $course) {
879
                $category = $repo->findOneBy(['course' => $course['real_id']]);
880
                /*$cats = Category::load(
881
                    null,
882
                    null,
883
                    $course['code'],
884
                    null,
885
                    null,
886
                    null,
887
                    false
888
                );*/
889
                if (null !== $category) {
890
                    Category::generateUserCertificate($category, $userId);
891
                }
892
            }
893
        }
894
895
        if (isset($courseAndSessions['sessions']) && !empty($courseAndSessions['sessions'])) {
896
            foreach ($courseAndSessions['sessions'] as $sessionCategory) {
897
                if (isset($sessionCategory['sessions'])) {
898
                    foreach ($sessionCategory['sessions'] as $sessionData) {
899
                        if (!empty($sessionData['courses'])) {
900
                            $sessionId = $sessionData['session_id'];
901
                            foreach ($sessionData['courses'] as $courseData) {
902
                                /*$cats = Category:: load(
903
                                    null,
904
                                    null,
905
                                    $courseData['course_code'],
906
                                    null,
907
                                    null,
908
                                    $sessionId,
909
                                    false
910
                                );*/
911
912
                                $category = $repo->findOneBy(
913
                                    ['course' => $courseData['real_id'], 'session' => $sessionId]
914
                                );
915
                                if (null !== $category) {
916
                                    Category::generateUserCertificate($category, $userId);
917
                                }
918
                            }
919
                        }
920
                    }
921
                }
922
            }
923
        }
924
    }
925
}
926