Test Failed
Push — master ( dfbb6d...5d1429 )
by Alexey
04:49
created

Tools::createDir()   B

Complexity

Conditions 5
Paths 7

Size

Total Lines 18
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
cc 5
eloc 13
nc 7
nop 1
dl 0
loc 18
ccs 0
cts 14
cp 0
crap 30
rs 8.8571
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * Tools object
5
 *
6
 * Toolkit with most needed functions
7
 *
8
 * @author Alexey Krupskiy <[email protected]>
9
 * @link http://inji.ru/
10
 * @copyright 2015 Alexey Krupskiy
11
 * @license https://github.com/injitools/cms-Inji/blob/master/LICENSE
12
 */
13
class Tools extends Model {
14
15
    /**
16
     * Return random string
17
     *
18
     * @param int $length
19
     * @param string $characters
20
     * @return string
21
     */
22
    public static function randomString($length = 20, $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') {
23
        $charactersLength = strlen($characters);
24
        $randomString = '';
25
        for ($i = 0; $i < $length; $i++) {
26
            $randomString .= $characters[rand(0, $charactersLength - 1)];
27
        }
28
        return $randomString;
29
    }
30
31
    /**
32
     * Clean and return user query params
33
     *
34
     * @param string $uri
35
     * @return array
36
     */
37
    public static function uriParse($uri) {
38
        $answerPos = strpos($uri, '?');
39
        $params = array_slice(explode('/', substr($uri, 0, $answerPos ? $answerPos : strlen($uri))), 1);
40
41
        foreach ($params as $key => $param) {
42
            if ($param != '') {
43
                $params[$key] = urldecode($param);
44
            } else {
45
                unset($params[$key]);
46
            }
47
        }
48
        return $params;
49
    }
50
51
    /**
52
     * Recursive create dir
53
     *
54
     * @param string $path
55
     * @return boolean
56
     */
57
    public static function createDir($path) {
58
        if (file_exists($path)) {
59
            return true;
60
        }
61
        $root = rtrim(str_replace(DIRECTORY_SEPARATOR, '/', $_SERVER['DOCUMENT_ROOT']), '/') . '/';
62
        if (strpos($path, $root) === 0) {
63
            $path = str_replace($root, '', $path);
64
        }
65
        $path = explode('/', $path);
66
        $cur = '';
67
        foreach ($path as $item) {
68
            $cur .= $item . '/';
69
            if (!file_exists($cur)) {
70
                mkdir($cur);
71
            }
72
        }
73
        return true;
74
    }
75
76
    public static function delDir($dir) {
77
        $files = array_diff(scandir($dir), array('.', '..'));
78
        foreach ($files as $file) {
79
            is_dir("$dir/$file") ? self::delDir("$dir/$file") : unlink("$dir/$file");
80
        }
81
        return rmdir($dir);
82
    }
83
84
    /**
85
     * Resize image in path
86
     *
87
     * @param string $img_path
88
     * @param int $max_width
89
     * @param int $max_height
90
     * @param string|false $crop
91
     * @param string $pos
92
     * @return string
93
     */
94
    public static function resizeImage($img_path, $max_width = 1000, $max_height = 1000, $crop = false, $pos = 'center') {
95
        ini_set("gd.jpeg_ignore_warning", 1);
96
        list($img_width, $img_height, $img_type, $img_tag) = getimagesize($img_path);
97
        switch ($img_type) {
98
            case 1:
99
                $img_type = 'gif';
100
                break;
101
            case 3:
102
                $img_type = 'png';
103
                break;
104
            case 2:
105
            default:
106
                $img_type = 'jpeg';
107
                break;
108
        }
109
        $imagecreatefromX = "imagecreatefrom{$img_type}";
110
        $src_res = $imagecreatefromX($img_path);
111
        if (!$src_res) {
112
            return false;
113
        }
114
115
        if ($img_width / $max_width > $img_height / $max_height) {
116
            $separator = $img_width / $max_width;
117
        } else {
118
            $separator = $img_height / $max_height;
119
        }
120
121
        if ($crop === true || $crop == 'q') {
122
            if ($img_width > $img_height) {
123
                $imgX = floor(($img_width - $img_height) / 2);
124
                $imgY = 0;
125
                $img_width = $img_height;
126
                $new_width = $max_width;
127
                $new_height = $max_height;
128 View Code Duplication
            } else {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
129
                $imgX = 0;
130
                $imgY = floor(($img_height - $img_width) / 2);
131
                $img_height = $img_width;
132
                $new_width = $max_width;
133
                $new_height = $max_height;
134
            }
135
            if ($pos == 'top') {
136
                $imgY = 0;
137
            }
138
        } elseif ($crop == 'c') {
139
//Вычисляем некий коэффициент масштабирования
140
            $k1 = $img_width / $max_width;
141
            $k2 = $img_height / $max_height;
142
            $k = $k1 > $k2 ? $k2 : $k1;
143
            $ow = $img_width;
144
            $oh = $img_height;
145
//Вычисляем размеры области для нового изображения
146
            $img_width = intval($max_width * $k);
147
            $img_height = intval($max_height * $k);
148
            $new_width = $max_width;
149
            $new_height = $max_height;
150
//Находим начальные координаты (центрируем новое изображение)
151
            $imgX = (int)(($ow / 2) - ($img_width / 2));
152
            if ($pos == 'center') {
153
                $imgY = (int)(($oh / 2) - ($img_height / 2));
154
            } else {
155
                $imgY = 0;
156
            }
157 View Code Duplication
        } else {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
158
            $imgX = 0;
159
            $imgY = 0;
160
            $new_width = floor($img_width / $separator);
161
            $new_height = floor($img_height / $separator);
162
        }
163
164
        $new_res = imagecreatetruecolor($new_width, $new_height);
165
        imageAlphaBlending($new_res, false);
166
        imagesavealpha($new_res, true);
167
        imagecopyresampled($new_res, $src_res, 0, 0, $imgX, $imgY, $new_width, $new_height, $img_width, $img_height);
168
169
        if ($img_type == 'jpeg') {
170
            imageinterlace($new_res, 1); // чересстрочное формирование изображение
171
            imagejpeg($new_res, $img_path, 85);
172
        } else {
173
            $imageX = "image{$img_type}";
174
            $imageX($new_res, $img_path);
175
        }
176
177
        imagedestroy($new_res);
178
        imagedestroy($src_res);
179
        return $img_type;
180
    }
181
182
    /**
183
     * Send mail
184
     *
185
     * @param string $from
186
     * @param string $to
187
     * @param string $subject
188
     * @param string $text
189
     * @param string $charset
190
     * @param string $ctype
191
     * @return boolean
192
     */
193
    public static function sendMail($from, $to, $subject, $text, $charset = 'utf-8', $ctype = 'text/html') {
194
        $msg = compact('from', 'to', 'subject', 'text', 'charset', 'ctype');
195
        $msg = Inji::$inst->event('sendMail', $msg);
196
        if (is_array($msg)) {
197
            $headers = "From: {$msg['from']}\r\n";
198
            $headers .= "Content-type: {$msg['ctype']}; charset={$msg['charset']}\r\n";
199
            $headers .= "Mime-Version: 1.0\r\n";
200
            return mail($msg['to'], $msg['subject'], $msg['text'], $headers);
201
        }
202
        return $msg;
203
    }
204
205
    /**
206
     * Redirect user from any place of code
207
     *
208
     * Also add message to message query for view
209
     *
210
     * @param string $href
211
     * @param string $text
212
     * @param string $status
213
     */
214
    public static function redirect($href = null, $text = false, $status = 'info') {
215
        if ($href === null) {
216
            $href = $_SERVER['REQUEST_URI'];
217
        }
218
        if ($text !== false) {
219
            Msg::add($text, $status);
220
        }
221
        if (!headers_sent()) {
222
            header("Location: {$href}");
223
        } else {
224
            echo '\'"><script>window.location="' . $href . '";</script>';
225
        }
226
        exit("Перенаправление на: <a href = '{$href}'>{$href}</a>");
227
    }
228
229
    /**
230
     * Функция возвращает окончание для множественного числа слова на основании числа и массива окончаний
231
     * @param  Integer $number Число на основе которого нужно сформировать окончание
232
     * @param  String[] $endingArray Массив слов или окончаний для чисел (1, 4, 5),
233
     *         например ['яблоко', 'яблока', 'яблок']
234
     * @return String
235
     */
236
    public static function getNumEnding($number, $endingArray) {
237
        $number = $number % 100;
238
        if ($number >= 11 && $number <= 19) {
239
            $ending = $endingArray[2];
240
        } else {
241
            $i = $number % 10;
242
            switch ($i) {
243
                case (1):
244
                    $ending = $endingArray[0];
245
                    break;
246
                case (2):
247
                case (3):
248
                case (4):
249
                    $ending = $endingArray[1];
250
                    break;
251
                default:
252
                    $ending = $endingArray[2];
253
            }
254
        }
255
        return $ending;
256
    }
257
258
    /**
259
     * Clean request path
260
     *
261
     * @param string $path
262
     * @return string
263
     */
264
    public static function parsePath($path) {
265
        $path = str_replace('\\', '/', $path);
266
        $pathArray = explode('/', $path);
267
        $cleanPathArray = [];
268
        do {
269
            $changes = 0;
270
            foreach ($pathArray as $pathItem) {
271
                if (trim($pathItem) === '' || $pathItem == '.') {
272
                    $changes++;
273
                    continue;
274
                }
275
                if ($pathItem == '..') {
276
                    array_pop($cleanPathArray);
277
                    $changes++;
278
                    continue;
279
                }
280
                $cleanPathArray[] = $pathItem;
281
            }
282
            $pathArray = $cleanPathArray;
283
            $cleanPathArray = [];
284
        } while ($changes);
285
        return (strpos($path, '/') === 0 ? '/' : '') . implode('/', $pathArray);
286
    }
287
288
    /**
289
     * Show date in rus
290
     *
291
     * @param string $date
292
     * @return string
293
     */
294
    public static function toRusDate($date) {
295
        $yy = (int)substr($date, 0, 4);
296
        $mm = (int)substr($date, 5, 2);
297
        $dd = (int)substr($date, 8, 2);
298
299
        $hours = substr($date, 11, 5);
300
301
        $month = array('января', 'февраля', 'марта', 'апреля', 'мая', 'июня', 'июля', 'августа', 'сентября', 'октября', 'ноября', 'декабря');
302
        if (empty($month[$mm - 1])) {
303
            return 'Не указано';
304
        }
305
        return ($dd > 0 ? $dd . " " : '') . $month[$mm - 1] . " " . $yy . " " . $hours;
306
    }
307
308
    /**
309
     * Set header
310
     *
311
     * @param string $code
312
     * @param boolean $exit
313
     */
314
    public static function header($code, $exit = false) {
315
        if (!headers_sent()) {
316
            switch ($code) {
317
                case '404':
318
                    header('HTTP/1.1 404 Not Found');
319
                    break;
320
                default:
321
                    header($code);
322
            }
323
        }
324
        if ($exit) {
325
            exit;
326
        }
327
    }
328
329
    /**
330
     * Return exist path from array
331
     *
332
     * If no exist path in array - return default
333
     *
334
     * @param array $paths
335
     * @param string|boolean $default
336
     * @return string|boolean
337
     */
338
    public static function pathsResolve($paths = [], $default = false) {
339
        foreach ($paths as $path) {
340
            if (file_exists($path)) {
341
                return $path;
342
            }
343
        }
344
        return $default;
345
    }
346
347
    /**
348
     * Convert acronyms to bites
349
     *
350
     * @param string $val
351
     * @return int
352
     */
353
    public static function toBytes($val) {
354
        $val = trim($val);
355
        $last = strtolower($val[strlen($val) - 1]);
356
        switch ($last) {
357
            case 'g':
358
                $val *= 1024;
359
            // no break
360
            case 'm':
361
                $val *= 1024;
362
            // no break
363
            case 'k':
364
                $val *= 1024;
365
        }
366
367
        return $val;
368
    }
369
370
    /**
371
     * Recursive copy directories and files
372
     *
373
     * @param string $from
374
     * @param string $to
375
     */
376
    public static function copyFiles($from, $to) {
377
        $from = rtrim($from, '/');
378
        $to = rtrim($to, '/');
379
        self::createDir($to);
380
        $files = scandir($from);
381
        foreach ($files as $file) {
382
            if (in_array($file, ['.', '..'])) {
383
                continue;
384
            }
385
            if (is_dir($from . '/' . $file)) {
386
                self::copyFiles($from . '/' . $file, $to . '/' . $file);
387
            } else {
388
                copy($from . '/' . $file, $to . '/' . $file);
389
            }
390
        }
391
    }
392
393
    /**
394
     * Translit function
395
     *
396
     * @param string $str
397
     * @return string
398
     */
399
    public static function translit($str) {
400
        $rus = array('А', 'Б', 'В', 'Г', 'Д', 'Е', 'Ё', 'Ж', 'З', 'И', 'Й', 'К', 'Л', 'М', 'Н', 'О', 'П', 'Р', 'С', 'Т', 'У', 'Ф', 'Х', 'Ц', 'Ч', 'Ш', 'Щ', 'Ъ', 'Ы', 'Ь', 'Э', 'Ю', 'Я', 'а', 'б', 'в', 'г', 'д', 'е', 'ё', 'ж', 'з', 'и', 'й', 'к', 'л', 'м', 'н', 'о', 'п', 'р', 'с', 'т', 'у', 'ф', 'х', 'ц', 'ч', 'ш', 'щ', 'ъ', 'ы', 'ь', 'э', 'ю', 'я');
401
        $lat = array('A', 'B', 'V', 'G', 'D', 'E', 'E', 'Gh', 'Z', 'I', 'Y', 'K', 'L', 'M', 'N', 'O', 'P', 'R', 'S', 'T', 'U', 'F', 'H', 'C', 'Ch', 'Sh', 'Sch', 'Y', 'Y', 'Y', 'E', 'Yu', 'Ya', 'a', 'b', 'v', 'g', 'd', 'e', 'e', 'gh', 'z', 'i', 'y', 'k', 'l', 'm', 'n', 'o', 'p', 'r', 's', 't', 'u', 'f', 'h', 'c', 'ch', 'sh', 'sch', 'y', 'y', 'y', 'e', 'yu', 'ya');
402
        return str_replace($rus, $lat, $str);
403
    }
404
405
    /**
406
     * get youtube video ID from URL
407
     *
408
     * @author http://stackoverflow.com/a/6556662
409
     * @param string $url
410
     * @return string Youtube video id or FALSE if none found.
411
     */
412
    public static function youtubeIdFromUrl($url) {
413
        $pattern = '%^# Match any youtube URL
414
        (?:https?://)?  # Optional scheme. Either http or https
415
        (?:www\.)?      # Optional www subdomain
416
        (?:             # Group host alternatives
417
          youtu\.be/    # Either youtu.be,
418
        | youtube\.com  # or youtube.com
419
          (?:           # Group path alternatives
420
            /embed/     # Either /embed/
421
          | /v/         # or /v/
422
          | /watch\?v=  # or /watch\?v=
423
          )             # End path alternatives.
424
        )               # End host alternatives.
425
        ([\w-]{10,12})  # Allow 10-12 for 11 char youtube id.
426
        $%x';
427
        $result = preg_match($pattern, $url, $matches);
428
        if (false !== $result) {
429
            return $matches[1];
430
        }
431
        return false;
432
    }
433
434
    /**
435
     * check array is associative
436
     *
437
     * @author http://stackoverflow.com/a/173479
438
     * @param array $arr
439
     * @return boolean
440
     */
441
    public static function isAssoc(&$arr) {
442
        return array_keys($arr) !== range(0, count($arr) - 1);
443
    }
444
}