ManagerApi   F
last analyzed

Complexity

Total Complexity 78

Size/Duplication

Total Lines 386
Duplicated Lines 1.3 %

Coupling/Cohesion

Components 2
Dependencies 3

Importance

Changes 0
Metric Value
dl 5
loc 386
rs 2.16
c 0
b 0
f 0
wmc 78
lcom 2
cbo 3

18 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A initPageViewState() 0 10 4
A savePageViewState() 0 6 2
A hasFormValues() 0 12 3
A saveFormValues() 0 5 2
A loadFormValues() 0 13 3
A clearSavedFormValues() 0 5 1
A getHashType() 0 13 5
B genV1Hash() 0 40 9
A getV1UserHashAlgorithm() 5 16 2
D checkHashAlgorithm() 0 40 20
A getSystemChecksum() 0 16 3
A getModifiedSystemFilesList() 0 19 5
A setSystemChecksum() 0 7 1
B checkSystemChecksum() 0 29 7
A getLastUserSetting() 0 21 5
A saveLastUserSetting() 0 21 4
A loadDatePicker() 0 8 1

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like ManagerApi 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. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

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 ManagerApi, and based on these observations, apply Extract Interface, too.

1
<?php namespace EvolutionCMS\Legacy;
2
3
use EvolutionCMS\Interfaces\ManagerApiInterface;
4
/*
5
 * Evolution CMS Manager API Class
6
 * Written by Raymond Irving 2005
7
 *
8
 */
9
10
//global $_PAGE; // page view state object. Usage $_PAGE['vs']['propertyname'] = $value;
11
12
// Content manager wrapper class
13
class ManagerApi implements ManagerApiInterface
14
{
15
    /**
16
     * @var string
17
     */
18
    public $action; // action directive
19
20
    /**
21
     * ManagerAPI constructor.
22
     */
23
    public function __construct()
24
    {
25
        global $action;
26
        $this->action = $action; // set action directive
27
    }
28
29
    /**
30
     * @param int $id
31
     */
32
    public function initPageViewState($id = 0)
33
    {
34
        global $_PAGE;
35
        $vsid = isset($_SESSION["mgrPageViewSID"]) ? $_SESSION["mgrPageViewSID"] : '';
36
        if ($vsid != $this->action) {
37
            $_SESSION["mgrPageViewSDATA"] = array(); // new view state
38
            $_SESSION["mgrPageViewSID"] = $id > 0 ? $id : $this->action; // set id
39
        }
40
        $_PAGE['vs'] = &$_SESSION["mgrPageViewSDATA"]; // restore viewstate
41
    }
42
43
    /**
44
     * save page view state - not really necessary,
45
     *
46
     * @param int $id
47
     */
48
    public function savePageViewState($id = 0)
49
    {
50
        global $_PAGE;
51
        $_SESSION["mgrPageViewSDATA"] = $_PAGE['vs'];
52
        $_SESSION["mgrPageViewSID"] = $id > 0 ? $id : $this->action;
53
    }
54
55
    /**
56
     * check for saved form
57
     *
58
     * @return bool
59
     */
60
    public function hasFormValues()
61
    {
62
        if (isset($_SESSION["mgrFormValueId"])) {
63
            if ($this->action == $_SESSION["mgrFormValueId"]) {
64
                return true;
65
            } else {
66
                $this->clearSavedFormValues();
67
            }
68
        }
69
70
        return false;
71
    }
72
73
    /**
74
     * saved form post from $_POST
75
     *
76
     * @param int $id
77
     */
78
    public function saveFormValues($id = 0)
79
    {
80
        $_SESSION["mgrFormValues"] = $_POST;
81
        $_SESSION["mgrFormValueId"] = $id > 0 ? $id : $this->action;
82
    }
83
84
    /**
85
     * load saved form values into $_POST
86
     *
87
     * @return bool
88
     */
89
    public function loadFormValues()
90
    {
91
        if (!$this->hasFormValues()) {
92
            return false;
93
        }
94
95
        $p = $_SESSION["mgrFormValues"];
96
        $this->clearSavedFormValues();
97
        foreach ($p as $k => $v) {
98
            $_POST[$k] = $v;
99
        }
100
        return true;
101
    }
102
103
    /**
104
     * clear form post
105
     *
106
     * @return void
107
     */
108
    public function clearSavedFormValues()
109
    {
110
        unset($_SESSION["mgrFormValues"]);
111
        unset($_SESSION["mgrFormValueId"]);
112
    }
113
114
    /**
115
     * @param string $db_value
116
     * @return string
117
     */
118
    public function getHashType($db_value = '')
119
    { // md5 | v1 | phpass
120
        $c = substr($db_value, 0, 1);
121
        if ($c === '$') {
122
            return 'phpass';
123
        } elseif (strlen($db_value) === 32) {
124
            return 'md5';
125
        } elseif ($c !== '$' && strpos($db_value, '>') !== false) {
126
            return 'v1';
127
        } else {
128
            return 'unknown';
129
        }
130
    }
131
132
    /**
133
     * @param string $password
134
     * @param string $seed
135
     * @return string
136
     */
137
    public function genV1Hash($password, $seed = '1')
138
    { // $seed is user_id basically
139
        $modx = evolutionCMS();
140
141
        if (isset($modx->config['pwd_hash_algo']) && !empty($modx->config['pwd_hash_algo'])) {
142
            $algorithm = $modx->getConfig('pwd_hash_algo');
143
        } else {
144
            $algorithm = 'UNCRYPT';
145
        }
146
147
        $salt = md5($password . $seed);
148
149
        switch ($algorithm) {
150
            case 'BLOWFISH_Y':
151
                $salt = '$2y$07$' . substr($salt, 0, 22);
152
                break;
153
            case 'BLOWFISH_A':
154
                $salt = '$2a$07$' . substr($salt, 0, 22);
155
                break;
156
            case 'SHA512':
157
                $salt = '$6$' . substr($salt, 0, 16);
158
                break;
159
            case 'SHA256':
160
                $salt = '$5$' . substr($salt, 0, 16);
161
                break;
162
            case 'MD5':
163
                $salt = '$1$' . substr($salt, 0, 8);
164
                break;
165
        }
166
167
        if ($algorithm !== 'UNCRYPT') {
168
            $password = sha1($password) . crypt($password, $salt);
169
        } else {
170
            $password = sha1($salt . $password);
171
        }
172
173
        $result = strtolower($algorithm) . '>' . md5($salt . $password) . substr(md5($salt), 0, 8);
174
175
        return $result;
176
    }
177
178
    /**
179
     * @param string $uid
180
     * @return string
181
     */
182
    public function getV1UserHashAlgorithm($uid)
183
    {
184
        $modx = evolutionCMS();
185
        $tbl_manager_users = $modx->getDatabase()->getFullTableName('manager_users');
186
        $uid = $modx->getDatabase()->escape($uid);
187
        $rs = $modx->getDatabase()->select('password', $tbl_manager_users, "id='{$uid}'");
188
        $password = $modx->getDatabase()->getValue($rs);
189
190 View Code Duplication
        if (strpos($password, '>') === false) {
191
            $algo = 'NOSALT';
192
        } else {
193
            $algo = substr($password, 0, strpos($password, '>'));
194
        }
195
196
        return strtoupper($algo);
197
    }
198
199
    /**
200
     * @param string $algorithm
201
     * @return bool
202
     */
203
    public function checkHashAlgorithm($algorithm = '')
204
    {
205
        $result = false;
206
        if (!empty($algorithm)) {
207
            switch ($algorithm) {
208
                case 'BLOWFISH_Y':
209
                    if (defined('CRYPT_BLOWFISH') && CRYPT_BLOWFISH == 1) {
210
                        if (version_compare('5.3.7', PHP_VERSION) <= 0) {
211
                            $result = true;
212
                        }
213
                    }
214
                    break;
215
                case 'BLOWFISH_A':
216
                    if (defined('CRYPT_BLOWFISH') && CRYPT_BLOWFISH == 1) {
217
                        $result = true;
218
                    }
219
                    break;
220
                case 'SHA512':
221
                    if (defined('CRYPT_SHA512') && CRYPT_SHA512 == 1) {
222
                        $result = true;
223
                    }
224
                    break;
225
                case 'SHA256':
226
                    if (defined('CRYPT_SHA256') && CRYPT_SHA256 == 1) {
227
                        $result = true;
228
                    }
229
                    break;
230
                case 'MD5':
231
                    if (defined('CRYPT_MD5') && CRYPT_MD5 == 1 && PHP_VERSION != '5.3.7') {
232
                        $result = true;
233
                    }
234
                    break;
235
                case 'UNCRYPT':
236
                    $result = true;
237
                    break;
238
            }
239
        }
240
241
        return $result;
242
    }
243
244
    /**
245
     * @param string $check_files
246
     * @return string
247
     */
248
    public function getSystemChecksum($check_files)
249
    {
250
        $_ = array();
251
        $check_files = trim($check_files);
252
        $check_files = explode("\n", $check_files);
253
        foreach ($check_files as $file) {
254
            $file = trim($file);
255
            $file = MODX_BASE_PATH . $file;
256
            if (!is_file($file)) {
257
                continue;
258
            }
259
            $_[$file] = md5_file($file);
260
        }
261
262
        return serialize($_);
263
    }
264
265
    /**
266
     * @param string $check_files
267
     * @param string $checksum
268
     * @return array
269
     */
270
    public function getModifiedSystemFilesList($check_files, $checksum)
271
    {
272
        $_ = array();
273
        $check_files = trim($check_files);
274
        $check_files = explode("\n", $check_files);
275
        $checksum = unserialize($checksum);
276
        foreach ($check_files as $file) {
277
            $file = trim($file);
278
            $filePath = MODX_BASE_PATH . $file;
279
            if (!is_file($filePath)) {
280
                continue;
281
            }
282
            if (!array_key_exists($filePath, $checksum) || md5_file($filePath) !== $checksum[$filePath]) {
283
                $_[] = $file;
284
            }
285
        }
286
287
        return $_;
288
    }
289
290
    /**
291
     * @param string $checksum
292
     */
293
    public function setSystemChecksum($checksum)
294
    {
295
        $modx = evolutionCMS();
296
        $tbl_system_settings = $modx->getDatabase()->getFullTableName('system_settings');
297
        $sql = "REPLACE INTO {$tbl_system_settings} (setting_name, setting_value) VALUES ('sys_files_checksum','" . $modx->getDatabase()->escape($checksum) . "')";
298
        $modx->getDatabase()->query($sql);
299
    }
300
301
    /**
302
     * @return array|string
303
     */
304
    public function checkSystemChecksum()
305
    {
306
        $modx = evolutionCMS();
307
308
        if (!isset($modx->config['check_files_onlogin']) || empty($modx->config['check_files_onlogin'])) {
309
            return '0';
310
        }
311
312
        $current = $this->getSystemChecksum($modx->getConfig('check_files_onlogin'));
313
        if (empty($current)) {
314
            return '0';
315
        }
316
317
        if (!isset($modx->config['sys_files_checksum']) || empty($modx->config['sys_files_checksum'])) {
318
            $this->setSystemChecksum($current);
319
320
            return '0';
321
        }
322
        if ($current === $modx->getConfig('sys_files_checksum')) {
323
            $result = '0';
324
        } else {
325
            $result = $this->getModifiedSystemFilesList(
326
                $modx->getConfig('check_files_onlogin'),
327
                $modx->getConfig('sys_files_checksum')
328
            );
329
        }
330
331
        return $result;
332
    }
333
334
    /**
335
     * @param bool|string $key
336
     * @return null|string|array
337
     */
338
    public function getLastUserSetting($key = false)
339
    {
340
        $modx = evolutionCMS();
341
342
        $rs = $modx->getDatabase()->select('*', $modx->getDatabase()->getFullTableName('user_settings'),
343
            "user = '{$_SESSION['mgrInternalKey']}'");
344
345
        $usersettings = array();
346
        while ($row = $modx->getDatabase()->getRow($rs)) {
347
            if (substr($row['setting_name'], 0, 6) == '_LAST_') {
348
                $name = substr($row['setting_name'], 6);
349
                $usersettings[$name] = $row['setting_value'];
350
            }
351
        }
352
353
        if ($key === false) {
354
            return $usersettings;
355
        } else {
356
            return isset($usersettings[$key]) ? $usersettings[$key] : null;
357
        }
358
    }
359
360
    /**
361
     * @param array $settings
362
     * @param string $val
363
     */
364
    public function saveLastUserSetting($settings, $val = '')
365
    {
366
        $modx = evolutionCMS();
367
368
        if (!empty($settings)) {
369
            if (!is_array($settings)) {
370
                $settings = array($settings => $val);
371
            }
372
373
            foreach ($settings as $key => $val) {
374
                $f = array();
375
                $f['user'] = $_SESSION['mgrInternalKey'];
376
                $f['setting_name'] = '_LAST_' . $key;
377
                $f['setting_value'] = $val;
378
                $f = $modx->getDatabase()->escape($f);
379
                $f = "(`" . implode("`, `", array_keys($f)) . "`) VALUES('" . implode("', '", array_values($f)) . "')";
380
                $f .= " ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)";
381
                $modx->getDatabase()->insert($f, $modx->getDatabase()->getFullTableName('user_settings'));
382
            }
383
        }
384
    }
385
386
    /**
387
     * @param $path
388
     * @return string
389
     */
390
    public function loadDatePicker($path)
391
    {
392
        $modx = evolutionCMS();
393
        include_once($path);
394
        $dp = new \DATEPICKER();
395
396
        return $modx->mergeSettingsContent($dp->getDP());
397
    }
398
}
399