Passed
Push — 1.11.x ( 57356f...e797ca )
by Yannick
10:01
created

CustomCertificatePlugin   A

Complexity

Total Complexity 34

Size/Duplication

Total Lines 320
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 34
eloc 171
c 0
b 0
f 0
dl 0
loc 320
rs 9.68

9 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 11 1
A create() 0 5 2
B redirectCheck() 0 30 7
B update() 0 93 9
A install() 0 17 2
A uninstall() 0 12 2
A getInfoCertificate() 0 19 3
A getInfoCertificateDefault() 0 14 3
A getCertificateData() 0 33 5
1
<?php
2
/* For license terms, see /license.txt */
3
4
/**
5
 * Plugin class for the CustomCertificate plugin.
6
 *
7
 * @package chamilo.plugin.customcertificate
8
 *
9
 * @author Jose Angel Ruiz <[email protected]>
10
 */
11
class CustomCertificatePlugin extends Plugin
12
{
13
    public const TABLE_CUSTOMCERTIFICATE = 'plugin_customcertificate';
14
    public $isCoursePlugin = true;
15
16
    // When creating a new course this settings are added to the course
17
    public $course_settings = [
18
        [
19
            'name' => 'customcertificate_course_enable',
20
            'type' => 'checkbox',
21
        ],
22
        [
23
            'name' => 'use_certificate_default',
24
            'type' => 'checkbox',
25
        ],
26
    ];
27
28
    /**
29
     * Constructor.
30
     */
31
    protected function __construct()
32
    {
33
        parent::__construct(
34
            '1.0',
35
            'Jose Angel Ruiz - NoSoloRed (original author), Julio Montoya',
36
            [
37
                'enable_plugin_customcertificate' => 'boolean',
38
            ]
39
        );
40
41
        $this->isAdminPlugin = true;
42
    }
43
44
    /**
45
     * Instance the plugin.
46
     *
47
     * @staticvar null $result
48
     *
49
     * @return CustomCertificatePlugin
50
     */
51
    public static function create()
52
    {
53
        static $result = null;
54
55
        return $result ? $result : $result = new self();
56
    }
57
58
    /**
59
     * This method creates the tables required to this plugin.
60
     */
61
    public function install()
62
    {
63
        //Installing course settings
64
        $this->setCourseToolDefaultVisibility(false);
65
        $this->install_course_fields_in_all_courses();
66
67
        $tablesToBeCompared = [self::TABLE_CUSTOMCERTIFICATE];
68
        $em = Database::getManager();
69
        $cn = $em->getConnection();
70
        $sm = $cn->getSchemaManager();
71
        $tables = $sm->tablesExist($tablesToBeCompared);
72
73
        if ($tables) {
74
            return false;
75
        }
76
77
        require_once api_get_path(SYS_PLUGIN_PATH).'customcertificate/database.php';
78
    }
79
80
    /**
81
     * This method drops the plugin tables.
82
     */
83
    public function uninstall()
84
    {
85
        // Deleting course settings.
86
        $this->uninstall_course_fields_in_all_courses();
87
88
        $tablesToBeDeleted = [self::TABLE_CUSTOMCERTIFICATE];
89
        foreach ($tablesToBeDeleted as $tableToBeDeleted) {
90
            $table = Database::get_main_table($tableToBeDeleted);
91
            $sql = "DROP TABLE IF EXISTS $table";
92
            Database::query($sql);
93
        }
94
        $this->manageTab(false);
95
    }
96
97
    /**
98
     * This method update the previous plugin tables.
99
     */
100
    public function update()
101
    {
102
        $oldCertificateTable = 'gradebook_certificate_alternative';
103
        $base = api_get_path(WEB_UPLOAD_PATH);
104
        if (Database::num_rows(Database::query("SHOW TABLES LIKE '$oldCertificateTable'")) == 1) {
105
            $sql = "SELECT * FROM $oldCertificateTable";
106
            $res = Database::query($sql);
107
            while ($row = Database::fetch_assoc($res)) {
108
                $pathOrigin = $base.'certificates/'.$row['id'].'/';
109
                $params = [
110
                    'access_url_id' => api_get_current_access_url_id(),
111
                    'c_id' => $row['c_id'],
112
                    'session_id' => $row['session_id'],
113
                    'content_course' => $row['content_course'],
114
                    'contents_type' => intval($row['contents_type']),
115
                    'contents' => $row['contents'],
116
                    'date_change' => intval($row['date_change']),
117
                    'date_start' => $row['date_start'],
118
                    'date_end' => $row['date_end'],
119
                    'place' => $row['place'],
120
                    'type_date_expediction' => intval($row['type_date_expediction']),
121
                    'day' => $row['day'],
122
                    'month' => $row['month'],
123
                    'year' => $row['year'],
124
                    'logo_left' => $row['logo_left'],
125
                    'logo_center' => $row['logo_center'],
126
                    'logo_right' => $row['logo_right'],
127
                    'seal' => $row['seal'],
128
                    'signature1' => $row['signature1'],
129
                    'signature2' => $row['signature2'],
130
                    'signature3' => $row['signature3'],
131
                    'signature4' => $row['signature4'],
132
                    'signature_text1' => $row['signature_text1'],
133
                    'signature_text2' => $row['signature_text2'],
134
                    'signature_text3' => $row['signature_text3'],
135
                    'signature_text4' => $row['signature_text4'],
136
                    'background' => $row['background'],
137
                    'margin_left' => intval($row['margin']),
138
                    'margin_right' => 0,
139
                    'certificate_default' => 0,
140
                ];
141
142
                $certificateId = Database::insert(self::TABLE_CUSTOMCERTIFICATE, $params);
143
144
                // Image manager
145
                $pathDestiny = $base.'certificates/'.$certificateId.'/';
0 ignored issues
show
Bug introduced by
Are you sure $certificateId of type false|integer can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

145
                $pathDestiny = $base.'certificates/'./** @scrutinizer ignore-type */ $certificateId.'/';
Loading history...
146
147
                if (!file_exists($pathDestiny)) {
148
                    mkdir($pathDestiny, api_get_permissions_for_new_directories(), true);
149
                }
150
151
                $imgList = [
152
                    'logo_left',
153
                    'logo_center',
154
                    'logo_right',
155
                    'seal',
156
                    'signature1',
157
                    'signature2',
158
                    'signature3',
159
                    'signature4',
160
                    'background',
161
                ];
162
                foreach ($imgList as $value) {
163
                    if (!empty($row[$value])) {
164
                        copy(
165
                            $pathOrigin.$row[$value],
166
                            $pathDestiny.$row[$value]
167
                        );
168
                    }
169
                }
170
171
                if ($row['certificate_default'] == 1) {
172
                    $params['c_id'] = 0;
173
                    $params['session_id'] = 0;
174
                    $params['certificate_default'] = 1;
175
                    $certificateId = Database::insert(self::TABLE_CUSTOMCERTIFICATE, $params);
176
                    $pathOrigin = $base.'certificates/default/';
177
                    $pathDestiny = $base.'certificates/'.$certificateId.'/';
178
                    foreach ($imgList as $value) {
179
                        if (!empty($row[$value])) {
180
                            copy(
181
                                $pathOrigin.$row[$value],
182
                                $pathDestiny.$row[$value]
183
                            );
184
                        }
185
                    }
186
                }
187
            }
188
189
            $sql = "DROP TABLE IF EXISTS $oldCertificateTable";
190
            Database::query($sql);
191
192
            echo get_lang('MessageUpdate');
193
        }
194
    }
195
196
    /**
197
     * Get certificate data.
198
     *
199
     * @param int $id     The certificate
200
     * @param int $userId
201
     *
202
     * @return array
203
     */
204
    public static function getCertificateData($id, $userId)
205
    {
206
        $id = (int) $id;
207
        $userId = (int) $userId;
208
209
        if (empty($id) || empty($userId)) {
210
            return [];
211
        }
212
213
        $certificateTable = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
214
        $categoryTable = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
215
        $sql = "SELECT cer.user_id AS user_id, cat.session_id AS session_id, cat.course_code AS course_code
216
                FROM $certificateTable cer
217
                INNER JOIN $categoryTable cat
218
                ON (cer.cat_id = cat.id AND cer.user_id = $userId)
219
                WHERE cer.id = $id";
220
221
        $rs = Database::query($sql);
222
        if (Database::num_rows($rs) > 0) {
223
            $row = Database::fetch_assoc($rs);
224
            $courseCode = $row['course_code'];
225
            $sessionId = $row['session_id'];
226
            $userId = $row['user_id'];
227
            if (api_get_course_setting('customcertificate_course_enable', api_get_course_info($courseCode)) == 1) {
228
                return [
229
                    'course_code' => $courseCode,
230
                    'session_id' => $sessionId,
231
                    'user_id' => $userId,
232
                ];
233
            }
234
        }
235
236
        return [];
237
    }
238
239
    /**
240
     * Check if it redirects.
241
     *
242
     * @param certificate $certificate
243
     * @param int         $certId
244
     * @param int         $userId
245
     */
246
    public static function redirectCheck($certificate, $certId, $userId)
247
    {
248
        $certId = (int) $certId;
249
        $userId = !empty($userId) ? $userId : api_get_user_id();
250
251
        if (api_get_plugin_setting('customcertificate', 'enable_plugin_customcertificate') === 'true') {
252
            $infoCertificate = self::getCertificateData($certId, $userId);
253
            if (!empty($infoCertificate)) {
254
                if ($certificate->user_id == api_get_user_id() && !empty($certificate->certificate_data)) {
255
                    $certificateId = $certificate->certificate_data['id'];
256
                    $extraFieldValue = new ExtraFieldValue('user_certificate');
257
                    $value = $extraFieldValue->get_values_by_handler_and_field_variable(
258
                        $certificateId,
259
                        'downloaded_at'
260
                    );
261
                    if (empty($value)) {
262
                        $params = [
263
                            'item_id' => $certificate->certificate_data['id'],
264
                            'extra_downloaded_at' => api_get_utc_datetime(),
265
                        ];
266
                        $extraFieldValue->saveFieldValues($params);
267
                    }
268
                }
269
270
                $url = api_get_path(WEB_PLUGIN_PATH).'customcertificate/src/print_certificate.php'.
271
                    '?student_id='.$infoCertificate['user_id'].
272
                    '&course_code='.$infoCertificate['course_code'].
273
                    '&session_id='.$infoCertificate['session_id'];
274
                header('Location: '.$url);
275
                exit;
276
            }
277
        }
278
    }
279
280
    /**
281
     * Get certificate info.
282
     *
283
     * @param int $courseId
284
     * @param int $sessionId
285
     * @param int $accessUrlId
286
     *
287
     * @return array
288
     */
289
    public static function getInfoCertificate($courseId, $sessionId, $accessUrlId)
290
    {
291
        $courseId = (int) $courseId;
292
        $sessionId = (int) $sessionId;
293
        $accessUrlId = !empty($accessUrlId) ? (int) $accessUrlId : 1;
294
295
        $table = Database::get_main_table(self::TABLE_CUSTOMCERTIFICATE);
296
        $sql = "SELECT * FROM $table
297
                WHERE 
298
                    c_id = $courseId AND 
299
                    session_id = $sessionId AND
300
                    access_url_id = $accessUrlId";
301
        $result = Database::query($sql);
302
        $resultArray = [];
303
        if (Database::num_rows($result) > 0) {
304
            $resultArray = Database::fetch_array($result);
305
        }
306
307
        return $resultArray;
308
    }
309
310
    /**
311
     * Get default certificate info.
312
     *
313
     * @param int $accessUrlId
314
     *
315
     * @return array
316
     */
317
    public static function getInfoCertificateDefault($accessUrlId)
318
    {
319
        $accessUrlId = !empty($accessUrlId) ? (int) $accessUrlId : 1;
320
321
        $table = Database::get_main_table(self::TABLE_CUSTOMCERTIFICATE);
322
        $sql = "SELECT * FROM $table
323
                WHERE certificate_default = 1 AND access_url_id = $accessUrlId";
324
        $result = Database::query($sql);
325
        $resultArray = [];
326
        if (Database::num_rows($result) > 0) {
327
            $resultArray = Database::fetch_array($result);
328
        }
329
330
        return $resultArray;
331
    }
332
}
333