APIhelpers::getEnv()   A
last analyzed

Complexity

Conditions 6
Paths 5

Size

Total Lines 21
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 0
Metric Value
eloc 17
c 0
b 0
f 0
dl 0
loc 21
ccs 0
cts 17
cp 0
rs 9.0777
cc 6
nc 5
nop 1
crap 42
1
<?php
2
3
/**
4
 * Class APIhelpers
5
 */
6
if (!class_exists('APIhelpers')) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after NOT operator; 0 found
Loading history...
7
8
class APIhelpers
9
{
10
11
    /**
12
     * Преобразует первый символ в нижний регистр
13
     * @param $str
14
     * @param string $encoding - кодировка, по-умолчанию UTF-8
15
     * @return string
16
     */
17
    public static function mb_lcfirst($str, $encoding = 'UTF-8')
0 ignored issues
show
Coding Style introduced by
Method name "APIhelpers::mb_lcfirst" is not in camel caps format
Loading history...
Coding Style introduced by
This method is not in camel caps format.

This check looks for method names that are not written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection seeker becomes databaseConnectionSeeker.

Loading history...
18
    {
19
        return mb_strtolower(mb_substr($str, 0, 1, $encoding), $encoding) . mb_substr(
20
            $str,
21
            1,
22
            mb_strlen($str),
23
            $encoding
24
        );
25
    }
26
27
    /**
28
     * mb_ucfirst - преобразует первый символ в верхний регистр
29
     * @param string $str - строка
30
     * @param string $encoding - кодировка, по-умолчанию UTF-8
31
     * @return string
32
     */
33
    public static function mb_ucfirst($str, $encoding = 'UTF-8')
0 ignored issues
show
Coding Style introduced by
Method name "APIhelpers::mb_ucfirst" is not in camel caps format
Loading history...
Coding Style introduced by
This method is not in camel caps format.

This check looks for method names that are not written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection seeker becomes databaseConnectionSeeker.

Loading history...
34
    {
35
        $str = mb_ereg_replace('^[\ ]+', '', $str);
36
        $str = mb_strtoupper(mb_substr($str, 0, 1, $encoding), $encoding) . mb_substr(
37
            $str,
38
            1,
39
            mb_strlen($str),
40
            $encoding
41
        );
42
43
        return $str;
44
    }
45
46
    /**
47
     * Обрезание текста по длине с поиском последнего полностью вмещающегося слова и удалением лишних крайних знаков пунктуации.
48
     *
49
     * @author Agel_Nash <[email protected]>
50
     * @version 0.1
51
     *
52
     * @param string $html HTML текст
53
     * @param integer $len максимальная длина строки
54
     * @param string $encoding кодировка
55
     * @return string
56
     */
57
    public static function mb_trim_word($html, $len, $encoding = 'UTF-8')
0 ignored issues
show
Coding Style introduced by
Method name "APIhelpers::mb_trim_word" is not in camel caps format
Loading history...
Coding Style introduced by
This method is not in camel caps format.

This check looks for method names that are not written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection seeker becomes databaseConnectionSeeker.

Loading history...
58
    {
59
        $text = trim(preg_replace('|\s+|', ' ', strip_tags($html)));
60
        $text = mb_substr($text, 0, $len + 1, $encoding);
61
        if (mb_substr($text, -1, null, $encoding) == ' ') {
62
            $out = trim($text);
63
        } else {
64
            $out = mb_substr($text, 0, mb_strripos($text, ' ', null, $encoding), $encoding);
0 ignored issues
show
Bug introduced by
null of type null is incompatible with the type integer expected by parameter $offset of mb_strripos(). ( Ignorable by Annotation )

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

64
            $out = mb_substr($text, 0, mb_strripos($text, ' ', /** @scrutinizer ignore-type */ null, $encoding), $encoding);
Loading history...
65
        }
66
67
        return preg_replace("/(([\.,\-:!?;\s])|(&\w+;))+$/ui", "", $out);
68
    }
69
70
    /**
71
     * Получение значения по ключу из массива, либо возврат значения по умолчанию
72
     *
73
     * @param mixed $data массив
74
     * @param string $key ключ массива
75
     * @param mixed $default null значение по умолчанию
76
     * @param Closure $validate null функция дополнительной валидации значения (должна возвращать true или false)
77 72
     * @return mixed
78
     */
79 72
    public static function getkey($data, $key, $default = null, $validate = null)
80 72
    {
81 72
        $out = $default;
82 72
        if (is_array($data) && (is_int($key) || is_string($key)) && $key !== '' && array_key_exists($key, $data)) {
83 72
            $out = $data[$key];
84
        }
85
        if (! empty($validate) && is_callable($validate)) {
86 72
            $out = (($validate($out) === true) ? $out : $default);
87
        }
88
89
        return $out;
90
    }
91
92
    /**
93
     * Email validate
94
     *
95
     * @category   validate
96
     * @version    0.1
97
     * @license    GNU General Public License (GPL), http://www.gnu.org/copyleft/gpl.html
98
     * @param string $email проверяемый email
99
     * @param boolean $dns проверять ли DNS записи
100
     * @return boolean|string Результат проверки почтового ящика
101
     * @author Anton Shevchuk
102
     */
103
    public static function emailValidate($email, $dns = true)
104
    {
105
        if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
106
            list(, $domain) = explode("@", $email, 2);
107
            if (! $dns || ($dns && checkdnsrr($domain, "MX") && checkdnsrr($domain, "A"))) {
108
                $error = false;
109
            } else {
110
                $error = 'dns';
111
            }
112
        } else {
113
            $error = 'format';
114
        }
115
116
        return $error;
117
    }
118
119
    /**
120
     * Password generate
121
     *
122
     * @category   generate
123
     * @version   0.1
124
     * @license    GNU General Public License (GPL), http://www.gnu.org/copyleft/gpl.html
125
     * @param string $len длина пароля
126
     * @param string $data правила генерации пароля
127
     * @return string Строка с паролем
128
     * @author Agel_Nash <[email protected]>
129
     *
130
     * Расшифровка значений $data
131
     * "A": A-Z буквы
132
     * "a": a-z буквы
133
     * "0": цифры
134
     * ".": все печатные символы
135
     *
136
     * @example
137
     * $this->genPass(10,"Aa"); //nwlTVzFdIt
138
     * $this->genPass(8,"0"); //71813728
139
     * $this->genPass(11,"A"); //VOLRTMEFAEV
140
     * $this->genPass(5,"a0"); //4hqi7
141
     * $this->genPass(5,"."); //2_Vt}
142
     * $this->genPass(20,"."); //AMV,>&?J)v55,(^g}Z06
143
     * $this->genPass(20,"aaa0aaa.A"); //rtvKja5xb0\KpdiRR1if
144
     */
145
    public static function genPass($len, $data = '')
146
    {
147
        if ($data == '') {
148
            $data = 'Aa0.';
149
        }
150
        $opt = strlen($data);
151
        $pass = array();
152
153
        for ($i = $len; $i > 0; $i--) {
154
            switch ($data[rand(0, ($opt - 1))]) {
155
                case 'A':
156
                    $tmp = rand(65, 90);
157
                    break;
158
                case 'a':
159
                    $tmp = rand(97, 122);
160
                    break;
161
                case '0':
162
                    $tmp = rand(48, 57);
163
                    break;
164
                default:
165
                    $tmp = rand(33, 126);
166
            }
167
            $pass[] = chr($tmp);
168
        }
169
        $pass = implode("", $pass);
170
171
        return $pass;
172
    }
173
174
    /**
175
     * @param $data
176
     * @return bool|false|string
177
     */
178
    public static function getEnv($data)
179
    {
180
        switch (true) {
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing $tmp = getenv($data) of type string to the boolean true. If you are specifically checking for a non-empty string, consider using the more explicit !== '' instead.
Loading history...
181
            case (isset($_SERVER[$data])):
182
                $out = $_SERVER[$data];
183
                break;
184
            case (isset($_ENV[$data])):
185
                $out = $_ENV[$data];
186
                break;
187
            case ($tmp = getenv($data)):
188
                $out = $tmp;
189
                break;
190
            case (function_exists('apache_getenv') && $tmp = apache_getenv($data, true)):
191
                $out = $tmp;
192
                break;
193
            default:
194
                $out = false;
195
        }
196
        unset($tmp);
197
198
        return $out;
199
    }
200
201
    /**
202
     * User IP
203
     *
204
     * @category   validate
205
     * @version   0.1
206
     * @license    GNU General Public License (GPL), http://www.gnu.org/copyleft/gpl.html
207
     * @param string $default IP адрес который будет отдан функцией, если больше ничего не обнаружено
208
     * @return string IP пользователя
209
     * @author Agel_Nash <[email protected]>
210
     *
211
     * @see http://stackoverflow.com/questions/5036443/php-how-to-block-proxies-from-my-site
212
     */
213
    public static function getUserIP($default = '127.0.0.1')
0 ignored issues
show
Coding Style introduced by
This method is not in camel caps format.

This check looks for method names that are not written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection seeker becomes databaseConnectionSeeker.

Loading history...
214
    {
215
        //Порядок условий зависит от приоритетов
216
        switch (true) {
217
            case ($tmp = self::getEnv('HTTP_COMING_FROM')):
218
                $out = $tmp;
219
                break;
220
            case ($tmp = self::getEnv('HTTP_X_COMING_FROM')):
221
                $out = $tmp;
222
                break;
223
            case ($tmp = self::getEnv('HTTP_VIA')):
224
                $out = $tmp;
225
                break;
226
            case ($tmp = self::getEnv('HTTP_FORWARDED')):
227
                $out = $tmp;
228
                break;
229
            case ($tmp = self::getEnv('HTTP_FORWARDED_FOR')):
230
                $out = $tmp;
231
                break;
232
            case ($tmp = self::getEnv('HTTP_X_FORWARDED')):
233
                $out = $tmp;
234
                break;
235
            case ($tmp = self::getEnv('HTTP_X_FORWARDED_FOR')):
236
                $out = $tmp;
237
                break;
238
            case (! empty($_SERVER['REMOTE_ADDR'])):
239
                $out = $_SERVER['REMOTE_ADDR'];
240
                break;
241
            default:
242
                $out = false;
243
        }
244
        unset($tmp);
245
246
        return (false !== $out && preg_match('|^(?:[0-9]{1,3}\.){3,3}[0-9]{1,3}$|', $out, $matches)) ? $out : $default;
247
    }
248
249
    /**
250
     * @param $data
251
     * @param string $charset
252 61
     * @param array $chars
253
     * @return array|mixed|string
254
     */
255
    public static function sanitarTag(
256
        $data,
257
        $charset = 'UTF-8',
258
        $chars = array(
259
            '['   => '&#91;',
260
            '%5B' => '&#91;',
261
            ']'   => '&#93;',
262
            '%5D' => '&#93;',
263
            '{'   => '&#123;',
264
            '%7B' => '&#123;',
265
            '}'   => '&#125;',
266
            '%7D' => '&#125;',
267
            '`'   => '&#96;',
268
            '%60' => '&#96;'
269 61
        )
270 61
    ) {
271 61
        switch (true) {
272 61
            case is_scalar($data):
273 61
                $out = str_replace(
274 61
                    array_keys($chars),
275 61
                    array_values($chars),
276 3
                    $charset === null ? $data : self::e($data, $charset)
0 ignored issues
show
introduced by
The condition $charset === null is always false.
Loading history...
277 2
                );
278 2
                break;
279 2
            case is_array($data):
280 2
                $out = array();
281 2
                foreach ($data as $key => $val) {
282 2
                    $key = self::sanitarTag($key, $charset, $chars);
283 1
                    $out[$key] = self::sanitarTag($val, $charset, $chars);
284 1
                }
285 1
                break;
286
            default:
287 61
                $out = '';
288
        }
289
290
        return $out;
291
    }
292
293
    /**
294
     * @param $text
295 58
     * @param string $charset
296
     * @return string
297 58
     */
298
    public static function e($text, $charset = 'UTF-8')
299
    {
300
        return is_scalar($text) ? htmlspecialchars($text, ENT_QUOTES, $charset, false) : '';
301
    }
302
303
    /**
304
     * Проверка строки на наличе запрещенных символов
305
     * Проверка конечно круто, но валидация русских символов в строке порой завершается не удачей по разным причинам
306
     * (начиная от кривых настроек сервера и заканчивая кривыми настройками кодировки на сайте)
307
     *
308
     * @param string $value Проверяемая строка
309
     * @param int $minLen Минимальная длина строки
310
     * @param array $alph Разрешенные алфавиты
311
     * @param array $mixArray Примесь символов, которые так же могут использоваться в строке
312
     * @return bool
313
     */
314
    public static function checkString($value, $minLen = 1, $alph = array(), $mixArray = array())
0 ignored issues
show
Coding Style introduced by
Function's nesting level (5) exceeds 3; consider refactoring the function
Loading history...
315
    {
316
        $flag = true;
317
        $len = mb_strlen($value, 'UTF-8');
318
        $value = trim($value);
319
        if (mb_strlen($value, 'UTF-8') == $len) {
320
            $data = is_array($mixArray) ? $mixArray : array();
0 ignored issues
show
introduced by
The condition is_array($mixArray) is always true.
Loading history...
321
            $alph = is_array($alph) ? array_unique($alph) : array();
0 ignored issues
show
introduced by
The condition is_array($alph) is always true.
Loading history...
322
            foreach ($alph as $item) {
323
                $item = strtolower($item);
324
                switch ($item) {
325
                    case 'rus':
326
                        $data = array_merge($data, array(
327
                            'А',
328
                            'Б',
329
                            'В',
330
                            'Г',
331
                            'Д',
332
                            'Е',
333
                            'Ё',
334
                            'Ж',
335
                            'З',
336
                            'И',
337
                            'Й',
338
                            'К',
339
                            'Л',
340
                            'М',
341
                            'Н',
342
                            'О',
343
                            'П',
344
                            'Р',
345
                            'С',
346
                            'Т',
347
                            'У',
348
                            'Ф',
349
                            'Х',
350
                            'Ц',
351
                            'Ч',
352
                            'Ш',
353
                            'Щ',
354
                            'Ъ',
355
                            'Ы',
356
                            'Ь',
357
                            'Э',
358
                            'Ю',
359
                            'Я'
360
                        ));
361
                        break;
362
                    case 'num':
363
                        $tmp = range('0', '9');
364
                        foreach ($tmp as $t) {
365
                            $data[] = (string)$t;
366
                        }
367
                        break;
368
                    case 'eng':
369
                        $data = array_merge($data, range('A', 'Z'));
370
                        break;
371
                }
372
            }
373
            for ($i = 0; $i < $len; $i++) {
374
                $chr = mb_strtoupper(mb_substr($value, $i, 1, 'UTF-8'), 'UTF-8');
375
                if (!in_array($chr, $data, true)) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after NOT operator; 0 found
Loading history...
376
                    $flag = false;
377
                    break;
378
                }
379
            }
380
            $flag = ($flag && $len >= $minLen);
381
        } else {
382
            $flag = false;
383
        }
384
385
        return $flag;
386
    }
387
388
    /**
389
     * @param $IDs
390
     * @param string $sep
391
     * @param integer[] $ignore
392 5
     * @return array
393
     * @throws Exception
394 5
     */
395 5
    public static function cleanIDs($IDs, $sep = ',', $ignore = array())
0 ignored issues
show
Coding Style introduced by
This method is not in camel caps format.

This check looks for method names that are not written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection seeker becomes databaseConnectionSeeker.

Loading history...
396 5
    {
397 4
        $out = [];
398 4
        if (!is_array($IDs)) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after NOT operator; 0 found
Loading history...
399 1
            if (is_scalar($IDs)) {
400 1
                $IDs = explode($sep, $IDs);
401
            } else {
402 4
                $IDs = [];
403 4
            }
404 4
        }
405 4
        foreach ($IDs as $item) {
406 4
            if (is_scalar($item) && (int)$item >= 0) { //Fix 0xfffffffff
407 4
                $item = (int)$item;
408 4
                if (empty($ignore) || !\in_array($item, $ignore, true)) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after NOT operator; 0 found
Loading history...
409 4
                    $out[] = $item;
410 4
                }
411 4
            }
412
        }
413 4
        $out = array_unique($out);
414
415
        return $out;
416
    }
417
418
    /**
419
     * Предварительная обработка данных перед вставкой в SQL запрос вида IN
420
     * Если данные в виде строки, то происходит попытка сформировать массив из этой строки по разделителю $sep
421
     * Точно по тому, по которому потом данные будут собраны обратно
422
     *
423
     * @param integer|string|array $data данные для обработки
424
     * @param string $sep разделитель
425
     * @param boolean $quote заключать ли данные на выходе в кавычки
426 59
     * @return string обработанная строка
427
     */
428 59
    public static function sanitarIn($data, $sep = ',', $quote = true)
429 59
    {
430 1
        $modx = evolutionCMS();
0 ignored issues
show
Bug introduced by
The function evolutionCMS was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

430
        $modx = /** @scrutinizer ignore-call */ evolutionCMS();
Loading history...
431 1
        if (is_scalar($data)) {
432 58
            $data = explode($sep, $data);
433 58
        }
434 58
        if (!is_array($data)) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after NOT operator; 0 found
Loading history...
introduced by
The condition is_array($data) is always true.
Loading history...
435 58
            $data = array(); //@TODO: throw
436 58
        }
437
438 58
        $out = array();
439 58
        foreach ($data as $item) {
440 58
            if ($item !== '') {
441
                $out[] = $modx->db->escape($item);
442
            }
443
        }
444
        $q = $quote ? "'" : "";
445
        $out = $q . implode($q . "," . $q, $out) . $q;
446
447 58
        return $out;
448 58
    }
449
450
    /**
451 59
     * Переменовывание элементов массива
452
     *
453
     * @param array $data массив с данными
454
     * @param string $prefix префикс ключей
455
     * @param string $suffix суффикс ключей
456
     * @param string $addPS разделитель суффиксов, префиксов и ключей массива
457
     * @param string $sep разделитель ключей при склейке многомерных массивов
458
     * @return array массив с переименованными ключами
459
     */
460
    public static function renameKeyArr($data, $prefix = '', $suffix = '', $addPS = '.', $sep = '.')
0 ignored issues
show
Coding Style introduced by
Function's nesting level (4) exceeds 3; consider refactoring the function
Loading history...
461
    {
462
        $out = array();
463
        if ($prefix == '' && $suffix == '') {
464
            $out = $data;
465
        } else {
466
            $InsertPrefix = ($prefix != '') ? ($prefix . $addPS) : '';
467
            $InsertSuffix = ($suffix != '') ? ($addPS . $suffix) : '';
468
            foreach ($data as $key => $item) {
469
                $key = $InsertPrefix . $key;
470
                $val = null;
471
                switch (true) {
472
                    case is_scalar($item):
473
                        $val = $item;
474
                        break;
475
                    case is_array($item):
476
                        $val = self::renameKeyArr($item, $key . $sep, $InsertSuffix, '', $sep);
477
                        $out = array_merge($out, $val);
478
                        $val = '';
479
                        break;
480
                }
481
                $out[$key . $InsertSuffix] = $val;
482
            }
483
        }
484
485
        return $out;
486
    }
487
}
488
489
}
490