GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — stable-3.1 ( 28f09e...905725 )
by Benjamin
03:04
created

functions.php ➔ fHSVtoRGB()   F

Complexity

Conditions 20
Paths 896

Size

Total Lines 80
Code Lines 65

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 20
eloc 65
c 1
b 0
f 0
nc 896
nop 3
dl 0
loc 80
rs 2.5

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/*
4
  ----------------------------------------------------------------------
5
  AlternC - Web Hosting System
6
  Copyright (C) 2000-2012 by the AlternC Development Team.
7
  https://alternc.org/
8
  ----------------------------------------------------------------------
9
  LICENSE
10
11
  This program is free software; you can redistribute it and/or
12
  modify it under the terms of the GNU General Public License (GPL)
13
  as published by the Free Software Foundation; either version 2
14
  of the License, or (at your option) any later version.
15
16
  This program is distributed in the hope that it will be useful,
17
  but WITHOUT ANY WARRANTY; without even the implied warranty of
18
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19
  GNU General Public License for more details.
20
21
  To read the license please visit http://www.gnu.org/copyleft/gpl.html
22
  ----------------------------------------------------------------------
23
  Purpose of file: Miscellaneous functions globally used
24
  ----------------------------------------------------------------------
25
 */
26
27
/**
28
 * Format a field value for input or textarea : 
29
 * 
30
 * @param string $str
31
 * @return string
32
 */
33
function fl($str) {
34
    return str_replace("<", "&lt;", str_replace("\"", "&quot;", $str));
35
}
36
37
/**
38
 *  Check if a domain can be hosted on this server :
39
 * Return a negative value in case of an error,
40
 * or a string for the index in $tld
41
 * 
42
 * @global string $L_NS1
43
 * @global string $L_NS2
44
 * @global m_mysql $db
45
 * @global m_dom $dom
46
 * @param string $domain
47
 * @param array $dns
48
 * @return int
49
 */
50
function checkhostallow($domain, $dns) {
51
    global $L_NS1, $L_NS2, $db, $dom;
52
    $sizefound = 0;
53
    $found = "";
54
    $db->query("SELECT tld,mode FROM tld;");
55
    while ($db->next_record()) {
56
        list($key, $val) = $db->Record;
57
        if (substr($domain, -1 - strlen($key)) == "." . $key) {
58
            if ($sizefound < strlen($key)) {
59
                $sizefound = strlen($key);
60
                $found = $key;
61
                $fmode = $val;
62
            }
63
        }
64
    }
65
    if ($dom->tld_no_check_at_all) {
66
        return 0; // OK , the boss say that you can.
67
    }
68
    if (!$found || $fmode == 0) {   // TLD not allowed at all
69
        return -1;
70
    }
71
    if (($fmode != 4) && (!is_array($dns))) { // NO dns found in the whois, and domain MUST exists
72
        return -2;
73
    }
74
    if ($fmode > 2) { // OK, in the case 3 4 5
75
        return $found;
76
    }
77
    $n1 = false;
78
    $n2 = false;
79
    for ($i = 0; $i < count($dns); $i++) {
80
        if (strtolower($dns[$i]) == strtolower($L_NS1)) {
81
            $n1 = true;
82
        }
83
        if (strtolower($dns[$i]) == strtolower($L_NS2)) {
84
            $n2 = true;
85
        }
86
    }
87
    if ($fmode == 1 && $n1) {
88
        return $found;
89
    }
90
    if ($fmode == 2 && $n1 && $n2) {
91
        return $found;
92
    }
93
    return -3; // DNS incorrect in the whois
94
}
95
96
/**
97
 * Check that a domain can be hosted in that server, 
98
 *   without DNS managment. 
99
 * @global m_mysql $db
100
 * @param string $domain
101
 * @return int
102
 */
103
function checkhostallow_nodns($domain) {
104
    global $db;
105
    $sizefound = 0;
106
    $found = "";
107
    $db->query("SELECT tld,mode FROM tld;");
108
    while ($db->next_record()) {
109
        list($key, $val) = $db->Record;
110
        if (substr($domain, -1 - strlen($key)) == "." . $key) {
111
            if ($sizefound < strlen($key)) {
112
                $sizefound = strlen($key);
113
                $found = $key;
114
                $fmode = $val;
115
            }
116
        }
117
    }
118
    // If we found a correct tld, let's find how many . before ;)
119
    if (!$found || $fmode == 0) {                      // TLD not allowed at all
120
        return 1;
121
    }
122
    if (count(explode(".", substr($domain, 0, -$sizefound))) > 2) {
123
        return 1;
124
    }
125
    return 0;
126
}
127
128
/**
129
 * Return the remote IP.
130
 * If you are behind a proxy, use X_FORWARDED_FOR instead of REMOTE_ADDR
131
 * @return string
132
 */
133
function get_remote_ip() {
134
    return getenv('REMOTE_ADDR');
135
}
136
137
/**
138
 * Check that $url is a correct url (http:// or https:// or ftp://) 
139
 * 
140
 * @param type $url
141
 * @return boolean
142
 */
143
function checkurl($url) {
144
    // TODO : add a path/file check
145
    if (substr($url, 0, 7) != "http://" && substr($url, 0, 8) != "https://" && substr($url, 0, 6) != "ftp://") {
146
        return false;
147
    }
148
    if (substr($url, 0, 7) == "http://") {
149
        $fq = substr($url, 7);
150
    }
151
    if (substr($url, 0, 8) == "https://") {
152
        $fq = substr($url, 8);
153
    }
154
    if (substr($url, 0, 6) == "ftp://") {
155
        $fq = substr($url, 6);
156
    }
157
    $f = explode("/", $fq);
158
    if (!is_array($f)) {
159
        $f = array($f);
160
    }
161
    $t = checkfqdn($f[0]);
162
    return !$t;
163
}
164
165
/**
166
 * Check that TXT domain is correct 
167
 * 
168
 * @param string $txt
169
 * @return boolean
170
 */
171
function checksubtxt($txt) {
172
    return true;
173
}
174
175
/**
176
 * Check that CNAME domain is correct 
177
 * @param string $cname
178
 * @return boolean
179
 */
180
function checkcname($cname) {
181
    if (($check = checkfqdn(rtrim($cname, ".")))) {
182
        if ($check != 4) { // ALLOW non-fully qualified (no .)
183
            return false; // bad FQDN
184
        }
185
    }
186
    if (substr($cname, -1) != ".") {
187
        // Not fully qualified : 
188
        if (strpos($cname, ".") === false) {
189
            // NO DOT in the middle, no DOT elsewhere => seems fine
190
            return true;
191
        } else {
192
            // NO DOT at the end, but A DOT ELSEWHERE => seems broken (please use fully qualified)
193
            return false;
194
        }
195
    }
196
    // fully qualified => fine
197
    return true;
198
}
199
200
/**
201
 * Check that $ip is a correct 4 Dotted ip
202
 * @param string $ip
203
 * @return type
204
 */
205
function checkip($ip) {
206
    // return true or false whether the ip is correctly formatted
207
    return filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4);
208
}
209
210
/**
211
 * Check that $ip is a correct ipv6 ip 
212
 * @param string $ip
213
 * @return type
214
 */
215
function checkipv6($ip) {
216
    // return true or false whether the ip is correctly formatted
217
    return filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6);
218
}
219
220
/**
221
 * Check a login mail, cf http://www.bortzmeyer.org/arreter-d-interdire-des-adresses-legales.html 
222
 * @todo Check who is using that function and delete it when unused 
223
 * @param string $mail
224
 * @return boolean
225
 */
226
function checkloginmail($mail) {
227
    return true;
228
}
229
230
/**
231
 * Check an email address, use filter_var with emails, which works great ;) 
232
 * @todo  check who is using that function and delete it when unused 
233
 * @param string $mail
234
 * @return boolean
235
 */
236
function checkmail($mail) {
237
    if (filter_var($mail, FILTER_VALIDATE_EMAIL)) {
238
        return FALSE;
239
    } else {
240
        return TRUE;
241
    }
242
}
243
244
/**
245
 * Check that a domain name is fqdn compliant 
246
 * @param string $fqdn
247
 * @return int
248
 */
249
function checkfqdn($fqdn) {
250
    // (RFC 1035 http://www.ietf.org/rfc/rfc1035.txt)
251
    // Retourne 0 si tout va bien, sinon, retourne un code erreur...
252
    // 1. Nom de domaine complet trop long.
253
    // 2. L'un des membres est trop long.
254
    // 3. Caractere interdit dans l'un des membres.
255
    // 4. Le fqdn ne fait qu'un seul membre (il n'est donc pas fq...)
256
    if (strlen($fqdn) > 255) {
257
        return 1;
258
    }
259
    $members = explode(".", $fqdn);
260
    if (count($members) > 1) {
261
        $ret = 0;
262
    } else {
263
        $ret = 4;
264
    }
265
    reset($members);
266
    while (list ($key, $val) = each($members)) {
267
        if (strlen($val) > 63) {
268
            return 2;
269
        }
270
        // Note: a.foo.net is a valid domain
271
        // Note: RFC1035 tells us that a domain should not start by a digit, but every registrar allows such a domain to be created ... too bad.
272
        if (!preg_match("#^[a-z0-9_]([a-z0-9-]*[a-z0-9])?$#i", $val)) {
273
            return 3;
274
        }
275
    }
276
    return $ret;
277
}
278
279
/**
280
 * @global m_mem $mem
281
 * @param string $path
282
 * @return int 
283
 * return 0 if the path is not in the user's space
284
 * return 1 if this is a directory
285
 * return 2 if this is a regular file
286
 */
287
function checkuserpath($path) {
288
    global $mem;
289
    $user = $mem->user["login"];
290
    $usar = substr($user, 0, 1);
291
    if (substr($path, 0, 1) != "/") {
292
        $path = "/" . $path;
293
    }
294
    $rpath = realpath(ALTERNC_HTML . "/$usar/$user$path");
295
    if (!$rpath) { // if file or directory does not exist
296
        return 1; // FIXME is it safe to say OK in this case ?
297
    }
298
    $userpath = getuserpath();
299
    if (strpos($rpath, $userpath) === 0) {
300
        if (is_dir(ALTERNC_HTML . "/$usar/$user$path")) {
301
            return 1;
302
        }
303
        if (is_file(ALTERNC_HTML . "/$usar/$user$path")) {
304
            return 2;
305
        }
306
    }
307
    return 0;
308
}
309
310
/**
311
 * get the home of the user
312
 *
313
 * @global m_mem $mem
314
 * @args string $user the username, if null will use the global $mem. no
315
 * security checks performed on path
316
 * @return string the actual absolute path
317
 */
318
function getuserpath($user = null) {
319
    if (is_null($user)) {
320
        global $mem;
321
        $user = $mem->user['login'];
322
    }
323
    return rtrim(ALTERNC_HTML, "/") . "/" . substr($user, 0, 1) . "/" . $user;
324
}
325
326
/**
327
 * ECHOes checked="checked" only if the parameter is true
328
 * useful for checkboxes and radio buttons
329
 * 
330
 * @param boolean $test
331
 * @param boolean $echo
332
 */
333
function cbox($test, $echo = true) {
334
    if ($test) {
335
        $return = " checked=\"checked\"";
336
    } else {
337
        $return = '';
338
    }
339
    if ($echo) {
340
        echo $return;
341
    }
342
    return $return;
343
}
344
345
/**
346
 * ECHOes selected="selected" only if the parameter is true
347
 * useful for checkboxes and radio buttons
348
 * 
349
 * @param boolean $bool
350
 * @param boolean $echo
351
 * @return string
352
 */
353
function selected($bool, $echo = TRUE) {
354
    if ($bool) {
355
        $return = " selected=\"selected\"";
356
    } else {
357
        $return = '';
358
    }
359
    if ($echo) {
360
        echo $return;
361
    }
362
    return $return;
363
}
364
365
/**
366
 * 
367
 * @param boolean $test
368
 * @param string $tr
369
 * @param string $fa
370
 * @param integer $affiche
371
 * @return string
372
 */
373
function ecif($test, $tr, $fa = "", $affiche = 1) {
374
    if ($test) {
375
        $retour = $tr;
376
    } else {
377
        $retour = $fa;
378
    }
379
    if ($affiche) {
380
        echo $retour;
381
    }
382
    return $retour;
383
}
384
385
/**
386
 * 
387
 * @param string $str
388
 */
389
function __($str) {
390
    echo _($str);
391
}
392
393
/**
394
 * 
395
 * @param boolean $test
396
 * @param string $tr
397
 * @param string $fa
398
 * @return string
399
 */
400
function ife($test, $tr, $fa = "") {
401
    if ($test) {
402
        return $tr;
403
    }
404
    return $fa;
405
}
406
407
/**
408
 * 
409
 * @param int|string $size
410
 * @param integer $html
411
 * @return string
412
 */
413
function format_size($size, $html = 0) {
414
    // Retourne une taille formatt�e en Octets, Kilo-octets, M�ga-octets ou Giga-Octets, avec 2 d�cimales.
415
    if ("-" == $size) {
416
        return $size;
417
    }
418
    $size = (float) $size;
419
    if ($size < 1024) {
420
        $r = $size;
421
        if ($size != 1) {
422
            $r.=" " . _("Bytes");
423
        } else {
424
            $r.=" " . _("Byte");
425
        }
426
    } else {
427
        $size = $size / 1024;
428
        if ($size < 1024) {
429
            $r = round($size, 2) . " " . _("Kb");
430
        } else {
431
            $size = $size / 1024;
432
            if ($size < 1024) {
433
                $r = round($size, 2) . " " . _("Mb");
434
            } else {
435
                $size = $size / 1024;
436
                if ($size < 1024) {
437
                    $r = round($size, 2) . " " . _("Gb");
438
                } else {
439
                    $r = round($size / 1024, 2) . " " . _("Tb");
440
                }
441
            }
442
        }
443
    }
444
    if ($html) {
445
        return str_replace(" ", "&nbsp;", $r);
446
    } else {
447
        return $r;
448
    }
449
}
450
451
/**
452
 * 
453
 * @param int $hid
454
 * @return string
455
 */
456
function getlinkhelp($hid) {
457
    return "(<a href=\"javascript:help($hid);\">?</a>)";
458
}
459
460
/**
461
 * 
462
 * @param int $hid
463
 */
464
function linkhelp($hid) {
465
    echo getlinkhelp($hid);
466
}
467
468
/**
469
 * 
470
 * @param string $format
471
 * @param string $date
472
 * @return string
473
 */
474
function format_date($format, $date) {
475
    $d = substr($date, 8, 2);
476
    $m = substr($date, 5, 2);
477
    $y = substr($date, 0, 4);
478
    $h = substr($date, 11, 2);
479
    $i = substr($date, 14, 2);
480
    if ($h > 12) {
481
        $hh = $h - 12;
482
        $am = "pm";
483
    } else {
484
        $hh = $h;
485
        $am = "am";
486
    }
487
488
    // we want every number to be treated as a string.
489
    $format=str_replace('$d', '$s', $format);
490
    return sprintf($format, $d, $m, $y, $h, $i, $hh, $am);
491
}
492
493
/**
494
 * Strip slashes if needed : 
495
 * @param string $str
496
 * @return string
497
 */
498
function ssla($str) {
499
    if (get_magic_quotes_gpc()) {
500
        return stripslashes($str);
501
    } else {
502
        return $str;
503
    }
504
}
505
506
/* ----------------------------------------------------------------- */
507
508
/** Hashe un mot de passe en clair en MD5 avec un salt al�atoire
509
 * @param string $pass Mot de passe � crypter (max 32 caract�res)
510
 * @return string Retourne le mot de passe crypt�
511
 * @access private
512
 */
513
function _md5cr($pass, $salt = "") {
514
    if (!$salt) {
515
        $chars = "./0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
516
        for ($i = 0; $i < 12; $i++) {
517
            $salt.=substr($chars, (mt_rand(0, strlen($chars))), 1);
518
        }
519
        $salt = "$1$" . $salt;
520
    }
521
    return crypt($pass, $salt);
522
}
523
524
/** split mysql database name between username and custom database name
525
 * @param string $dbname database name
526
 * @return array returns username as first element, custom name as second
527
 */
528
function split_mysql_database_name($dbname) {
529
    $db_exploded_name = explode("_", $dbname);
530
    return array($db_exploded_name[0],
531
        implode("_", array_slice($db_exploded_name, 1)));
532
}
533
534
/* ----------------------------------------------------------------- */
535
536
/** Echappe les caract�res pouvant perturber un flux XML standard : 
537
 * @param string $string Chaine de caract�re � encoder en valeur xml.
538
 * @return string Retourne la cha�ne modifi�e si besoin.
539
 * @access private
540
 */
541
function xml_entities($string) {
542
    return str_replace("<", "&lt;", str_replace(">", "&gt;", str_replace("&", "&amp;", $string)));
543
}
544
545
/* ----------------------------------------------------------------- */
546
547
/** Converti un nombre de mois en une chaine plus lisible
548
 * @param  integer $months Nombre de mois
549
 * @return string Cha�ne repr�sentant le nombre de mois
550
 * @access private
551
 */
552
function pretty_months($months) {
553
    if ($months % 12 == 0 && $months > 11) {
554
        $years = $months / 12;
555
        return "$years " . ($years > 1 ? _("years") : _("year"));
556
    } else {
557
        return "$months " . ($months > 1 ? _("months") : _("month"));
558
    }
559
}
560
561
/* ----------------------------------------------------------------- */
562
563
/** Fabrique un drop-down pour les dur�es de comptes
564
 * @name string $name Nom pour le composasnt
565
 * @selected number Option selection�e du composant
566
 * @return string Code html pour le drop-down
567
 * @access private
568
 */
569
function duration_list($name, $selected = 0) {
570
    $res = "<select name=\"$name\" id=\"$name\" class=\"inl\">";
571
572
    foreach (array(0, 1, 2, 3, 4, 6, 12, 24) as $dur) {
573
        $res .= "<option value=\"$dur\"";
574
        if ($selected == $dur) {
575
            $res .= ' selected="selected" ';
576
        }
577
578
        $res .= '>';
579
580
        if ($dur == 0) {
581
            $res .= _('Not managed');
582
        } else {
583
            $res .= pretty_months($dur);
584
        }
585
        $res .= '</option>';
586
    }
587
588
    $res .= '</select>';
589
    return $res;
590
}
591
592
/**
593
 * select_values($arr,$cur) echo des <option> du tableau $values ou de la table sql $values
594
 *  selectionne $current par defaut. 
595
 *  Si on lui demande poliement, il prend un tableau a une dimension
596
 * 
597
 * @param array $values
598
 * @param string $cur
599
 * @param boolean $onedim
600
 */
601
function eoption($values, $cur, $onedim = false) {
602
    if (is_array($values)) {
603
        foreach ($values as $k => $v) {
604
            if ($onedim) {
605
                $k = $v;
606
            }
607
            echo "<option value=\"$k\"";
608
            if ($k == $cur) {
609
                echo " selected=\"selected\"";
610
            }
611
            echo ">" . $v . "</option>";
612
        }
613
    }
614
}
615
616
/**
617
  /* Echo the HTMLSpecialChars version of a value.
618
 * Must be called when pre-filling fields values in forms such as : 
619
 * <input type="text" name="toto" value="<?php ehe($toto); ?>" />
620
 * Use the charset of the current language for transcription
621
 * 
622
 * @global string $charset
623
 * @param string $str
624
 * @param boolean $affiche
625
 * @return string
626
 */
627
function ehe($str, $affiche = TRUE) {
628
    global $charset;
629
    $retour = htmlspecialchars($str, ENT_QUOTES|ENT_SUBSTITUTE, $charset);
630
    if ($affiche) {
631
        echo $retour;
632
    }
633
    return $retour;
634
}
635
636
/**
637
  /* Echo the URLENCODED version of a value.
638
 * Must be called when pre-filling fields values in URLS such as : 
639
 * document.location='logs_tail.php?file=<?php eue($file); ?>
640
 * Use the charset of the current language for transcription
641
 * 
642
 * @global string $charset
643
 * @param string $str
644
 * @param boolean $affiche
645
 * @return string
646
 */
647
function eue($str, $affiche = TRUE) {
648
    global $charset;
649
    $retour = urlencode($str);
650
    if ($affiche) {
651
        echo $retour;
652
    }
653
    return $retour;
654
}
655
656
/* Get the Fields of the posted form from $_REQUEST or POST or GET
657
 * and check their type
658
 */
659
660
/**
661
 * 
662
 * @param array $fields
663
 * @param boolean $requestOnly
664
 * @return array
665
 */
666
function getFields($fields, $requestOnly = false) {
667
    $vars = array();
668
    $methodType = array("get", "post", "request", "files", "server");
669
670
    foreach ($fields AS $name => $options) {
671
        if (in_array(strtolower($options[0]), $methodType) === false) {
672
            die("Unrecognized method type used for field " . $name . " : " . $options[0]);
673
        }
674
        if ($requestOnly === true) {
675
            $method = "_REQUEST";
676
        } else {
677
            $method = "_" . strtoupper($options[0]);
678
        }
679
        switch ($options[1]) {
680
            case "integer":
681
                $vars[$name] = (isset($GLOBALS[$method][$name]) && is_numeric($GLOBALS[$method][$name]) ? intval($GLOBALS[$method][$name]) : $options[2]);
682
                break;
683
            case "float":
684
                $vars[$name] = (isset($GLOBALS[$method][$name]) && is_numeric($GLOBALS[$method][$name]) ? floatval($GLOBALS[$method][$name]) : $options[2]);
685
                break;
686
            case "string":
687
                $vars[$name] = (isset($GLOBALS[$method][$name]) ? trim($GLOBALS[$method][$name]) : $options[2]);
688
                break;
689
            case "array":
690
                $vars[$name] = (isset($GLOBALS[$method][$name]) && is_array($GLOBALS[$method][$name]) ? $GLOBALS[$method][$name] : $options[2]);
691
                break;
692
            case "boolean":
693
                $vars[$name] = (isset($GLOBALS[$method][$name]) ? $GLOBALS[$method][$name] : $options[2]);
694
                break;
695
            case "file":
696
                $vars[$name] = (isset($GLOBALS[$method][$name]) ? $GLOBALS[$method][$name] : $options[2]);
697
                break;
698
            default:
699
                die("Illegal method type used for field " . $name . " : " . $options[1]);
700
        }
701
    }
702
703
    // Insert into $GLOBALS.
704
    foreach ($vars AS $var => $value) {
705
        $GLOBALS[$var] = $value;
706
    }
707
    return $vars;
708
}
709
710
/**
711
 * 
712
 * @param array $array
713
 */
714
function printVar($array) {
715
    echo "<pre style=\"border: 1px solid black; text-align: left; font-size: 9px\">\n";
716
    print_r($array);
717
    echo "</pre>\n";
718
}
719
720
/**
721
 * 
722
 * @param array $a
723
 * @param array $b
724
 * @return int
725
 */
726
function list_properties_order($a, $b) {
727
    if ($a['label'] == $b['label']) {
728
        return 0;
729
    }
730
    return ($a['label'] < $b['label']) ? -1 : 1;
731
}
732
733
/**
734
 * Shows a pager : Previous page 0 1 2 ... 16 17 18 19 20 ... 35 36 37 Next page
735
 * 
736
 * 
737
 * Arguments are as follow : 
738
 * $offset = the current offset from 0 
739
 * $count = The number of elements shown per page 
740
 * $total = The total number of elements 
741
 * $url = The url to show for each page. %%offset%% will be replace by the proper offset
742
 * $before & $after are HTML code to show before and after the pager **only if the pager is to be shown
743
 * 
744
 * @param int $offset
745
 * @param int $count
746
 * @param int $total
747
 * @param string $url
748
 * @param string $before
749
 * @param string $after
750
 * @param boolean $echo
751
 * @return string
752
 */
753
function pager($offset, $count, $total, $url, $before = "", $after = "", $echo = true) {
754
    $return = "";
755
    $offset = intval($offset);
756
    $count = intval($count);
757
    $total = intval($total);
758
    if ($offset <= 0) {
759
        $offset = "0";
760
    }
761
    if ($count <= 1) {
762
        $count = "1";
763
    }
764
    if ($total <= 0) {
765
        $total = "0";
766
    }
767
    if ($total < $offset) {
768
        $offset = max(0, $total - $count);
769
    }
770
    if ($total <= $count) { // When there is less element than 1 complete page, just don't do anything :-D
771
        return true;
772
    }
773
    $return .= $before;
774
    // Shall-we show previous page link ?
775
    if ($offset) {
776
        $o = max($offset - $count, 0);
777
        $return .= "<a href=\"" . str_replace("%%offset%%", $o, $url) . "\" alt=\"(Ctl/Alt-p)\" title=\"(Alt-p)\" accesskey=\"p\">" . _("Previous Page") . "</a> ";
778
    } else {
779
        $return .= _("Previous Page") . " ";
780
    }
781
782
    if ($total > (2 * $count)) { // On n'affiche le pager central (0 1 2 ...) s'il y a au moins 2 pages.
783
        $return .= " - ";
784
        if (($total < ($count * 10)) && ($total > $count)) {  // moins de 10 pages : 
785
            for ($i = 0; $i < $total / $count; $i++) {
786
                $o = $i * $count;
787
                if ($offset == $o) {
788
                    $return .= $i . " ";
789
                } else {
790
                    $return .= "<a href = \"" . str_replace("%%offset%%", $o, $url) . "\">$i</a> ";
791
                }
792
            }
793
        } else { // Plus de 10 pages, on affiche 0 1 2 , 2 avant et 2 apr�s la page courante, et les 3 dernieres
794
            for ($i = 0; $i <= 2; $i++) {
795
                $o = $i * $count;
796
                if ($offset == $o) {
797
                    $return .= $i . " ";
798
                } else {
799
                    $return .= "<a href=\"" . str_replace("%%offset%%", $o, $url) . "\">$i</a> ";
800
                }
801
            }
802
            if ($offset >= $count && $offset < ($total - 2 * $count)) { // On est entre les milieux ...
803
                // On affiche 2 avant jusque 2 apr�s l'offset courant mais sans d�border sur les indices affich�s autour
804
                $start = max(3, intval($offset / $count) - 2);
805
                $end = min(intval($offset / $count) + 3, intval($total / $count) - 3);
806
                if ($start != 3) {
807
                    $return .= " ... ";
808
                }
809
                for ($i = $start; $i < $end; $i++) {
810
                    $o = $i * $count;
811
                    if ($offset == $o) {
812
                        $return .= $i . " ";
813
                    } else {
814
                        $return .= "<a href=\"" . str_replace("%%offset%%", $o, $url) . "\">$i</a> ";
815
                    }
816
                }
817
                if ($end != intval($total / $count) - 3) {
818
                    $return .= " ... ";
819
                }
820
            } else {
821
                $return .= " ... ";
822
            }
823
            for ($i = intval($total / $count) - 3; $i < $total / $count; $i++) {
824
                $o = $i * $count;
825
                if ($offset == $o) {
826
                    $return .= $i . " ";
827
                } else {
828
                    $return .= "<a href=\"" . str_replace("%%offset%%", $o, $url) . "\">$i</a> ";
829
                }
830
            }
831
            $return .= " - ";
832
        } // More than 10 pages?
833
    }
834
    // Shall-we show the next page link ?
835
    if ($offset + $count < $total) {
836
        $o = $offset + $count;
837
        $return .= "<a href=\"" . str_replace("%%offset%%", $o, $url) . "\" alt=\"(Ctl/Alt-s)\" title=\"(Alt-s)\" accesskey=\"s\">" . _("Next Page") . "</a> ";
838
    } else {
839
        $return .= _("Next Page") . " ";
840
    }
841
    $return .= $after;
842
    if ($echo) {
843
        echo $return;
844
    }
845
    return $return;
846
}
847
848
/**
849
 * 
850
 * @param int $length
851
 * @return string
852
 */
853
function create_pass($length = 8) {
854
    $chars = "1234567890abcdefghijkmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
855
    $i = 0;
856
    $password = "";
857
    while ($i <= $length) {
858
        $password .= @$chars{mt_rand(0, strlen($chars))};
859
        $i++;
860
    }
861
    return $password;
862
}
863
864
/**
865
 *  Affiche un bouton qui permet de generer automatiquement des mots de passes 
866
 * 
867
 * @param int $pass_size
868
 * @param string $fields_to_fill1
869
 * @param string $fields_to_fill2
870
 * @return int
871
 */
872
function display_div_generate_password($pass_size = DEFAULT_PASS_SIZE, $fields_to_fill1 = "", $fields_to_fill2 = "") {
873
    static $id=1;
874
    echo "<div id='z$id' style='display:none;'><a href=\"javascript:generate_password_html('$id',$pass_size,'$fields_to_fill1','$fields_to_fill2');\">";
875
    __("Clic here to generate a password");
876
    echo "</a></div>";
877
    echo "<script type='text/javascript'>$('#z$id').show();</script>";
878
    $id++;
879
    return 0;
880
}
881
882
/**
883
 * Affiche un bouton pour selectionner un dossier sur le serveur 
884
 * 
885
 * @param string    $dir
886
 * @param string    $caller
887
 * @param int       $width
888
 * @param int       $height
889
 */
890
function display_browser($dir = "", $caller = "main.dir", $width = 350, $height = 450) {
891
    // Browser id
892
    static $id=0;
893
    $id++;
894
    $bid = "b" . $id;
895
    echo "<script type=\"text/javascript\">
896
        <!--
897
          $(function() {
898
              $( \"#" . $bid . "\" ).dialog({
899
              autoOpen: false,
900
              width: " . $width . ",
901
              height: " . $height . ",
902
              modal: true,
903
              open: function()
904
                {
905
                    $('.ui-widget-overlay').css('opacity', .70);
906
                    $('.ui-dialog-content').css('background-color', '#F0F0FA');
907
                },
908
            });
909
         
910
            $( \"#bt" . $bid . "\" )
911
              .button()
912
              .attr(\"class\", \"ina\")
913
              .click(function() {
914
                $( \"#" . $bid . "\" ).dialog( \"open\" );
915
                return false;
916
              });
917
          });
918
          
919
          
920
          document.write('&nbsp;<input type=\"button\" id=\"bt" . $bid . "\" value=\"" . _("Choose a folder...") . "\" class=\"ina\">');
921
          document.write('<div id=\"" . $bid . "\" title=\"" . _("Choose a folder...") . "\" style=\"display: none; bgcolor:red;\">');
922
          document.write('  <iframe src=\"/browseforfolder2.php?caller=" . $caller . "&amp;file=" . ehe($dir, false) . "&amp;bid=" . $bid . "\" width=\"" . ($width - 40) . "\" height=\"" . ($height - 64) . "\" frameborder=\"no\" id=\"browseiframe\"></iframe>');
923
          document.write('</div>');
924
        //  -->
925
        </script>
926
        ";
927
}
928
929
/**
930
 *  Converts HSV to RGB values
931
 * -----------------------------------------------------
932
 *  Reference: http://en.wikipedia.org/wiki/HSL_and_HSV
933
 *  Purpose:   Useful for generating colours with
934
 *             same hue-value for web designs.
935
 *  Input:     Hue        (H) Integer 0-360
936
 *             Saturation (S) Integer 0-100
937
 *             Lightness  (V) Integer 0-100
938
 *  Output:    String "R,G,B"
939
 *             Suitable for CSS function RGB().
940
 *  
941
 * @param int   $iH
942
 * @param int   $iS
943
 * @param int   $iV
944
 * @return array
945
 */
946
function fHSVtoRGB($iH, $iS, $iV) {
947
948
    if ($iH < 0) {
949
        $iH = 0;   // Hue:
950
    }
951
    if ($iH > 360) {
952
        $iH = 360; //   0-360
953
    }
954
    if ($iS < 0) {
955
        $iS = 0;   // Saturation:
956
    }
957
    if ($iS > 100) {
958
        $iS = 100; //   0-100
959
    }
960
    if ($iV < 0) {
961
        $iV = 0;   // Lightness:
962
    }
963
    if ($iV > 100) {
964
        $iV = 100; //   0-100
965
    }
966
967
    $dS = $iS / 100.0; // Saturation: 0.0-1.0
968
    $dV = $iV / 100.0; // Lightness:  0.0-1.0
969
    $dC = $dV * $dS;   // Chroma:     0.0-1.0
970
    $dH = $iH / 60.0;  // H-Prime:    0.0-6.0
971
    $dT = $dH;       // Temp variable
972
973
    while ($dT >= 2.0) {
974
        $dT -= 2.0; // php modulus does not work with float
975
    }
976
    $dX = $dC * (1 - abs($dT - 1));     // as used in the Wikipedia link
977
978
    switch ($dH) {
979
        case($dH >= 0.0 && $dH < 1.0):
980
            $dR = $dC;
981
            $dG = $dX;
982
            $dB = 0.0;
983
            break;
984
        case($dH >= 1.0 && $dH < 2.0):
985
            $dR = $dX;
986
            $dG = $dC;
987
            $dB = 0.0;
988
            break;
989
        case($dH >= 2.0 && $dH < 3.0):
990
            $dR = 0.0;
991
            $dG = $dC;
992
            $dB = $dX;
993
            break;
994
        case($dH >= 3.0 && $dH < 4.0):
995
            $dR = 0.0;
996
            $dG = $dX;
997
            $dB = $dC;
998
            break;
999
        case($dH >= 4.0 && $dH < 5.0):
1000
            $dR = $dX;
1001
            $dG = 0.0;
1002
            $dB = $dC;
1003
            break;
1004
        case($dH >= 5.0 && $dH < 6.0):
1005
            $dR = $dC;
1006
            $dG = 0.0;
1007
            $dB = $dX;
1008
            break;
1009
        default:
1010
            $dR = 0.0;
1011
            $dG = 0.0;
1012
            $dB = 0.0;
1013
            break;
1014
    }
1015
1016
    $dM = $dV - $dC;
1017
    $dR += $dM;
1018
    $dG += $dM;
1019
    $dB += $dM;
1020
    $dR *= 255;
1021
    $dG *= 255;
1022
    $dB *= 255;
1023
1024
    return array('r' => round($dR), 'g' => round($dG), 'b' => round($dB));
1025
}
1026
1027
/**
1028
 * 
1029
 * @param int   $hex
1030
 * @return int  
1031
 */
1032
function hexa($hex) {
1033
    $num = dechex($hex);
1034
    return (strlen("$num") >= 2) ? "$num" : "0$num";
1035
}
1036
1037
/**
1038
 * 
1039
 * @param int   $p
1040
 * @return string
1041
 */
1042
function PercentToColor($p = 0) {
1043
    if ($p > 100) {
1044
        $p = 100;
1045
    }
1046
    if ($p < 0) {
1047
        $p = 0;
1048
    }
1049
    // Pour aller de vert a rouge en passant par jaune et orange
1050
    $h = 1 + ((100 - $p) * 130 / 100);
1051
1052
    $rvb = fHSVtoRGB((int) $h, 96, 93);
1053
    $color = "#" . hexa($rvb['r']) . hexa($rvb['g']) . hexa($rvb['b']);
1054
1055
    return $color;
1056
}
1057
1058
/**
1059
 * 
1060
 * @global m_err    $err
1061
 * @global m_mem    $mem
1062
 * @global int          $cuid
1063
 * @return boolean
1064
 */
1065
function panel_lock() {
1066
    global $cuid;
1067
    if ($cuid != 2000) {
1068
        return false;
1069
    }
1070
    return touch(ALTERNC_LOCK_PANEL);
1071
}
1072
1073
/**
1074
 * 
1075
 * @global m_err    $err
1076
 * @global m_mem    $mem
1077
 * @global int          $cuid
1078
 * @return boolean
1079
 */
1080
function panel_unlock() {
1081
    global $cuid;
1082
    if ($cuid != 2000) {
1083
        return false;
1084
    }
1085
    return unlink(ALTERNC_LOCK_PANEL);
1086
}
1087
1088
/**
1089
 * 
1090
 * @return boolean
1091
 */
1092
function panel_islocked() {
1093
    return file_exists(ALTERNC_LOCK_PANEL);
1094
}
1095
1096
1097
/** Give a new CSRF uniq token for a form
1098
 * the session must be up since the CSRF is linked
1099
 * to the session cookie. We also need the $db pdo object
1100
 * @return the csrf cookie to add into a csrf hidden field in your form
1101
 */
1102
function csrf_get($return=false) {
1103
    global $db;
1104
    static $token="";
1105
    if (!isset($_SESSION["csrf"])) {
1106
        $_SESSION["csrf"]=md5(mt_rand().mt_rand().mt_rand());
1107
    }
1108
    if ($token=="") {
1109
      $token=md5(mt_rand().mt_rand().mt_rand());
1110
      $db->query("INSERT INTO csrf SET cookie=?, token=?, created=NOW(), used=0;",array($_SESSION["csrf"],$token));
1111
    }
1112
    if ($return) 
1113
        return $token;
1114
    echo '<input type="hidden" name="csrf" value="'.$token.'" />';
1115
    return true;        
1116
}
1117
1118
/** Check a CSRF token against the current session
1119
 * a token can be only checked once, it's disabled then
1120
 * @param $token string the token to check in the DB + session
1121
 * @return $result integer 0 for invalid token, 1 for good token, -1 for expired token (already used)
0 ignored issues
show
Documentation introduced by
The doc-type $result could not be parsed: Unknown type name "$result" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
1122
 * if a token is invalid or expired, an $err is raised, that can be displayed
1123
 */
1124
function csrf_check($token=null) {
1125
    global $db,$err;
1126
1127
    if (is_null($token)) $token=$_POST["csrf"];
1128
1129
    if (!isset($_SESSION["csrf"])) {
1130
        $err->raise("functions", _("The posted form token is incorrect. Maybe you need to allow cookies"));
1131
        return 0; // no csrf cookie :/
1132
    }
1133
    if (strlen($token)!=32 || strlen($_SESSION["csrf"])!=32) {
1134
        unset($_SESSION["csrf"]);
1135
        $err->raise("functions", _("Your cookie or token is invalid"));
1136
        return 0; // invalid csrf cookie 
1137
    }
1138
    $db->query("SELECT used FROM csrf WHERE cookie=? AND token=?;",array($_SESSION["csrf"],$token));
1139
    if (!$db->next_record()) {
1140
        $err->raise("functions", _("Your token is invalid"));
1141
        return 0; // invalid csrf cookie 
1142
    }
1143
    if ($db->f("used")) {
1144
        $err->raise("functions", _("Your token is expired. Please refill the form."));
1145
        return -1; // expired
1146
    }
1147
    $db->query("UPDATE csrf SET used=1 WHERE cookie=? AND token=?;",array($_SESSION["csrf"],$token)); 
1148
    $db->exec("DELETE FROM csrf WHERE created<DATE_SUB(NOW(), INTERVAL 1 DAY);");
1149
    return 1;
1150
}
1151