Completed
Push — master ( 3b3f82...8690b8 )
by Julito
10:13
created

Certificate::generateUserSkills()   C

Complexity

Conditions 15
Paths 16

Size

Total Lines 47
Code Lines 35

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 15
eloc 35
nc 16
nop 1
dl 0
loc 47
rs 5.9166
c 0
b 0
f 0

How to fix   Complexity   

Long Method

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

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

Commonly applied refactorings include:

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