LegalManager   B
last analyzed

Complexity

Total Complexity 52

Size/Duplication

Total Lines 477
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 216
dl 0
loc 477
rs 7.44
c 0
b 0
f 0
wmc 52

17 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 2 1
A delete() 0 2 1
A updateExtraFields() 0 10 2
A sendLegal() 0 22 3
A replaceTags() 0 16 4
A count() 0 11 1
A hasVersion() 0 21 3
B show_last_condition() 0 34 6
A get_last_version() 0 17 2
A getTreatmentTypeList() 0 18 1
A get_legal_data() 0 32 5
A deleteLegal() 0 15 3
A get_type_of_terms_and_conditions() 0 10 1
A getLastVersion() 0 14 2
B add() 0 67 11
A get_last_condition() 0 20 3
A sendEmailToUserBoss() 0 26 3

How to fix   Complexity   

Complex Class

Complex classes like LegalManager often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use LegalManager, and based on these observations, apply Extract Interface, too.

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
        if (empty($content)) {
31
            return 0;
32
        }
33
34
        $legalTable = Database::get_main_table(TABLE_MAIN_LEGAL);
35
        $last = self::get_last_condition($language);
36
        $type = (int) $type;
37
        $time = time();
38
39
        $changeList = [];
40
41
        if (isset($last['id'])) {
42
            $id = $last['id'];
43
44
            // Check if extra fields changed
45
            $extraFieldValue = new ExtraFieldValue('terms_and_condition');
46
            $values = $extraFieldValue->getAllValuesByItem($id);
47
            $oldValues = array_column($values, 'value', 'variable');
48
            foreach ($extraFieldValuesToSave as $key => $value) {
49
                if (is_numeric(strpos($key, 'extra_'))) {
50
                    $replace = str_replace('extra_', '', $key);
51
                    if (isset($oldValues[$replace])) {
52
                        if ($value != $oldValues[$replace]) {
53
                            $changeList[] = $replace;
54
                        }
55
                    } else {
56
                        // It means there's a new extra field that was not included before.
57
                        $changeList[] = $replace;
58
                    }
59
                }
60
            }
61
        }
62
63
        if ($last['content'] != $content || !empty($changeList)) {
64
            $version = self::getLastVersion($language);
65
            $version++;
66
            $params = [
67
                'language_id' => $language,
68
                'content' => $content,
69
                'changes' => $changes,
70
                'type' => $type,
71
                'version' => $version,
72
                'date' => $time,
73
            ];
74
75
            $id = Database::insert($legalTable, $params);
76
77
            self::updateExtraFields($id, $extraFieldValuesToSave);
78
79
            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...
80
        } elseif ($last['type'] != $type && $language == $last['language_id']) {
81
            // Update
82
            $id = $last['id'];
83
            $params = [
84
                'changes' => $changes,
85
                'type' => $type,
86
                'date' => $time,
87
            ];
88
            Database::update($legalTable, $params, ['id = ?' => $id]);
89
            self::updateExtraFields($id, $extraFieldValuesToSave);
90
91
            return $id;
92
        }
93
94
        return 0;
95
    }
96
97
    /**
98
     * @param int   $itemId
99
     * @param array $values
100
     *
101
     * @return bool
102
     */
103
    public static function updateExtraFields($itemId, $values)
104
    {
105
        if (empty($itemId)) {
106
            return false;
107
        }
108
        $extraFieldValues = new ExtraFieldValue('terms_and_condition');
109
        $values['item_id'] = $itemId;
110
        $extraFieldValues->saveFieldValues($values);
111
112
        return true;
113
    }
114
115
    /**
116
     * @param int $id
117
     */
118
    public static function delete($id)
119
    {
120
        /*
121
        $legalTable = Database::get_main_table(TABLE_MAIN_LEGAL);
122
        $id = (int) $id;
123
        $sql = "DELETE FROM $legalTable WHERE id = '".$id."'";
124
        */
125
    }
126
127
    /**
128
     * Gets the last version of a Term and condition by language.
129
     *
130
     * @param int $language language id
131
     *
132
     * @return int
133
     */
134
    public static function getLastVersion($language)
135
    {
136
        $table = Database::get_main_table(TABLE_MAIN_LEGAL);
137
        $language = (int) $language;
138
        $sql = "SELECT version FROM $table
139
                WHERE language_id = $language
140
                ORDER BY id DESC LIMIT 1 ";
141
        $result = Database::query($sql);
142
        $row = Database::fetch_array($result);
143
        if (Database::num_rows($result) > 0) {
144
            return (int) $row['version'];
145
        }
146
147
        return 0;
148
    }
149
150
    /**
151
     * Gets the data of a Term and condition by language.
152
     *
153
     * @param int $language language id
154
     *
155
     * @return array all the info of a Term and condition
156
     */
157
    public static function get_last_condition($language)
158
    {
159
        $table = Database::get_main_table(TABLE_MAIN_LEGAL);
160
        $language = (int) $language;
161
        $sql = "SELECT * FROM $table
162
                WHERE language_id = $language
163
                ORDER BY version DESC
164
                LIMIT 1 ";
165
        $result = Database::query($sql);
166
        $result = Database::fetch_array($result, 'ASSOC');
167
168
        if (empty($result)) {
169
            return [];
170
        }
171
172
        if (isset($result['content'])) {
173
            $result['content'] = self::replaceTags($result['content']);
174
        }
175
176
        return $result;
177
    }
178
179
    /**
180
     * Check if an specific version of an agreement exists.
181
     *
182
     * @param int $language
183
     * @param int $version
184
     *
185
     * @return bool
186
     */
187
    public static function hasVersion($language, $version)
188
    {
189
        $table = Database::get_main_table(TABLE_MAIN_LEGAL);
190
        $language = (int) $language;
191
        $version = (int) $version;
192
193
        if (empty($language)) {
194
            return false;
195
        }
196
197
        $sql = "SELECT version FROM $table
198
                WHERE
199
                    language_id = $language AND
200
                    version = $version
201
                LIMIT 1 ";
202
        $result = Database::query($sql);
203
        if (Database::num_rows($result) > 0) {
204
            return true;
205
        }
206
207
        return false;
208
    }
209
210
    /**
211
     * @param string $content
212
     *
213
     * @return string
214
     */
215
    public static function replaceTags($content)
216
    {
217
        if (strpos($content, '{{sessions}}')) {
218
            $sessionListToString = '';
219
            $sessionList = SessionManager::get_sessions_by_user(api_get_user_id());
220
            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...
221
                $sessionListToString = get_lang('SessionList').'<ul>';
222
                foreach ($sessionList as $session) {
223
                    $sessionListToString .= '<li>'.$session['session_name'].'</li>';
224
                }
225
                $sessionListToString .= '<ul>';
226
            }
227
            $content = str_replace('{{sessions}}', $sessionListToString, $content);
228
        }
229
230
        return $content;
231
    }
232
233
    /**
234
     * Gets the last version of a Term and condition by language.
235
     *
236
     * @param int $language language id
237
     *
238
     * @return bool|int the version or false if does not exist
239
     */
240
    public static function get_last_version($language)
241
    {
242
        $table = Database::get_main_table(TABLE_MAIN_LEGAL);
243
        $language = (int) $language;
244
        $sql = "SELECT version FROM $table
245
                WHERE language_id = '$language'
246
                ORDER BY version DESC
247
                LIMIT 1 ";
248
        $result = Database::query($sql);
249
        if (Database::num_rows($result) > 0) {
250
            $version = Database::fetch_array($result);
251
            $version = explode(':', $version[0]);
252
253
            return $version[0];
254
        }
255
256
        return false;
257
    }
258
259
    /**
260
     * Show the last condition.
261
     *
262
     * @param array $term_preview with type and content i.e array('type'=>'1', 'content'=>'hola');
263
     *
264
     * @return string html preview
265
     */
266
    public static function show_last_condition($term_preview)
267
    {
268
        $preview = '';
269
        switch ($term_preview['type']) {
270
            case 0:
271
                if (!empty($term_preview['content'])) {
272
                    $preview = '<div class="terms-conditions">
273
                    <div id="legal-terms" class="scrollbar-inner">'.$term_preview['content'].'</div>
274
                    </div>';
275
                }
276
                $preview .= get_lang('ByClickingRegisterYouAgreeTermsAndConditions');
277
                $courseInfo = api_get_course_info();
278
                if (api_get_setting('load_term_conditions_section') === 'course' && empty($courseInfo)) {
279
                    $preview = '';
280
                }
281
                break;
282
                // Page link
283
            case 1:
284
                $preview = '<fieldset>
285
                             <legend>'.get_lang('TermsAndConditions').'</legend>';
286
                $preview .= '<div id="legal-accept-wrapper" class="form-item">
287
                <label class="option" for="legal-accept">
288
                <input id="legal-accept" type="checkbox" value="1" name="legal_accept"/>
289
                '.get_lang('IHaveReadAndAgree').'
290
                <a href="#">'.get_lang('TermsAndConditions').'</a>
291
                </label>
292
                </div>
293
                </fieldset>';
294
                break;
295
            default:
296
                break;
297
        }
298
299
        return $preview;
300
    }
301
302
    /**
303
     * Get the terms and condition table (only for maintenance).
304
     *
305
     * @param int $from
306
     * @param int $number_of_items
307
     * @param int $column
308
     *
309
     * @return array
310
     */
311
    public static function get_legal_data($from, $number_of_items, $column)
312
    {
313
        $table = Database::get_main_table(TABLE_MAIN_LEGAL);
314
        $lang_table = Database::get_main_table(TABLE_MAIN_LANGUAGE);
315
        $from = (int) $from;
316
        $number_of_items = (int) $number_of_items;
317
        $column = (int) $column;
318
319
        $sql = "SELECT version, original_name as language, content, changes, type, FROM_UNIXTIME(date)
320
                FROM $table
321
                INNER JOIN $lang_table l
322
                ON (language_id = l.id)
323
                ORDER BY language, version ASC
324
                LIMIT $from, $number_of_items ";
325
326
        $result = Database::query($sql);
327
        $legals = [];
328
        while ($legal = Database::fetch_array($result)) {
329
            // max 2000 chars
330
            $languages[] = $legal[1];
331
            if (strlen($legal[2]) > 2000) {
332
                $legal[2] = substr(strip_tags($legal[2]), 0, 2000).' ... ';
333
            }
334
            if ($legal[4] == 0) {
335
                $legal[4] = get_lang('HTMLText');
336
            } elseif ($legal[4] == 1) {
337
                $legal[4] = get_lang('PageLink');
338
            }
339
            $legals[] = $legal;
340
        }
341
342
        return $legals;
343
    }
344
345
    /**
346
     * Gets the number of terms and conditions available.
347
     *
348
     * @return int
349
     */
350
    public static function count()
351
    {
352
        $table = Database::get_main_table(TABLE_MAIN_LEGAL);
353
        $sql = "SELECT count(*) as count_result
354
                FROM $table
355
                ORDER BY id DESC ";
356
        $result = Database::query($sql);
357
        $url = Database::fetch_array($result, 'ASSOC');
358
        $result = $url['count_result'];
359
360
        return $result;
361
    }
362
363
    /**
364
     * Get type of terms and conditions.
365
     * Type 0 is HTML Text
366
     * Type 1 is a link to a different terms and conditions page.
367
     *
368
     * @param int $legal_id
369
     * @param int $language_id
370
     *
371
     * @return mixed The current type of terms and conditions (int) or false on error
372
     */
373
    public static function get_type_of_terms_and_conditions($legal_id, $language_id)
374
    {
375
        $table = Database::get_main_table(TABLE_MAIN_LEGAL);
376
        $legal_id = (int) $legal_id;
377
        $language_id = (int) $language_id;
378
        $sql = "SELECT type FROM $table
379
                WHERE id = $legal_id AND language_id = $language_id";
380
        $rs = Database::query($sql);
381
382
        return Database::result($rs, 0, 'type');
383
    }
384
385
    /**
386
     * @param int $userId
387
     */
388
    public static function sendLegal($userId)
389
    {
390
        $subject = get_lang('SendTermsSubject');
391
        $content = sprintf(
392
            get_lang('SendTermsDescriptionToUrlX'),
393
            api_get_path(WEB_PATH)
394
        );
395
        MessageManager::send_message_simple($userId, $subject, $content);
396
        Display::addFlash(Display::return_message(get_lang('Sent')));
397
398
        $extraFieldValue = new ExtraFieldValue('user');
399
        $value = $extraFieldValue->get_values_by_handler_and_field_variable($userId, 'termactivated');
400
        if (false === $value) {
401
            $extraFieldInfo = $extraFieldValue->getExtraField()->get_handler_field_info_by_field_variable('termactivated');
402
            if ($extraFieldInfo) {
403
                $newParams = [
404
                    'item_id' => $userId,
405
                    'field_id' => $extraFieldInfo['id'],
406
                    'value' => 1,
407
                    'comment' => '',
408
                ];
409
                $extraFieldValue->save($newParams);
410
            }
411
        }
412
    }
413
414
    /**
415
     * @param int $userId
416
     */
417
    public static function deleteLegal($userId)
418
    {
419
        $extraFieldValue = new ExtraFieldValue('user');
420
        $value = $extraFieldValue->get_values_by_handler_and_field_variable($userId, 'legal_accept');
421
        $result = $extraFieldValue->delete($value['id']);
422
        if ($result) {
423
            Display::addFlash(Display::return_message(get_lang('Deleted')));
424
        }
425
426
        $value = $extraFieldValue->get_values_by_handler_and_field_variable(
427
            $userId,
428
            'termactivated'
429
        );
430
        if ($value) {
431
            $extraFieldValue->delete($value['id']);
432
        }
433
    }
434
435
    /**
436
     * @return array
437
     */
438
    public static function getTreatmentTypeList()
439
    {
440
        return [
441
            'privacy_terms_collection' => 'collection',
442
            'privacy_terms_recording' => 'recording',
443
            'privacy_terms_organization' => 'organization',
444
            'privacy_terms_structure' => 'structure',
445
            'privacy_terms_conservation' => 'conservation',
446
            'privacy_terms_adaptation' => 'adaptation',
447
            'privacy_terms_extraction' => 'extraction',
448
            'privacy_terms_consultation' => 'consultation',
449
            'privacy_terms_usage' => 'usage',
450
            'privacy_terms_communication' => 'communication',
451
            'privacy_terms_interconnection' => 'interconnection',
452
            'privacy_terms_limitation' => 'limitation',
453
            'privacy_terms_deletion' => 'deletion',
454
            'privacy_terms_destruction' => 'destruction',
455
            'privacy_terms_profiling' => 'profiling',
456
        ];
457
    }
458
459
    public static function sendEmailToUserBoss($userId, $conditionToSave)
460
    {
461
        UserManager::update_extra_field_value($userId, 'legal_accept', $conditionToSave);
462
463
        $bossList = UserManager::getStudentBossList($userId);
464
465
        if (empty($bossList)) {
466
            return;
467
        }
468
469
        $bossList = array_column($bossList, 'boss_id');
470
471
        $currentUserInfo = api_get_user_info($userId);
472
473
        foreach ($bossList as $bossId) {
474
            $subjectEmail = sprintf(
475
                get_lang('UserXSignedTheAgreement'),
476
                $currentUserInfo['complete_name']
477
            );
478
            $contentEmail = sprintf(
479
                get_lang('UserXSignedTheAgreementTheDateY'),
480
                $currentUserInfo['complete_name'],
481
                api_get_local_time()
482
            );
483
484
            MessageManager::send_message_simple($bossId, $subjectEmail, $contentEmail, $userId);
485
        }
486
    }
487
}
488