Utils2.php ➔ array_power_set()   B
last analyzed

Complexity

Conditions 6
Paths 6

Size

Total Lines 21
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 0
Metric Value
cc 6
eloc 10
nc 6
nop 2
dl 0
loc 21
ccs 0
cts 12
cp 0
crap 42
rs 8.7624
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * Get difference time entities between two dates
5
 *
6
 * @param string $enddate
7
 * @param string $startdate If no starting date is specified - current timestamp is used
8
 *
9
 * @return array Array of dirrence date entities( years, month, days, hours, minutes )
10
 */
11
function time_difference($enddate, $startdate = null)
12
{
13
    // Get current timestamp
14
    if (!isset($startdate)) $startdate = time();
0 ignored issues
show
Coding Style Best Practice introduced by
It is generally a best practice to always use braces with control structures.

Adding braces to control structures avoids accidental mistakes as your code changes:

// Without braces (not recommended)
if (true)
    doSomething();

// Recommended
if (true) {
    doSomething();
}
Loading history...
15
    else $startdate = strtotime($startdate);
0 ignored issues
show
Coding Style Best Practice introduced by
It is generally a best practice to always use braces with control structures.

Adding braces to control structures avoids accidental mistakes as your code changes:

// Without braces (not recommended)
if (true)
    doSomething();

// Recommended
if (true) {
    doSomething();
}
Loading history...
16
17
    // Difference in miliseconds
18
    $difference = strtotime($enddate) - $startdate;
19
20
    // Different time delimeters for calculations
21
    $minutes_delimeter = 60;
22
    $hours_delimeter = $minutes_delimeter * 60;
23
    $days_delimiter = $hours_delimeter * 24;
24
    $month_delimiter = $days_delimiter * 30;
25
    $year_delimiter = $month_delimiter * 12;
26
27
    //elapsed($difference.'-'.$year_delimiter.'-'.($difference / $year_delimiter).'-'.round( $difference / $year_delimiter ));
28
29
    // Count time entities
30
    $year = round($difference / $year_delimiter);
31
    $year_ms = $year * $year_delimiter;
32
33
    $month = round(($difference - $year_ms) / $month_delimiter);
34
    $month_ms = abs($month * $month_delimiter);
35
36
    $days = round(($difference - $year_ms - $month_ms) / $days_delimiter);
37
    $days_ms = abs($days * $days_delimiter);
38
39
    $hours = round(($difference - $year_ms - $month_ms - $days_ms) / $hours_delimeter);
40
    $hours_ms = abs($hours * $hours_delimeter);
41
42
    $minutes = round(($difference - $year_ms - $month_ms - $days_ms - $hours_ms) / $minutes_delimeter);
43
    $minutes_ms = abs($minutes * $minutes_delimeter);
0 ignored issues
show
Unused Code introduced by
$minutes_ms is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
44
45
    $seconds = ($difference - $year_ms - $month_ms - $days_ms - $hours_ms - $minutes);
46
47
    // Return time entities
48
    return array(
49
        'year' => $year,
50
        'month' => $month,
51
        'day' => $days,
52
        'hour' => $hours,
53
        'minute' => $minutes,
54
        'second' => $seconds
55
    );
56
}
57
58
/**
59
 * Perform URL replacement in string
60
 *
61
 * @param string $str         Inncoming string
62
 * @param string $replacement Replacement string
63
 *
64
 * @return string Replaced string
65
 */
66
function replace_url($str, $replacement = null)
67
{
68
    if (!isset($replacement)) $replacement = "<a href=\"\\0\" rel=\"nofollow\" target=\"_blank\">\\0</a>";
0 ignored issues
show
Coding Style Best Practice introduced by
It is generally a best practice to always use braces with control structures.

Adding braces to control structures avoids accidental mistakes as your code changes:

// Without braces (not recommended)
if (true)
    doSomething();

// Recommended
if (true) {
    doSomething();
}
Loading history...
69
70
    $pattern = '(?xi)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`\!()\[\]{};:\'".,<>?«»“”‘’]))';
71
72
    return preg_replace("!$pattern!i", $replacement, $str);
73
}
74
75
/**
76
 * Get all possible combinations of array elements
77
 *
78
 * @param array  $array Array for building combinations
79
 * @param string $size  Desired result combination size
80
 *
81
 * @return array Collection of array values combinations
82
 */
83
function array_power_set(array $array, $size = null)
84
{
85
    // initialize by adding the empty set
86
    $results = array(array());
87
88
    foreach ($array as $element) {
89
        foreach ($results as $combination) {
90
            array_push($results, array_merge(array($element), $combination));
91
        }
92
    }
93
94
    // Filter combinations by size if nessesar
95
    $_results = array();
96
    if (isset($size)) foreach ($results as $combination) {
0 ignored issues
show
Coding Style Best Practice introduced by
It is generally a best practice to always use braces with control structures.

Adding braces to control structures avoids accidental mistakes as your code changes:

// Without braces (not recommended)
if (true)
    doSomething();

// Recommended
if (true) {
    doSomething();
}
Loading history...
97
        if (sizeof($combination) == $size) $_results[] = $combination;
0 ignored issues
show
Coding Style Best Practice introduced by
It is generally a best practice to always use braces with control structures.

Adding braces to control structures avoids accidental mistakes as your code changes:

// Without braces (not recommended)
if (true)
    doSomething();

// Recommended
if (true) {
    doSomething();
}
Loading history...
98
    }
99
    // Return original results
100
    else $_results = &$results;
0 ignored issues
show
Coding Style Best Practice introduced by
It is generally a best practice to always use braces with control structures.

Adding braces to control structures avoids accidental mistakes as your code changes:

// Without braces (not recommended)
if (true)
    doSomething();

// Recommended
if (true) {
    doSomething();
}
Loading history...
101
102
    return $_results;
103
}
104
105
/**
106
 * Get only folder structure from path.
107
 * Function can also be used for getting namespace withou classname
108
 * If file name specified in path it will be removed, if no
109
 * filename in path - nothing will happen
110
 *
111
 * @return string Folder structure
112
 */
113
function pathname($path)
114
{
115
    // If win or NS path with slash('\')
116
    if (($p = strrpos($path, __NS_SEPARATOR__)) === false) {
117
        // Get position on last *nix slash
118
        $p = strrpos($path, '/');
119
    }
120
121
    // Cut unnessesary part of the path
122
    return $p !== false ? substr($path, 0, $p) : $path;
123
}
124
125
/**
126
 * Normalize path to *nix style with slash('/'), removing
127
 * double slashes
128
 *
129
 * @param string $path Path to be normalized
130
 *
131
 * @return string Normalized path
132
 */
133
function normalizepath($path)
134
{
135 7
    return str_replace(array('\\\\', '///', '//', '\\'), '/', $path);
136
}
137
138
/**
139
 * Изменить регистр ключей массива, с поддержкой UNICODE
140
 *
141
 * @param array $arr Массив для преобразования ключей
142
 * @param int   $c   Регистр в которой необходимо преобразовать ключи массива
143
 *
144
 * @return array Массив с преобразованными ключами
145
 */
146
function & array_change_key_case_unicode(array $arr, $c = CASE_LOWER)
147
{
148
    // Результирующий массив
149
    $ret = array();
150
151
    // Определим в какой регистр преобразовывать ключи
152
    $c = ($c == CASE_LOWER) ? MB_CASE_LOWER : MB_CASE_UPPER;
153
154
    // Создадим новый массив с преобразованными ключами
155
    foreach ($arr as $k => $v) $ret[mb_convert_case($k, $c, "UTF-8")] = $v;
0 ignored issues
show
Coding Style Best Practice introduced by
It is generally a best practice to always use braces with control structures.

Adding braces to control structures avoids accidental mistakes as your code changes:

// Without braces (not recommended)
if (true)
    doSomething();

// Recommended
if (true) {
    doSomething();
}
Loading history...
156
157
    // Верем полученный массив
158
    return $ret;
159
}
160
161
/**
162
 * Выполнить рекурсивную очистку массива от незаполненый ключей
163
 * с его последующей перенумерацией.
164
 *
165
 * @param array $input Массив для рекурсивной очистки и перенумерации
166
 *
167
 * @return array Перенумерованный очищеный массив
168
 */
169
function array_filter_recursive(array & $input)
170
{
171
    // Переберем полученный массив
172
    // Используем foreach потому что незнаем какой массив
173
    // имеет ли он ключи или только нумерацию
174
    foreach ($input as & $value) {
175
        // Если это подмассив
176
        if (is_array($value)) {
177
            // Выполним углубление в рекурсию и перенумерируем полученный "очищенный" массив
178
            $value = array_values(array_filter_recursive($value));
179
        }
180
    }
181
182
    // Выполним фильтрацию массива от пустых значений
183
    return array_filter($input);
184
}
185
186
/**
187
 * Оберточная функция для print_r только выводит все красиво в HTML
188
 *
189
 * @param string $data Объект для представления
190
 */
191
function print_a($data, $return = FALSE)
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected false, but found FALSE.
Loading history...
192
{
193
    // Преобразуем стандартную функцию вывода массива/объекта для HTML
194
    $out = str_replace(array("\n", " "), array('<br>', '&nbsp;'), print_r($data, TRUE));
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected true, but found TRUE.
Loading history...
195
196
    // Если необходимо вывести результат в поток вывода
197
    if (!$return) echo $out;
0 ignored issues
show
Coding Style Best Practice introduced by
It is generally a best practice to always use braces with control structures.

Adding braces to control structures avoids accidental mistakes as your code changes:

// Without braces (not recommended)
if (true)
    doSomething();

// Recommended
if (true) {
    doSomething();
}
Loading history...
198
199
    // Вернем что получили
200
    return $out;
201
}
202
203
/**
204
 * Обработать шаблон сообщения со специальными маркерами
205
 * для их выделения в нем
206
 *
207
 * @param string $pattern Строка для обработки
208
 * @param array  $args
209
 */
210
function debug_parse_markers($pattern, array & $args = NULL)
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
211
{
212
    // Текущий номер аргумента для подмены
213
    $a_ind = 0;
214
215
    // Сохраним количество аргументов условия
216
    $a_count = sizeof($args);
217
218
    // Текущий отступ в поисковом шаблоне
219
    $l_pos = 0;
220
221
    // Защита от ошибок
222
    if (strlen($pattern) > 0 && $a_count > 0) {
223
        // Выполним циклическую обработку шаблона с поиском маркера
224
        // учитываю позицию предыдкщего маркера
225
        while (($l_pos = strpos($pattern, '##', $l_pos)) !== FALSE) {
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected false, but found FALSE.
Loading history...
226
            // Проверим не вылазит ли индекс аргумента за пределы
227
            if ($a_ind < $a_count) {
228
                // Получим значение для текущего маркера
229
                $a_value = '<b>' . $args[$a_ind++] . '</b>';
230
231
                // Заменим найденный маркер
232
                $pattern = substr_replace($pattern, $a_value, $l_pos, 2);
233
            }
234
        }
235
    }
236
237
    // Вернем результат
238
    return $pattern;
239
}
240
241
/**
242
 * Трассировка сообщения в поток вывода
243
 * Оберточная функция для echo с переходом но новую строку
244
 *
245
 * @param string  $text       Текст для вывода
246
 * @param boolean $totextarea Выводить результат в textarea
247
 */
248
function trace($text = '', $totextarea = false)
249
{
250
    if (!$totextarea) echo '' . print_a($text, TRUE) . '<br>' . "\n";
0 ignored issues
show
Coding Style Best Practice introduced by
It is generally a best practice to always use braces with control structures.

Adding braces to control structures avoids accidental mistakes as your code changes:

// Without braces (not recommended)
if (true)
    doSomething();

// Recommended
if (true) {
    doSomething();
}
Loading history...
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected true, but found TRUE.
Loading history...
251
    else echo '<textarea style="z-index:1000; position:relative;">' . print_r($text, true) . '</textarea>';
0 ignored issues
show
Coding Style Best Practice introduced by
It is generally a best practice to always use braces with control structures.

Adding braces to control structures avoids accidental mistakes as your code changes:

// Without braces (not recommended)
if (true)
    doSomething();

// Recommended
if (true) {
    doSomething();
}
Loading history...
252
253
    return FALSE;
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected false, but found FALSE.
Loading history...
254
}
255
256
function & debug_parse_args(array $args)
257
{
258
    // Соберем сюда описание аргументов функции
259
    $result = array();
260
261
    // Переберем аргументы функции
262
    $args_count = sizeof($args);
263
    for ($j = 0; $j < $args_count; $j++) {
264
        // Получим аргумент
265
        $arg = &$args[$j];
266
267
        // Опредилим тип арргумента и сформируем для него "понятное" представление
268
        switch (gettype($arg)) {
269
            case 'array':
270
                // Вырежем первые 5 элементов массива
271
                $array_values = array_slice($arg, 0, 5);
272
                // Рекурсивно разберем элементны массива
273
                $result[] = 'Array#' . sizeof($arg) . '(' . implode(', ', debug_parse_args($array_values)) . ')';
274
                break;
275
            case 'string':
276
                $result[] = '&#34;' . $arg . '&#34;';
277
                break;
278
            case 'object':
279
                $class = 'Class:' . get_class($arg);
280
                // Если передана запись из БД
281
                if (get_parent_class($arg) == 'dbRecord') $class .= '(' . $arg->id . ')';
0 ignored issues
show
Coding Style Best Practice introduced by
It is generally a best practice to always use braces with control structures.

Adding braces to control structures avoids accidental mistakes as your code changes:

// Without braces (not recommended)
if (true)
    doSomething();

// Recommended
if (true) {
    doSomething();
}
Loading history...
282
                else if (get_class($arg) == 'Module') $class .= '(' . $arg->id() . ')';
0 ignored issues
show
Coding Style Best Practice introduced by
It is generally a best practice to always use braces with control structures.

Adding braces to control structures avoids accidental mistakes as your code changes:

// Without braces (not recommended)
if (true)
    doSomething();

// Recommended
if (true) {
    doSomething();
}
Loading history...
283
                $result[] = $class;
284
                break;
285
            case 'NULL':
286
                $result[] = 'NULL';
287
                break;
288
            // Незнаем как преобразовать
289
            default:
290
                $result[] = $arg;
291
        }
292
    }
293
294
    // Вернем результат
295
    return $result;
296
}
297
298
function debug_to_string($errno = NULL, $file = NULL, $line = NULL, $class = NULL, $function = NULL, $args = NULL)
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
299
{
300
    // Если первым аргументом передан массив, создадим из него переменные
301
    if (is_array($errno)) {
302
        extract($errno);
303
        $errno = NULL;
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
304
    }
305
306
    // Сформируем представление функции, с аргументами
307
    $html = '';
308
309
    // Если указаны аргументы функции
310
    if (isset($errno)) $html .= $errno . ', ';
0 ignored issues
show
Coding Style Best Practice introduced by
It is generally a best practice to always use braces with control structures.

Adding braces to control structures avoids accidental mistakes as your code changes:

// Without braces (not recommended)
if (true)
    doSomething();

// Recommended
if (true) {
    doSomething();
}
Loading history...
311
312
    // Если указаны аргументы функции
313
    if (isset($file)) $html .= $file . ', ';
0 ignored issues
show
Coding Style Best Practice introduced by
It is generally a best practice to always use braces with control structures.

Adding braces to control structures avoids accidental mistakes as your code changes:

// Without braces (not recommended)
if (true)
    doSomething();

// Recommended
if (true) {
    doSomething();
}
Loading history...
314
315
    // Если указана строка
316
    if (isset($line)) $html .= '<b>стр. ' . $line . '</b>, ';
0 ignored issues
show
Coding Style Best Practice introduced by
It is generally a best practice to always use braces with control structures.

Adding braces to control structures avoids accidental mistakes as your code changes:

// Without braces (not recommended)
if (true)
    doSomething();

// Recommended
if (true) {
    doSomething();
}
Loading history...
317
318
    // Если это метод класса - укажем и его
319
    if (isset($class)) $html .= '<b>' . $class . '::</b>';
0 ignored issues
show
Coding Style Best Practice introduced by
It is generally a best practice to always use braces with control structures.

Adding braces to control structures avoids accidental mistakes as your code changes:

// Without braces (not recommended)
if (true)
    doSomething();

// Recommended
if (true) {
    doSomething();
}
Loading history...
320
321
    // Если указана функция
322
    if (isset($function)) $html .= '<b>' . $function . '</b>( ';
0 ignored issues
show
Coding Style Best Practice introduced by
It is generally a best practice to always use braces with control structures.

Adding braces to control structures avoids accidental mistakes as your code changes:

// Without braces (not recommended)
if (true)
    doSomething();

// Recommended
if (true) {
    doSomething();
}
Loading history...
323
324
    // Если указаны аргументы функции
325
    if (isset($args)) $html .= implode(', ', debug_parse_args($args)) . ' )';
0 ignored issues
show
Coding Style Best Practice introduced by
It is generally a best practice to always use braces with control structures.

Adding braces to control structures avoids accidental mistakes as your code changes:

// Without braces (not recommended)
if (true)
    doSomething();

// Recommended
if (true) {
    doSomething();
}
Loading history...
326
327
    return $html;
328
}
329
330
/**
331
 * Сгенерировать HTML представление для стека вызовов
332
 *
333
 * @param array $backtrace Стек вызовов
334
 *
335
 * @return string HTML представление для стека вызовов
336
 */
337
function debug_backtrace_html($message, array $backtrace = NULL)
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
338
{
339
    // Сюда соберем результат
340
    $html = array();
341
342
    // Получим размера стека вызовов
343
    $stack_size = sizeof($backtrace);
344
345
    // Переберем элементы стека вызовов начиная с 3-го элемента
346
    for ($i = 1; $i < $stack_size; $i++) $html[] = debug_to_string($backtrace[$i]);
0 ignored issues
show
Coding Style Best Practice introduced by
It is generally a best practice to always use braces with control structures.

Adding braces to control structures avoids accidental mistakes as your code changes:

// Without braces (not recommended)
if (true)
    doSomething();

// Recommended
if (true) {
    doSomething();
}
Loading history...
Coding Style introduced by
It is generally recommended to place each PHP statement on a line by itself.

Let’s take a look at an example:

// Bad
$a = 5; $b = 6; $c = 7;

// Good
$a = 5;
$b = 6;
$c = 7;
Loading history...
347
348
    // Create unique id fo input [checkbox]
349
    $id = '__error_backtrace_' . rand(0, 1000);
350
351
    // Вернем преобразованный в HTML стек вызовов
352
    return '<ul class="_core_error_text">
353
				<li class="_core_error_function">
354
					<input type="checkbox" class="elapsed_click" id="' . $id . '">
355
					<label for="' . $id . '"></label>' . $message . '
356
					<ul class="_core_error_stack"><li>' . implode('</li>
357
						<li>', $html) . '</li>
358
					</ul>
359
				</li>
360
			</ul>';
361
}
362
363
/**
364
 * Профайлер с выводом отладочного сообщения, отметки времени, и промежутка
365
 * времени прошедшего с последнего вызова данной функции
366
 *
367
 * @param string $text Отладочное сообщение об отметки времени
368
 *
369
 * @return string Сообщение об профайлинге
370
 */
371
function elapsed($text = '')
372
{
373
    // Переменная для сохранения последнего момента времени вызова данного метода
374
    static $l = __SAMSON_T_STARTED__;
375
376
    // Получим текущую отметку времени
377
    $c = microtime(TRUE);
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected true, but found TRUE.
Loading history...
378
    trace(number_format($c-__SAMSON_T_STARTED__,5).' - '.number_format($c-$l,5).' -- '.print_a($text,TRUE));
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected true, but found TRUE.
Loading history...
379
    // Выведем сообщение про текущую отметку времени и время прошедшее с последнего времени
380
    //e(number_format($c - __SAMSON_T_STARTED__, 5) . ' - ' . number_format($c - $l, 5) . ' -- ' . print_a($text, TRUE), D_SAMSON_DEBUG);
381
382
    // Сохраним отметку времени последнего вызова данной функции
383
    $l = $c;
384
}
385
386
/**
387
 * Перевести в верхний регистр первую букву в строке
388
 *
389
 * @param string $string   Строка для преобразования
390
 * @param string $encoding Кодировка
391
 *
392
 * @return string Преобразованная строка
393
 */
394
function utf8_ucfirst($string, $encoding = 'utf-8')
395
{
396
    $strlen = mb_strlen($string, $encoding);
397
398
    $firstChar = mb_substr($string, 0, 1, $encoding);
399
400
    $then = mb_substr($string, 1, $strlen - 1, $encoding);
401
402
    return mb_strtoupper($firstChar, $encoding) . $then;
403
}
404
405
/**
406
 * Обрезать строку "аккуратно" до определенной длины
407
 *
408
 * @param string  $string Входная строка
409
 * @param integer $width  Желаемая длина строка в символах
410
 * @param string  $break  Символ разделения строк
411
 * @param string  $cut    Флаг обрезания больших слов
412
 *
413
 * @return string Обрезанную строку
414
 */
415
function utf8_wordwrap($string, $width = 75, $break = "\n", $cut = FALSE)
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected false, but found FALSE.
Loading history...
416
{
417
    if ($cut) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $cut of type false|string is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
418
        // Match anything 1 to $width chars long followed by whitespace or EOS,
419
        // otherwise match anything $width chars long
420
        $search = '/(.{1,' . $width . '})(?:\s|$)|(.{' . $width . '})/uS';
421
        $replace = '$1$2' . $break;
422
    } else {
423
        // Anchor the beginning of the pattern with a lookahead
424
        // to avoid crazy backtracking when words are longer than $width
425
        $search = '/(?=\s)(.{1,' . $width . '})(?:\s|$)/uS';
426
        $replace = '$1' . $break;
427
    }
428
    return preg_replace($search, $replace, $string);
429
}
430
431
/**
432
 * Обрезать строку до определенной длины и если операция была выполнена
433
 * то добавить маркер в конец строки
434
 *
435
 * @param string  $str          Строка для обрезания
436
 * @param integer $length       Размер выходной строки
437
 * @param string  $limit_marker Строка добавляемая в случаи обрезания строки
438
 *
439
 * @return string Обрезанную строку с маркером обрезания если оно было выполнено
440
 */
441
function utf8_limit_string($str, $length, $limit_marker = '...')
442
{
443
    // Если длина строки превышает требуемую
444
    if (strlen($str) > $length) $str = mb_substr($str, 0, $length, 'UTF-8') . $limit_marker;
0 ignored issues
show
Coding Style Best Practice introduced by
It is generally a best practice to always use braces with control structures.

Adding braces to control structures avoids accidental mistakes as your code changes:

// Without braces (not recommended)
if (true)
    doSomething();

// Recommended
if (true) {
    doSomething();
}
Loading history...
445
446
    // Вернем строку
447
    return $str;
448
}
449
450
/**
451
 * Perform string transliteration from UTF-8 Cyrilic to Latin
452
 *
453
 * @param string $str String to transliterate
454
 *
455
 * @return string Transliterated string
456
 */
457
function utf8_translit($str)
458
{
459
    $converter = array('а' => 'a', 'б' => 'b', 'в' => 'v',
460
        'г' => 'g', 'д' => 'd', 'е' => 'e',
461
        'ё' => 'je', 'ж' => 'zh', 'з' => 'z',
462
        'и' => 'i', 'й' => 'j', 'к' => 'k',
463
        'л' => 'l', 'м' => 'm', 'н' => 'n',
464
        'о' => 'o', 'п' => 'p', 'р' => 'r',
465
        'с' => 's', 'т' => 't', 'у' => 'y',
466
        'ф' => 'f', 'х' => 'h', 'ц' => 'ts',
467
        'ч' => 'ch', 'ш' => 'sh', 'щ' => 'sch',
468
        'ь' => "", 'ы' => 'u', 'ъ' => "i",
469
        'э' => 'e', 'ю' => 'ju', 'я' => 'ja', ' ' => '-', 'ї' => 'gi', 'і' => 'i');
470
471
472
    $str = mb_strtolower($str, 'UTF-8');
473
474
    $str = strtr($str, $converter);
475
476
    $str = preg_replace('/[\-]+/ui', '-', $str);
477
478
    $str = trim(preg_replace('/[^a-z0-9\-\_]/ui', '', $str), '-');
479
480
    $str = str_replace('--', '-', $str);
481
482
    return $str;
483
}
484
485
/**
486
 * Закодировать данные для отправки в E-mail
487
 *
488
 * @param string $str     Данные для кодировки
489
 * @param string $charset Кодировка
490
 *
491
 * @return string    Закодированные данные для передачи
492
 */
493
function mail_encode($str, $charset)
494
{
495
    return '=?' . $charset . '?B?' . base64_encode($str) . '?=';
496
}
497
498
/**
499
 * Отправить HTML письмо
500
 *
501
 * @param string $to      Кому
502
 * @param string $from    От кого
503
 * @param string $message Письмо
504
 * @param string $subject Тема письма
505
 */
506
function mail_send($to, $from = '[email protected]', $message = '', $subject = '', $from_user = '')
507
{
508
    // Обработаем кирилицу в поле: От кого
509
    $from_user = mail_encode($from_user, 'UTF-8');
510
511
    // Обработаем кирилицу в поле: Тема письма
512
    $subject = mail_encode($subject, 'UTF-8');
513
514
    // Uniqid Session
515
    $session = md5(uniqid(time()));
0 ignored issues
show
Unused Code introduced by
$session is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
516
517
    // Установим необходимые заголовки
518
    $headers = 'MIME-Version: 1.0' . "\r\n";
519
    $headers .= 'Content-type: text/html; charset="UTF-8"' . "\r\n";
520
    //"Content-Type: multipart/mixed; boundary=\"".$strSid."\"\n\n";
521
    //$strHeader .= "This is a multi-part message in MIME format.\n";
522
    $headers .= 'From: ' . $from_user . '<' . $from . '>' . "\r\n";
523
524
    // Добавим в сообщение HTML тэги
525
    $message = '<html><head><meta charset="utf-8"></head><body>' . $message . '</body></html>';
526
527
    // Если письмо отправленно вернем 1
528
    return mail($to, $subject, $message, $headers);
529
}
530
531
/**
532
 * Просклонять слово
533
 *
534
 * @param array $words массив с 3-мя элеметами - вариантами написания слов
535
 * @param int   $n     число
536
 *
537
 * @return string Сгенерированный код формы для отправки на LIQPAY
538
 */
539
function incline_word($words, $n)
540
{
541
    if ($n % 100 > 4 && $n % 100 < 20) {
542
        return $words[2];
543
    }
544
    $a = array(2, 0, 1, 1, 1, 2);
545
    return $words[$a[min($n % 10, 5)]];
546
}
547
548
/**
549
 * Отформатировать дату на русском языке
550
 *
551
 * @param int $date метку времени Unix
552
 *
553
 * @return string дата на русском языке
554
 */
555
function date_format_ru($date)
556
{
557
    $date = strtotime($date);
558
    $day = date("d", $date);
559
    $month_en = date("F", $date);
560
    $year = date("Y", $date);
561
    $days_of_week_en = date("l", $date);
562
    $month_ru = array(
563
        'January' => 'января',
564
        'February' => 'февраля',
565
        'March' => 'марта',
566
        'April' => 'апреля',
567
        'May' => 'мая',
568
        'June' => 'июня',
569
        'July' => 'июля',
570
        'August' => 'августа',
571
        'September' => 'сентября',
572
        'October' => 'октября',
573
        'November' => 'ноября',
574
        'December' => 'декабря',
575
    );
576
    $days_of_week_ru = array(
577
        'Monday' => 'Понедельник',
578
        'Tuesday' => 'Вторник',
579
        'Wednesday' => 'Среда',
580
        'Thursday' => 'Четверг',
581
        'Friday' => 'Пятница',
582
        'Saturday' => 'Суббота',
583
        'Sunday' => 'Воскресенье',
584
    );
585
    $month = $month_ru[$month_en];
586
    $days_of_week = $days_of_week_ru[$days_of_week_en];
587
    $date = "$days_of_week, $day $month $year года";
588
    return $date;
589
}
590
591
/**
592
 * Получить все классы наследующие переданный класс
593
 *
594
 * @param string $parent Имя класса родителя
595
 *
596
 * @return array Коллекцию классов наследующих указанный класс
597
 */
598
function get_child_classes($parent)
599
{
600
    $ancestors = array();
601
602
    // Перерберем все задекларированные классы и посмотрим те которые наследуют нужный класс
603
    foreach (get_declared_classes() as $class) {
604
        // Если класс наследует нужный нам класс
605
        if (in_array($parent, class_parents($class))) {
606
            $ancestors[] = $class;
607
        }
608
    }
609
610
    return $ancestors;
611
}
612
613
/**
614
 * Функция для генерации пароля
615
 *
616
 * @param int $count Голичество символом в пароле
617
 *
618
 * @return string Сгенерированный пароль
619
 */
620
function generate_password($count)
621
{
622
    $symbols = array('a', 'b', 'c', 'd', 'e', 'f',
623
        'g', 'h', 'i', 'j', 'k', 'l',
624
        'm', 'n', 'o', 'p', 'r', 's',
625
        't', 'u', 'v', 'x', 'y', 'z',
626
        'A', 'B', 'C', 'D', 'E', 'F',
627
        'G', 'H', 'I', 'J', 'K', 'L',
628
        'M', 'N', 'O', 'P', 'R', 'S',
629
        'T', 'U', 'V', 'X', 'Y', 'Z',
630
        '1', '2', '3', '4', '5', '6',
631
        '7', '8', '9', '0');
632
    // Генерируем пароль
633
    $pass = "";
634
    for ($i = 0; $i < $count; $i++) {
635
        // Вычисляем случайный индекс массива
636
        $index = rand(0, sizeof($symbols) - 1);
637
        $pass .= $symbols[$index];
638
    }
639
    return $pass;
640
}
641
642
/**
643
 * Сформировать правильное имя класса с использованием namespace, если оно не указано
644
 * Функция нужна для обратной совместимости с именами классов без NS
645
 *
646
 * @param string $class_name Имя класса для исправления
647
 * @param string $ns         Пространство имен которому принадлежит класс
648
 *
649
 * @deprecated use \samson\core\AutoLoader::value() and pass full class name to it without splitting into class
650
 *             name and namespace
651
 * @return string Исправленное имя класса
652
 */
653
function ns_classname($class_name, $ns = null)
654
{
655
    return \samson\core\AutoLoader::className($class_name, $ns);
656
}
657