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