Passed
Push — master ( 4e247b...3e9cbb )
by
unknown
10:51
created

LegalManager::sendLegal()   B

Complexity

Conditions 11
Paths 54

Size

Total Lines 55
Code Lines 39

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 11
eloc 39
nc 54
nop 2
dl 0
loc 55
rs 7.3166
c 0
b 0
f 0

How to fix   Long Method    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
3
/* For licensing terms, see /license.txt */
4
5
/**
6
 * Class LegalManager.
7
 */
8
class LegalManager
9
{
10
    /**
11
     * Constructor.
12
     */
13
    public function __construct()
14
    {
15
    }
16
17
    /**
18
     * Add a new Term and Condition.
19
     *
20
     * @param int    $language               language id
21
     * @param string $content                content
22
     * @param int    $type                   term and condition type (0 for HTML text or 1 for link to another page)
23
     * @param string $changes                explain changes
24
     * @param array  $extraFieldValuesToSave
25
     *
26
     * @return int
27
     */
28
    public static function add($language, $content, $type, $changes, $extraFieldValuesToSave = [])
29
    {
30
        $legalTable = Database::get_main_table(TABLE_MAIN_LEGAL);
31
        $last = self::get_last_condition($language);
32
33
        if (false === $last) {
34
            return 0;
35
        }
36
37
        $type = (int) $type;
38
        $time = time();
39
40
        $changeList = [];
41
42
        if (isset($last['id'])) {
43
            $id = $last['id'];
44
45
            // Check if extra fields changed
46
            $extraFieldValue = new ExtraFieldValue('terms_and_condition');
47
            $values = $extraFieldValue->getAllValuesByItem($id);
48
            $oldValues = array_column($values, 'value', 'variable');
49
            foreach ($extraFieldValuesToSave as $key => $value) {
50
                if (is_numeric(strpos($key, 'extra_'))) {
51
                    $replace = str_replace('extra_', '', $key);
52
                    if (isset($oldValues[$replace])) {
53
                        if ($value != $oldValues[$replace]) {
54
                            $changeList[] = $replace;
55
                        }
56
                    } else {
57
                        // It means there's a new extra field that was not included before.
58
                        $changeList[] = $replace;
59
                    }
60
                }
61
            }
62
        }
63
64
        if ((isset($last['content']) && $last['content'] != $content) || !empty($changeList) || empty($last)) {
65
            $version = self::getLastVersion($language);
66
            $version++;
67
            $params = [
68
                'language_id' => $language,
69
                'content' => $content,
70
                'changes' => $changes,
71
                'type' => $type,
72
                'version' => $version,
73
                'date' => $time,
74
            ];
75
76
            $id = Database::insert($legalTable, $params);
77
78
            self::updateExtraFields($id, $extraFieldValuesToSave);
79
80
            return $id;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $id could also return false which is incompatible with the documented return type integer. Did you maybe forget to handle an error condition?

If the returned type also contains false, it is an indicator that maybe an error condition leading to the specific return statement remains unhandled.

Loading history...
81
        } elseif ($last['type'] != $type && $language == $last['language_id']) {
82
            // Update
83
            $id = $last['id'];
84
            $params = [
85
                'changes' => $changes,
86
                'type' => $type,
87
                'date' => $time,
88
            ];
89
            Database::update($legalTable, $params, ['id = ?' => $id]);
90
            self::updateExtraFields($id, $extraFieldValuesToSave);
91
92
            return $id;
93
        }
94
95
        return 0;
96
    }
97
98
    /**
99
     * @param int   $itemId
100
     * @param array $values
101
     *
102
     * @return bool
103
     */
104
    public static function updateExtraFields($itemId, $values)
105
    {
106
        if (empty($itemId)) {
107
            return false;
108
        }
109
        $extraFieldValues = new ExtraFieldValue('terms_and_condition');
110
        $values['item_id'] = $itemId;
111
        $extraFieldValues->saveFieldValues($values);
112
113
        return true;
114
    }
115
116
    /**
117
     * @param int $id
118
     */
119
    public static function delete($id)
120
    {
121
        /*
122
        $legalTable = Database::get_main_table(TABLE_MAIN_LEGAL);
123
        $id = (int) $id;
124
        $sql = "DELETE FROM $legalTable WHERE id = '".$id."'";
125
        */
126
    }
127
128
    /**
129
     * Gets the last version of a Term and condition by language.
130
     *
131
     * @param int $language language id
132
     *
133
     * @return int
134
     */
135
    public static function getLastVersion($language)
136
    {
137
        $table = Database::get_main_table(TABLE_MAIN_LEGAL);
138
        $language = (int) $language;
139
        $sql = "SELECT version FROM $table
140
                WHERE language_id = $language
141
                ORDER BY id DESC LIMIT 1 ";
142
        $result = Database::query($sql);
143
        $row = Database::fetch_array($result);
144
        if (Database::num_rows($result) > 0) {
145
            return (int) $row['version'];
146
        }
147
148
        return 0;
149
    }
150
151
    /**
152
     * Gets the data of a Term and condition by language.
153
     *
154
     * @param int $language language id
155
     *
156
     * @return array all the info of a Term and condition
157
     */
158
    public static function get_last_condition($language)
159
    {
160
        $table = Database::get_main_table(TABLE_MAIN_LEGAL);
161
        $language = (int) $language;
162
        $sql = "SELECT * FROM $table
163
                WHERE language_id = $language
164
                ORDER BY version DESC
165
                LIMIT 1 ";
166
        $result = Database::query($sql);
167
        $result = Database::fetch_assoc($result);
168
169
        if (isset($result['content'])) {
170
            $result['content'] = self::replaceTags($result['content']);
171
        }
172
173
        return $result;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $result also could return the type boolean which is incompatible with the documented return type array.
Loading history...
174
    }
175
176
    /**
177
     * Check if an specific version of an agreement exists.
178
     *
179
     * @param int $language
180
     * @param int $version
181
     *
182
     * @return bool
183
     */
184
    public static function hasVersion($language, $version)
185
    {
186
        $table = Database::get_main_table(TABLE_MAIN_LEGAL);
187
        $language = (int) $language;
188
        $version = (int) $version;
189
190
        if (empty($language)) {
191
            return false;
192
        }
193
194
        $sql = "SELECT version FROM $table
195
                WHERE
196
                    language_id = $language AND
197
                    version = $version
198
                LIMIT 1 ";
199
        $result = Database::query($sql);
200
        if (Database::num_rows($result) > 0) {
201
            return true;
202
        }
203
204
        return false;
205
    }
206
207
    /**
208
     * @param string $content
209
     *
210
     * @return string
211
     */
212
    public static function replaceTags($content)
213
    {
214
        if (strpos($content, '{{sessions}}')) {
215
            $sessionListToString = '';
216
            $sessionList = SessionManager::get_sessions_by_user(api_get_user_id());
217
            if ($sessionList) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $sessionList of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
218
                $sessionListToString = get_lang('Session list').'<ul>';
219
                foreach ($sessionList as $session) {
220
                    $sessionListToString .= '<li>'.$session['session_name'].'</li>';
221
                }
222
                $sessionListToString .= '<ul>';
223
            }
224
            $content = str_replace('{{sessions}}', $sessionListToString, $content);
225
        }
226
227
        return $content;
228
    }
229
230
    /**
231
     * Gets the last version of a Term and condition by language.
232
     *
233
     * @param int $language language id
234
     *
235
     * @return bool | int the version or false if does not exist
236
     */
237
    public static function get_last_version($language)
238
    {
239
        $table = Database::get_main_table(TABLE_MAIN_LEGAL);
240
        $language = (int) $language;
241
        $sql = "SELECT version FROM $table
242
                WHERE language_id = '$language'
243
                ORDER BY version DESC
244
                LIMIT 1 ";
245
        $result = Database::query($sql);
246
        if (Database::num_rows($result) > 0) {
247
            $version = Database::fetch_array($result);
248
            $version = explode(':', $version[0]);
249
250
            return $version[0];
251
        }
252
253
        return false;
254
    }
255
256
    /**
257
     * Show the last condition.
258
     *
259
     * @param array $term_preview with type and content i.e array('type'=>'1', 'content'=>'hola');
260
     *
261
     * @return string html preview
262
     */
263
    public static function show_last_condition($term_preview)
264
    {
265
        $preview = '';
266
        switch ($term_preview['type']) {
267
            case 0:
268
                if (!empty($term_preview['content'])) {
269
                    $preview = '<div class="terms-conditions">
270
                    <div id="legal-terms" class="scrollbar-inner">'.$term_preview['content'].'</div>
271
                    </div>';
272
                }
273
                $preview .= get_lang('By clicking on \'Register\' below you are agreeing to the Terms and Conditions');
274
                break;
275
                // Page link
276
            case 1:
277
                $preview = '<fieldset>
278
                             <legend>'.get_lang('Terms and Conditions').'</legend>';
279
                $preview .= '<div id="legal-accept-wrapper" class="form-item">
280
                <label class="option" for="legal-accept">
281
                <input id="legal-accept" type="checkbox" value="1" name="legal_accept"/>
282
                '.get_lang('I have read and agree to the').'
283
                <a href="#">'.get_lang('Terms and Conditions').'</a>
284
                </label>
285
                </div>
286
                </fieldset>';
287
                break;
288
            default:
289
                break;
290
        }
291
292
        return $preview;
293
    }
294
295
    /**
296
     * Get the terms and condition table (only for maintenance).
297
     *
298
     * @param int $from
299
     * @param int $number_of_items
300
     * @param int $column
301
     *
302
     * @return array
303
     */
304
    public static function get_legal_data($from, $number_of_items, $column)
305
    {
306
        $table = Database::get_main_table(TABLE_MAIN_LEGAL);
307
        $lang_table = Database::get_main_table(TABLE_MAIN_LANGUAGE);
308
        $from = (int) $from;
309
        $number_of_items = (int) $number_of_items;
310
        $column = (int) $column;
311
312
        $sql = "SELECT version, original_name as language, content, changes, type, FROM_UNIXTIME(date)
313
                FROM $table
314
                INNER JOIN $lang_table l
315
                ON (language_id = l.id)
316
                ORDER BY language, version ASC
317
                LIMIT $from, $number_of_items ";
318
319
        $result = Database::query($sql);
320
        $legals = [];
321
        while ($legal = Database::fetch_array($result)) {
322
            // max 2000 chars
323
            $languages[] = $legal[1];
324
            if (strlen($legal[2]) > 2000) {
325
                $legal[2] = substr(strip_tags($legal[2]), 0, 2000).' ... ';
326
            }
327
            if (0 == $legal[4]) {
328
                $legal[4] = get_lang('HTML');
329
            } elseif (1 == $legal[4]) {
330
                $legal[4] = get_lang('Page Link');
331
            }
332
            $legals[] = $legal;
333
        }
334
335
        return $legals;
336
    }
337
338
    /**
339
     * Gets the number of terms and conditions available.
340
     *
341
     * @return int
342
     */
343
    public static function count()
344
    {
345
        $table = Database::get_main_table(TABLE_MAIN_LEGAL);
346
        $sql = "SELECT count(*) as count_result
347
                FROM $table
348
                ORDER BY id DESC ";
349
        $result = Database::query($sql);
350
        $url = Database::fetch_assoc($result);
351
        $result = $url['count_result'];
352
353
        return $result;
354
    }
355
356
    /**
357
     * Get type of terms and conditions.
358
     * Type 0 is HTML Text
359
     * Type 1 is a link to a different terms and conditions page.
360
     *
361
     * @param int $legal_id
362
     * @param int $language_id
363
     *
364
     * @return mixed The current type of terms and conditions (int) or false on error
365
     */
366
    public static function get_type_of_terms_and_conditions($legal_id, $language_id)
367
    {
368
        $table = Database::get_main_table(TABLE_MAIN_LEGAL);
369
        $legal_id = (int) $legal_id;
370
        $language_id = (int) $language_id;
371
        $sql = "SELECT type FROM $table
372
                WHERE id = $legal_id AND language_id = $language_id";
373
        $rs = Database::query($sql);
374
375
        return Database::result($rs, 0, 'type');
376
    }
377
378
    /**
379
     * Send a message to a student with the legal terms link to validate
380
     *
381
     * @param int $userId The user to send legal terms to
382
     * @param int $coachId The user who sends the legal terms
383
     */
384
    public static function sendLegal(int $userId, int $coachId)
385
    {
386
        $subject = get_lang('Your terms and conditions are ready to be signed');
387
        $studentDetails = api_get_user_info($userId);
388
        $coachDetails   = api_get_user_info($coachId);
389
        $link           = trim(api_get_setting('course_validation_terms_and_conditions_url'));
390
        $completeLink   = '<a href="'.$link.'">'.$link.'</a>';
391
392
        $content = sprintf(
393
            get_lang('Hello,<br />Your tutor sent you your terms and conditions. You can sign it following this URL: %s'),
394
            $studentDetails['firstname'],
395
            $completeLink,
396
            $coachDetails['complete_name']
397
        );
398
        MessageManager::send_message_simple($userId, $subject, $content);
399
        Display::addFlash(Display::return_message(get_lang('Sent')));
400
401
        $extraFieldValue = new ExtraFieldValue('user');
402
        $value = $extraFieldValue->get_values_by_handler_and_field_variable($userId, 'termactivated');
403
        if ($value === false || (int)($value['value'] ?? 0) !== 1) {
404
            $extraFieldInfo = $extraFieldValue->getExtraField()->get_handler_field_info_by_field_variable('termactivated');
405
            if ($extraFieldInfo) {
406
                $extraFieldValue->save([
407
                    'item_id'     => $userId,
408
                    'field_id'    => $extraFieldInfo['id'],
409
                    'field_value' => 1,
410
                    'comment'     => '',
411
                ]);
412
            }
413
        }
414
415
        $enforceProfileCompleted =
416
            api_get_setting('ticket.show_terms_if_profile_completed') === 'true'
417
            || api_get_setting('registration.show_terms_if_profile_completed') === 'true';
418
419
        if ($enforceProfileCompleted) {
420
            $allValues = $extraFieldValue->getAllValuesByItem($userId);
421
            $justTermResults = [];
422
            foreach ($allValues as $row) {
423
                $var = $row['field_variable'] ?? $row['variable'] ?? null;
424
                if ($var !== null && str_starts_with($var, 'terms_')) {
425
                    $val = $row['value'] ?? null;
426
                    $justTermResults[$var] = !empty($val) && $val !== '0';
427
                }
428
            }
429
430
            $profileCompleted = 1;
431
            if (in_array(false, $justTermResults, true)) {
432
                $profileCompleted = 0;
433
            }
434
435
            $table = Database::get_main_table(TABLE_MAIN_USER);
436
            Database::query("UPDATE $table SET profile_completed = ".$profileCompleted." WHERE id = ".$userId);
437
438
            ChamiloSession::write('profile_completed_result', $justTermResults);
439
        }
440
    }
441
442
    /**
443
     * @param int $userId
444
     */
445
    public static function deleteLegal($userId)
446
    {
447
        $extraFieldValue = new ExtraFieldValue('user');
448
        $value = $extraFieldValue->get_values_by_handler_and_field_variable($userId, 'legal_accept');
449
        $result = $extraFieldValue->delete($value['id']);
450
        if ($result) {
451
            Display::addFlash(Display::return_message(get_lang('Deleted')));
452
        }
453
454
        $value = $extraFieldValue->get_values_by_handler_and_field_variable(
455
            $userId,
456
            'termactivated'
457
        );
458
        if ($value) {
459
            $extraFieldValue->delete($value['id']);
460
        }
461
    }
462
463
    /**
464
     * @return array
465
     */
466
    public static function getTreatmentTypeList()
467
    {
468
        return [
469
            'privacy_terms_collection' => 'collection',
470
            'privacy_terms_recording' => 'recording',
471
            'privacy_terms_organization' => 'organization',
472
            'privacy_terms_structure' => 'structure',
473
            'privacy_terms_conservation' => 'conservation',
474
            'privacy_terms_adaptation' => 'adaptation',
475
            'privacy_terms_extraction' => 'extraction',
476
            'privacy_terms_consultation' => 'consultation',
477
            'privacy_terms_usage' => 'usage',
478
            'privacy_terms_communication' => 'communication',
479
            'privacy_terms_interconnection' => 'interconnection',
480
            'privacy_terms_limitation' => 'limitation',
481
            'privacy_terms_deletion' => 'deletion',
482
            'privacy_terms_destruction' => 'destruction',
483
            'privacy_terms_profiling' => 'profiling',
484
        ];
485
    }
486
}
487