aboutsummaryrefslogtreecommitdiff
path: root/app/fn/fn.php
blob: 461f1297b78f639c01647ee5085098c9f6b0c3b3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
<?php

use Wcms\Mediaopt;

use function Clue\StreamFilter\fun;

function readablesize($bytes, $base = 2 ** 10)
{
    $format = ' %d %s';

    if ($base === 2 ** 10) {
        $i = 'i';
    } else {
        $i = '';
    }

    $unit = '';

    if ($bytes < $base) {
        $num = $bytes;
    } elseif ($bytes < $base ** 2) {
        $num = round($bytes / $base, 1);
        $unit = 'K' . $i;
    } elseif ($bytes < $base ** 3) {
        $num = round($bytes / $base ** 2, 1);
        $unit = 'M' . $i;
    } else {
        $num = round($bytes / $base ** 3, 1);
        $unit = 'G' . $i;
    }

    return sprintf($format, $num, $unit);
}

/* human readable date interval
 * @param DateInterval $diff - l'interval de temps
 * @return string
 */
function hrdi(DateInterval $diff)
{
    $str = "";
    if ($diff->y > 1) {
        return $str . $diff->y . ' years';
    }
    if ($diff->y == 1) {
        return $str . ' 1 year and ' . $diff->m . ' months';
    }
    if ($diff->m > 1) {
        return $str . $diff->m . ' months';
    }
    if ($diff->m == 1) {
        return $str . ' 1 month and ' . $diff->d . ($diff->d > 1 ? ' days' : ' day');
    }
    if ($diff->d > 1) {
        return $str . $diff->d . ' days';
    }
    if ($diff->d == 1) {
        return $str . ' 1 day and ' . $diff->h . ($diff->h > 1 ? ' hours' : ' hour');
    }
    if ($diff->h > 1) {
        return $str . $diff->h . ' hours';
    }
    if ($diff->h == 1) {
        return $str . ' 1 hour and ' . $diff->i . ($diff->i > 1 ? ' minutes' : ' minute');
    }
    if ($diff->i > 1) {
        return $str . $diff->i . ' minutes';
    }
    if ($diff->i == 1) {
        return $str . ' 1 minute';
    }
    return $str . ' a few secondes';
}



function arrayclean($input)
{
    $output = [];
    foreach ($input as $key => $value) {
        if (is_array($value)) {
            $output[$key] = array_filter($value);
        } else {
            $output[$key] = $value;
        }
    }
    return $output;
}

/**
 * Clean string from characters outside `[0-9a-z-_]` and troncate it
 * @param string $input
 * @param int $max minmum input length to trucate id
 * @return string output formated id
 */
function idclean(string $input, int $max = Wcms\Model::MAX_ID_LENGTH): string
{
    $regex = '%[^a-z0-9-_]%';
    $input = urldecode($input);

    if (preg_match($regex, $input)) {
        $search =  ['é', 'à', 'è', 'ç', 'ù', 'ï', 'î', ' '];
        $replace = ['e', 'a', 'e', 'c', 'u', 'i', 'i', '-'];
        $input = str_replace($search, $replace, $input);
        
        $input = preg_replace($regex, '', strtolower(trim($input)));
        
        $input = substr($input, 0, $max);
    }
    return $input;
}

function isreportingerrors()
{
    return function_exists('Sentry\init') && !empty(Wcms\Config::sentrydsn());
}


function getversion()
{
    if (file_exists('VERSION')) {
        $version = trim(file_get_contents('VERSION'));
    } else {
        $version = 'unknown';
    }
    return $version;
}



function array_update($base, $new)
{
    foreach ($base as $key => $value) {
        if (array_key_exists($key, $new)) {
            if (gettype($base[$key]) == gettype($new[$key])) {
                $base[$key] = $new[$key];
            }
        }
    }
    return $base;
}

function contains($needle, $haystack)
{
    return strpos($haystack, $needle) !== false;
}


function str_clean(string $string)
{
    return str_replace(' ', '_', strtolower(strip_tags($string)));
}




function changekey($array, $oldkey, $newkey)
{
    if (!array_key_exists($oldkey, $array)) {
        return $array;
    }

    $keys = array_keys($array);
    $keys[array_search($oldkey, $keys)] = $newkey;

    return array_combine($keys, $array);
}



function compare($stringa, $stringb)
{
    $arraya = explode(PHP_EOL, $stringa);
    $arrayb = explode(PHP_EOL, $stringb);

    $lnb = -1;
    $commonlines = [];
    foreach ($arraya as $na => $linea) {
        $found = false;
        foreach ($arrayb as $nb => $lineb) {
            if ($linea === $lineb && $nb > $lnb && !$found && !empty($linea)) {
                $commonlines[$na] = $nb;
                $merge[] = $arrayb[$nb];
                $lnb = $nb;
                $found = true;
            }
        }
    }


    $merge = [];
    $lnb = 0;
    foreach ($arraya as $na => $linea) {
        if (array_key_exists($na, $commonlines)) {
            for ($j = $lnb; $j <= $commonlines[$na]; $j++) {
                    $merge[] = $arrayb[$j];
            }
            $lnb = $j;
        } else {
            $merge[] = $arraya[$na];
        }
    }
    for ($k = $lnb;; $k++) {
        if (array_key_exists($k, $arrayb)) {
            $merge[] = $arrayb[$k];
        } else {
            break;
        }
    }

    return implode(PHP_EOL, $merge);
}



function findsize($file)
{
    if (substr(PHP_OS, 0, 3) == "WIN") {
        exec('for %I in ("' . $file . '") do @echo %~zI', $output);
        $return = $output[0];
    } else {
        $return = filesize($file);
    }
    return $return;
}

function array_diff_assoc_recursive($array1, $array2)
{
    $difference = array();
    foreach ($array1 as $key => $value) {
        if (is_array($value)) {
            if (!isset($array2[$key]) || !is_array($array2[$key])) {
                $difference[$key] = $value;
            } else {
                $new_diff = array_diff_assoc_recursive($value, $array2[$key]);
                if (!empty($new_diff)) {
                    $difference[$key] = $new_diff;
                }
            }
        } elseif (!array_key_exists($key, $array2) || $array2[$key] !== $value) {
            $difference[$key] = $value;
        }
    }
    return $difference;
}


/**
 * Generate a clickable folder tree based on reccurive array
 */
function treecount(
    array $dirlist,
    string $dirname,
    int $deepness,
    string $path,
    string $currentdir,
    Mediaopt $mediaopt
) {
    if ($path . '/' === $currentdir) {
        $folder = '├─📂<span id="currentdir">' . $dirname . '<span>';
    } else {
        $folder = '├─📁' . $dirname;
    }
    echo '<tr>';
    $href = $mediaopt->getpathadress($path);
    $foldername = str_repeat('&nbsp;&nbsp;', $deepness) . $folder;
    echo '<td><a href="' . $href . '">' . $foldername . '</a></td>';
    echo '<td>' . $dirlist['dirfilecount'] . '</td>';
    echo '</tr>';
    foreach ($dirlist as $key => $value) {
        if (is_array($value)) {
            treecount($value, $key, $deepness + 1, $path . DIRECTORY_SEPARATOR . $key, $currentdir, $mediaopt);
        }
    }
}


/**
 * Generate a clickable folder tree based on reccurive array
 */
function basictree(array $dirlist, string $dirname, int $deepness, string $path, string $currentdir)
{

    if ($path === $currentdir) {
        $folder = '├─📂<span id="currentdir">' . $dirname . '<span>';
        $checked = 'checked';
    } else {
        $folder = '├─📁' . $dirname;
        $checked = '';
    }

    if ($deepness === 1) {
        // phpcs:ignore Generic.Files.LineLength.TooLong
        $radio = '<input type="radio" name="pagetable" value="' . $dirname . '" id="db_' . $path . '" ' . $checked . '>';
    } else {
        $radio = '';
    }

    echo '<tr>';
    echo '<td>' . $radio . '</td>';
    echo '<td><label for="db_' . $path . '">' . str_repeat('&nbsp;&nbsp;', $deepness) . $folder . '</label></td>';
    echo '<td>' . $dirlist['dirfilecount'] . '</td>';
    echo '</tr>';
    foreach ($dirlist as $key => $value) {
        if (is_array($value)) {
            basictree($value, $key, $deepness + 1, $path . DIRECTORY_SEPARATOR . $key, $currentdir);
        }
    }
}

function checkboxes(string $name, array $optionlist = [], array $checkedlist = [])
{
    $checkboxes = '';
    foreach ($optionlist as $option) {
        $checkboxes .= '<li><input type="checkbox" name="' . $name . '[]" id="' . $option . '" value="' . $option . '"';
        if (in_array($option, $checkedlist)) {
            $checkboxes .= ' checked';
        }
        $checkboxes .= '><label for="' . $option . '">' . $option . '</label></li>';
        $checkboxes .= PHP_EOL;
    }
    return '<ul>' . PHP_EOL . $checkboxes . PHP_EOL . '</ul>';
}


function recurse_copy($src, $dst)
{
    $dir = opendir($src);
    mkdir($dst);
    while (false !== ( $file = readdir($dir))) {
        if (( $file != '.' ) && ( $file != '..' )) {
            if (is_dir($src . '/' . $file)) {
                recurse_copy($src . '/' . $file, $dst . '/' . $file);
            } else {
                copy($src . '/' . $file, $dst . '/' . $file);
            }
        }
    }
    closedir($dir);
}

/**
 * Generate a list of <options> html drop down list
 *
 * @param array $options as `value => title`
 * @param string|int $selected value of actualy selected option
 * @param bool $title Use title as value. Default : false
 *
 * @return string HTML list of options
 */
function options(array $options, $selected = null, $title = false): string
{
    $html = '';
    foreach ($options as $value => $title) {
        if ($value === $selected) {
            $attribute = 'selected';
        } else {
            $attribute = '';
        }
        if ($title) {
            $value = $title;
        }
        $html .= '<option value="' . $value . '" ' . $attribute . '>' . $title . '</option>' . PHP_EOL;
    }
    return $html;
}


/**
 * Hash a Token using secret key and sha256
 *
 * @param string $token Input token
 *
 * @return string Hashed mac
 */
function secrethash(string $token): string
{
    return hash_hmac('sha256', $token, Wcms\Config::secretkey());
}


/**
 * Check if dir exist. If not, create it
 *
 * @param string $dir Directory to check
 * @param bool $createdir create dir in case of non existence default is true
 * @return bool return true if the dir already exist or was created succesfullt. Otherwise return false
 * @throws \InvalidArgumentException If folder creation is impossible or if directory doeas not exist
 */
function dircheck(string $dir, bool $createdir = true): bool
{
    if (!is_dir($dir)) {
        if ($createdir) {
            $parent = dirname($dir);
            if (dircheck($parent)) {
                if (mkdir($dir)) {
                    return true;
                } else {
                    throw new \InvalidArgumentException("Cannot create directory : $dir");
                }
            } else {
                return false;
            }
        } else {
            throw new \InvalidArgumentException("Directory '$dir' does not exist.");
        }
    } else {
        return true;
    }
}


/**
 * Check if a file is accessible or can be writen
 * @param string $path file path to check
 * @param bool $createdir create directory if does not exist
 * @return bool If no error occured
 * @throws \InvalidArgumentException if :
 * parent directory does not exist | is not writable | file exist and not writable
 */
function accessfile(string $path, bool $createdir = false): bool
{
    $dir = dirname($path);
    if (dircheck($dir, $createdir)) {
        if (!is_writable($dir)) {
            throw new \InvalidArgumentException("Directory '$dir' is not writable.");
        }
        if (!file_exists($path)) {
            throw new \InvalidArgumentException("The file '$path' does not exist.");
        }
        if (is_file($path) && !is_writable($path)) {
            throw new \InvalidArgumentException("The file '$path' is not writable.");
        }
        return true;
    } else {
        return false;
    }
}