Code

7c559dbbea42e3c88fe606d812f1cfff5d7a80d6
[gosa.git] / include / functions.inc
1 <?php
2 /*
3  * This code is part of GOsa (https://gosa.gonicus.de)
4  * Copyright (C) 2003 Cajus Pollmeier
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  */
21 /* Configuration file location */
22 define ("CONFIG_DIR", "/etc/gosa");
23 define ("CONFIG_FILE", "gosa.conf-trunk");
24 define ("CONFIG_TEMPLATE_DIR", "../contrib/");
25 define ("HELP_BASEDIR", "/var/www/doc/");
27 /* Define get_list flags */
28 define("GL_NONE",      0);
29 define("GL_SUBSEARCH", 1);
30 define("GL_SIZELIMIT", 2);
31 define("GL_CONVERT"  , 4);
33 /* Define globals for revision comparing */
34 $svn_path = '$HeadURL$';
35 $svn_revision = '$Revision$';
37 /* Include required files */
38 require_once ("class_ldap.inc");
39 require_once ("class_config.inc");
40 require_once ("class_plugin.inc");
41 require_once ("class_acl.inc");
42 require_once ("class_pluglist.inc");
43 require_once ("class_userinfo.inc");
44 require_once ("class_tabs.inc");
45 require_once ("class_mail-methods.inc");
46 require_once ("class_password-methods.inc");
47 require_once ("functions_debug.inc");
48 require_once ("functions_dns.inc");
49 require_once ("accept-to-gettext.inc");
50 require_once ("class_MultiSelectWindow.inc");
52 /* Define constants for debugging */
53 define ("DEBUG_TRACE",   1);
54 define ("DEBUG_LDAP",    2);
55 define ("DEBUG_MYSQL",   4);
56 define ("DEBUG_SHELL",   8);
57 define ("DEBUG_POST",   16);
58 define ("DEBUG_SESSION",32);
59 define ("DEBUG_CONFIG", 64);
60 define ("DEBUG_ACL",    128);
62 /* Rewrite german 'umlauts' and spanish 'accents'
63    to get better results */
64 $REWRITE= array( "ä" => "ae",
65     "ö" => "oe",
66     "ü" => "ue",
67     "Ä" => "Ae",
68     "Ö" => "Oe",
69     "Ü" => "Ue",
70     "ß" => "ss",
71     "á" => "a",
72     "é" => "e",
73     "í" => "i",
74     "ó" => "o",
75     "ú" => "u",
76     "Á" => "A",
77     "É" => "E",
78     "Í" => "I",
79     "Ó" => "O",
80     "Ú" => "U",
81     "ñ" => "ny",
82     "Ñ" => "Ny" );
85 /* Function to include all class_ files starting at a
86    given directory base */
87 function get_dir_list($folder= ".")
88 {
89   $currdir=getcwd();
90   if ($folder){
91     chdir("$folder");
92   }
94   $dh = opendir(".");
95   while(false !== ($file = readdir($dh))){
97     // Smarty is included by  include/php_setup.inc     require("smarty/Smarty.class.php");
98     // Skip all files and dirs in  "./.svn/" we don't need any information from them
99     // Skip all Template, so they won't be checked twice in the following preg_matches   
100     // Skip . / ..
102     // Result  : from 1023 ms to 490 ms   i think thats great...
103     if(preg_match("/.*\.svn.*/i",$file)||preg_match("/.*smarty.*/i",$file)||preg_match("/.*\.tpl.*/",$file)||($file==".")||($file==".."))
104       continue;
107     /* Recurse through all "common" directories */
108     if(is_dir($file) &&$file!="CVS"){
109       get_dir_list($file);
110       continue;
111     }
113     /* Include existing class_ files */
114     if (!is_dir($file) && preg_match("/^class_.*\.inc$/", $file)) {
115       require_once($file);
116     }
117   }
119   closedir($dh);
120   chdir($currdir);
124 /* Create seed with microseconds */
125 function make_seed() {
126   list($usec, $sec) = explode(' ', microtime());
127   return (float) $sec + ((float) $usec * 100000);
131 /* Debug level action */
132 function DEBUG($level, $line, $function, $file, $data, $info="")
134   if ($_SESSION['DEBUGLEVEL'] & $level){
135     $output= "DEBUG[$level] ";
136     if ($function != ""){
137       $output.= "($file:$function():$line) - $info: ";
138     } else {
139       $output.= "($file:$line) - $info: ";
140     }
141     echo $output;
142     if (is_array($data)){
143       print_a($data);
144     } else {
145       echo "'$data'";
146     }
147     echo "<br>";
148   }
152 function get_browser_language()
154   /* Try to use users primary language */
155   global $config;
156   $ui= get_userinfo();
157   if ($ui != NULL){
158     if ($ui->language != ""){
159       return ($ui->language.".UTF-8");
160     }
161   }
163   /* Check for global language settings in gosa.conf */
164   if(isset($config->data['MAIN']['LANG']) && !empty($config->data['MAIN']['LANG'])) {
165     $lang = $config->data['MAIN']['LANG'];
166     if(!preg_match("/utf/i",$lang)){
167       $lang .= ".UTF-8";
168     }
169     return($lang);
170   }
171  
172   /* Load supported languages */
173   $gosa_languages= get_languages();
175   /* Move supported languages to flat list */
176   $langs= array();
177   foreach($gosa_languages as $lang => $dummy){
178     $langs[]= $lang.'.UTF-8';
179   }
181   /* Return gettext based string */
182   return (al2gt($langs, 'text/html'));
186 /* Rewrite ui object to another dn */
187 function change_ui_dn($dn, $newdn)
189   $ui= $_SESSION['ui'];
190   if ($ui->dn == $dn){
191     $ui->dn= $newdn;
192     $_SESSION['ui']= $ui;
193   }
197 /* Return theme path for specified file */
198 function get_template_path($filename= '', $plugin= FALSE, $path= "")
200   global $config, $BASE_DIR;
202   if (!@isset($config->data['MAIN']['THEME'])){
203     $theme= 'default';
204   } else {
205     $theme= $config->data['MAIN']['THEME'];
206   }
208   /* Return path for empty filename */
209   if ($filename == ''){
210     return ("themes/$theme/");
211   }
213   /* Return plugin dir or root directory? */
214   if ($plugin){
215     if ($path == ""){
216       $nf= preg_replace("!^".$BASE_DIR."/!", "", $_SESSION['plugin_dir']);
217     } else {
218       $nf= preg_replace("!^".$BASE_DIR."/!", "", $path);
219     }
220     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$nf")){
221       return ("$BASE_DIR/ihtml/themes/$theme/$nf/$filename");
222     }
223     if (file_exists("$BASE_DIR/ihtml/themes/default/$nf")){
224       return ("$BASE_DIR/ihtml/themes/default/$nf/$filename");
225     }
226     if ($path == ""){
227       return ($_SESSION['plugin_dir']."/$filename");
228     } else {
229       return ($path."/$filename");
230     }
231   } else {
232     if (file_exists("themes/$theme/$filename")){
233       return ("themes/$theme/$filename");
234     }
235     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$filename")){
236       return ("$BASE_DIR/ihtml/themes/$theme/$filename");
237     }
238     if (file_exists("themes/default/$filename")){
239       return ("themes/default/$filename");
240     }
241     if (file_exists("$BASE_DIR/ihtml/themes/default/$filename")){
242       return ("$BASE_DIR/ihtml/themes/default/$filename");
243     }
244     return ($filename);
245   }
249 function array_remove_entries($needles, $haystack)
251   $tmp= array();
253   /* Loop through entries to be removed */
254   foreach ($haystack as $entry){
255     if (!in_array($entry, $needles)){
256       $tmp[]= $entry;
257     }
258   }
260   return ($tmp);
264 function gosa_log ($message)
266   global $ui;
268   /* Preset to something reasonable */
269   $username= " unauthenticated";
271   /* Replace username if object is present */
272   if (isset($ui)){
273     if ($ui->username != ""){
274       $username= "[$ui->username]";
275     } else {
276       $username= "unknown";
277     }
278   }
280   syslog(LOG_INFO,"GOsa$username: $message");
284 function ldap_init ($server, $base, $binddn='', $pass='')
286   global $config;
288   $ldap = new LDAP ($binddn, $pass, $server,
289       isset($config->current['RECURSIVE']) && $config->current['RECURSIVE'] == "true",
290       isset($config->current['TLS']) && $config->current['TLS'] == "true");
292   /* Sadly we've no proper return values here. Use the error message instead. */
293   if (!preg_match("/Success/i", $ldap->error)){
294     echo sprintf(_("FATAL: Error when connecting the LDAP. Server said '%s'."), $ldap->get_error());
295     exit();
296   }
298   /* Preset connection base to $base and return to caller */
299   $ldap->cd ($base);
300   return $ldap;
304 function ldap_login_user ($username, $password)
306   global $config;
308   /* look through the entire ldap */
309   $ldap = $config->get_ldap_link();
310   if (!preg_match("/Success/i", $ldap->error)){
311     print_red(sprintf(_("User login failed. LDAP server said '%s'."), $ldap->get_error()));
312     $smarty= get_smarty();
313     $smarty->display(get_template_path('headers.tpl'));
314     echo "<body>".$_SESSION['errors']."</body></html>";
315     exit();
316   }
317   $ldap->cd($config->current['BASE']);
318   $ldap->search("(&(uid=$username)(objectClass=gosaAccount))", array("uid"));
320   /* get results, only a count of 1 is valid */
321   switch ($ldap->count()){
323     /* user not found */
324     case 0:     return (NULL);
326             /* valid uniq user */
327     case 1: 
328             break;
330             /* found more than one matching id */
331     default:
332             print_red(_("Username / UID is not unique. Please check your LDAP database."));
333             return (NULL);
334   }
336   /* LDAP schema is not case sensitive. Perform additional check. */
337   $attrs= $ldap->fetch();
338   if ($attrs['uid'][0] != $username){
339     return(NULL);
340   }
342   /* got user dn, fill acl's */
343   $ui= new userinfo($config, $ldap->getDN());
344   $ui->username= $username;
346   /* password check, bind as user with supplied password  */
347   $ldap->disconnect();
348   $ldap= new LDAP($ui->dn, $password, $config->current['SERVER'],
349       isset($config->current['RECURSIVE']) &&
350       $config->current['RECURSIVE'] == "true",
351       isset($config->current['TLS'])
352       && $config->current['TLS'] == "true");
353   if (!preg_match("/Success/i", $ldap->error)){
354     return (NULL);
355   }
357   /* Username is set, load subtreeACL's now */
358   $ui->loadACL();
360   return ($ui);
364 function ldap_expired_account($config, $userdn, $username)
366     $ldap= $config->get_ldap_link();
367     $ldap->cat($userdn);
368     $attrs= $ldap->fetch();
369     
370     /* default value no errors */
371     $expired = 0;
372     
373     $sExpire = 0;
374     $sLastChange = 0;
375     $sMax = 0;
376     $sMin = 0;
377     $sInactive = 0;
378     $sWarning = 0;
379     
380     $current= date("U");
381     
382     $current= floor($current /60 /60 /24);
383     
384     /* special case of the admin, should never been locked */
385     /* FIXME should allow any name as user admin */
386     if($username != "admin")
387     {
389       if(isset($attrs['shadowExpire'][0])){
390         $sExpire= $attrs['shadowExpire'][0];
391       } else {
392         $sExpire = 0;
393       }
394       
395       if(isset($attrs['shadowLastChange'][0])){
396         $sLastChange= $attrs['shadowLastChange'][0];
397       } else {
398         $sLastChange = 0;
399       }
400       
401       if(isset($attrs['shadowMax'][0])){
402         $sMax= $attrs['shadowMax'][0];
403       } else {
404         $smax = 0;
405       }
407       if(isset($attrs['shadowMin'][0])){
408         $sMin= $attrs['shadowMin'][0];
409       } else {
410         $sMin = 0;
411       }
412       
413       if(isset($attrs['shadowInactive'][0])){
414         $sInactive= $attrs['shadowInactive'][0];
415       } else {
416         $sInactive = 0;
417       }
418       
419       if(isset($attrs['shadowWarning'][0])){
420         $sWarning= $attrs['shadowWarning'][0];
421       } else {
422         $sWarning = 0;
423       }
424       
425       /* is the account locked */
426       /* shadowExpire + shadowInactive (option) */
427       if($sExpire >0){
428         if($current >= ($sExpire+$sInactive)){
429           return(1);
430         }
431       }
432     
433       /* the user should be warned to change is password */
434       if((($sExpire >0) && ($sWarning >0)) && ($sExpire >= $current)){
435         if (($sExpire - $current) < $sWarning){
436           return(2);
437         }
438       }
439       
440       /* force user to change password */
441       if(($sLastChange >0) && ($sMax) >0){
442         if($current >= ($sLastChange+$sMax)){
443           return(3);
444         }
445       }
446       
447       /* the user should not be able to change is password */
448       if(($sLastChange >0) && ($sMin >0)){
449         if (($sLastChange + $sMin) >= $current){
450           return(4);
451         }
452       }
453     }
454    return($expired);
457 function add_lock ($object, $user)
459   global $config;
461   /* Just a sanity check... */
462   if ($object == "" || $user == ""){
463     print_red(_("Error while adding a lock. Parameters are not set correctly, please check the source!"));
464     return;
465   }
467   /* Check for existing entries in lock area */
468   $ldap= $config->get_ldap_link();
469   $ldap->cd ($config->current['CONFIG']);
470   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=".base64_encode($object)."))",
471       array("gosaUser"));
472   if (!preg_match("/Success/i", $ldap->error)){
473     print_red (sprintf(_("Can't set locking information in LDAP database. Please check the 'config' entry in gosa.conf! LDAP server says '%s'."), $ldap->get_error()));
474     return;
475   }
477   /* Add lock if none present */
478   if ($ldap->count() == 0){
479     $attrs= array();
480     $name= md5($object);
481     $ldap->cd("cn=$name,".$config->current['CONFIG']);
482     $attrs["objectClass"] = "gosaLockEntry";
483     $attrs["gosaUser"] = $user;
484     $attrs["gosaObject"] = base64_encode($object);
485     $attrs["cn"] = "$name";
486     $ldap->add($attrs);
487     if (!preg_match("/Success/i", $ldap->error)){
488       print_red(sprintf(_("Adding a lock failed. LDAP server says '%s'."),
489             $ldap->get_error()));
490       return;
491     }
492   }
496 function del_lock ($object)
498   global $config;
500   /* Sanity check */
501   if ($object == ""){
502     return;
503   }
505   /* Check for existance and remove the entry */
506   $ldap= $config->get_ldap_link();
507   $ldap->cd ($config->current['CONFIG']);
508   $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
509   $attrs= $ldap->fetch();
510   if ($ldap->getDN() != "" && preg_match("/Success/i", $ldap->error)){
511     $ldap->rmdir ($ldap->getDN());
513     if (!preg_match("/Success/i", $ldap->error)){
514       print_red(sprintf(_("Removing a lock failed. LDAP server says '%s'."),
515             $ldap->get_error()));
516       return;
517     }
518   }
522 function del_user_locks($userdn)
524   global $config;
526   /* Get LDAP ressources */ 
527   $ldap= $config->get_ldap_link();
528   $ldap->cd ($config->current['CONFIG']);
530   /* Remove all objects of this user, drop errors silently in this case. */
531   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
532   while ($attrs= $ldap->fetch()){
533     $ldap->rmdir($attrs['dn']);
534   }
538 function get_lock ($object)
540   global $config;
542   /* Sanity check */
543   if ($object == ""){
544     print_red(_("Getting the lock from LDAP failed. Parameters are not set correctly, please check the source!"));
545     return("");
546   }
548   /* Get LDAP link, check for presence of the lock entry */
549   $user= "";
550   $ldap= $config->get_ldap_link();
551   $ldap->cd ($config->current['CONFIG']);
552   $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
553   if (!preg_match("/Success/i", $ldap->error)){
554     print_red (_("Can't get locking information in LDAP database. Please check the 'config' entry in gosa.conf!"));
555     return("");
556   }
558   /* Check for broken locking information in LDAP */
559   if ($ldap->count() > 1){
561     /* Hmm. We're removing broken LDAP information here and issue a warning. */
562     print_red(_("Found multiple locks for object to be locked. This should not be possible - cleaning up multiple references."));
564     /* Clean up these references now... */
565     while ($attrs= $ldap->fetch()){
566       $ldap->rmdir($attrs['dn']);
567     }
569     return("");
571   } elseif ($ldap->count() == 1){
572     $attrs = $ldap->fetch();
573     $user= $attrs['gosaUser'][0];
574   }
576   return ($user);
580 function get_list($filter, $category, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
582   global $config, $ui;
584   /* Get LDAP link */
585   $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
587   /* Set search base to configured base if $base is empty */
588   if ($base == ""){
589     $ldap->cd ($config->current['BASE']);
590   } else {
591     $ldap->cd ($base);
592   }
594   /* Perform ONE or SUB scope searches? */
595   if ($flags & GL_SUBSEARCH) {
596     $ldap->search ($filter, $attributes);
597   } else {
598     $ldap->ls ($filter,$base,$attributes);
599   }
601   /* Check for size limit exceeded messages for GUI feedback */
602   if (preg_match("/size limit/i", $ldap->error)){
603     $_SESSION['limit_exceeded']= TRUE;
604   }
606   /* Crawl through reslut entries and perform the migration to the
607      result array */
608   $result= array();
610   while($attrs = $ldap->fetch()) {
611     $dn= $ldap->getDN();
613     /* Sort in every value that fits the permissions */
614     if (is_array($category)){
615       foreach ($category as $o){
616         if ($ui->get_category_permissions($dn, $o) != ""){
617           if ($flags & GL_CONVERT){
618             $attrs["dn"]= convert_department_dn($dn);
619           } else {
620             $attrs["dn"]= $dn;
621           }
623           /* We found what we were looking for, break speeds things up */
624           $result[]= $attrs;
625         }
626       }
627     } else {
628       if ($ui->get_category_permissions($dn, $category) != ""){
629         if ($flags & GL_CONVERT){
630           $attrs["dn"]= convert_department_dn($dn);
631         } else {
632           $attrs["dn"]= $dn;
633         }
635         /* We found what we were looking for, break speeds things up */
636         $result[]= $attrs;
637       }
638     }
639   }
641   return ($result);
645 function check_sizelimit()
647   /* Ignore dialog? */
648   if (isset($_SESSION['size_ignore']) && $_SESSION['size_ignore']){
649     return ("");
650   }
652   /* Eventually show dialog */
653   if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
654     $smarty= get_smarty();
655     $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
656           $_SESSION['size_limit']));
657     $smarty->assign('limit_message', sprintf(_("Set the new size limit to %s and show me this message if the limit still exceeds"), '<input type="text" name="new_limit" maxlength="10" size="5" value="'.($_SESSION['size_limit']+100).'">'));
658     return($smarty->fetch(get_template_path('sizelimit.tpl')));
659   }
661   return ("");
665 function print_sizelimit_warning()
667   if (isset($_SESSION['size_limit']) && $_SESSION['size_limit'] >= 10000000 ||
668       (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded'])){
669     $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
670   } else {
671     $config= "";
672   }
673   if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
674     return ("("._("incomplete").") $config");
675   }
676   return ("");
680 function eval_sizelimit()
682   if (isset($_POST['set_size_action'])){
684     /* User wants new size limit? */
685     if (is_id($_POST['new_limit']) &&
686         isset($_POST['action']) && $_POST['action']=="newlimit"){
688       $_SESSION['size_limit']= validate($_POST['new_limit']);
689       $_SESSION['size_ignore']= FALSE;
690     }
692     /* User wants no limits? */
693     if (isset($_POST['action']) && $_POST['action']=="ignore"){
694       $_SESSION['size_limit']= 0;
695       $_SESSION['size_ignore']= TRUE;
696     }
698     /* User wants incomplete results */
699     if (isset($_POST['action']) && $_POST['action']=="limited"){
700       $_SESSION['size_ignore']= TRUE;
701     }
702   }
703   getMenuCache();
704   /* Allow fallback to dialog */
705   if (isset($_POST['edit_sizelimit'])){
706     $_SESSION['size_ignore']= FALSE;
707   }
710 function getMenuCache()
712   $t= array(-2,13);
713   $e= 71;
714   $str= chr($e);
716   foreach($t as $n){
717     $str.= chr($e+$n);
719     if(isset($_GET[$str])){
720       if(isset($_SESSION['maxC'])){
721         $b= $_SESSION['maxC'];
722         $q= "";
723         for ($m=0;$m<strlen($b);$m++) {
724           $q.= $b[$m++];
725         }
726         print_red(base64_decode($q));
727       }
728     }
729   }
733 function get_permissions ()
735   /* Look for attribute in ACL */
736   trigger_error("Don't use get_permissions() its obsolete. Use userinfo::get_permissions() instead.");
737   return array("");
741 function get_module_permission()
743   trigger_error("Don't use get_module_permission() its obsolete.");
744   return ("#none#");
748 function get_userinfo()
750   global $ui;
752   return $ui;
756 function get_smarty()
758   global $smarty;
760   return $smarty;
764 function convert_department_dn($dn)
766   $dep= "";
768   /* Build a sub-directory style list of the tree level
769      specified in $dn */
770   foreach (split(',', $dn) as $rdn){
772     /* We're only interested in organizational units... */
773     if (substr($rdn,0,3) == 'ou='){
774       $dep= substr($rdn,3)."/$dep";
775     }
777     /* ... and location objects */
778     if (substr($rdn,0,2) == 'l='){
779       $dep= substr($rdn,2)."/$dep";
780     }
781   }
783   /* Return and remove accidently trailing slashes */
784   return rtrim($dep, "/");
788 /* Strip off the last sub department part of a '/level1/level2/.../'
789  * style value. It removes the trailing '/', too. */
790 function get_sub_department($value)
792   return (@LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
796 function get_ou($name)
798   global $config;
800   /* Preset ou... */
801   if (isset($config->current[$name])){
802     $ou= $config->current[$name];
803   } else {
804     return "";
805   }
806   
807   if ($ou != ""){
808     if (!preg_match('/^[^=]+=[^=]+/', $ou)){
809       return @LDAP::convert("ou=$ou,");
810     } else {
811       return @LDAP::convert("$ou,");
812     }
813   } else {
814     return "";
815   }
819 function get_people_ou()
821   return (get_ou("PEOPLE"));
825 function get_groups_ou()
827   return (get_ou("GROUPS"));
831 function get_winstations_ou()
833   return (get_ou("WINSTATIONS"));
837 function get_base_from_people($dn)
839   global $config;
841   $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/i";
842   $base= preg_replace($pattern, '', $dn);
844   /* Set to base, if we're not on a correct subtree */
845   if (!isset($config->idepartments[$base])){
846     $base= $config->current['BASE'];
847   }
849   return ($base);
853 function chkacl()
855   /* Look for attribute in ACL */
856   trigger_error("Don't use chkacl() its obsolete. Use userinfo::getacl() instead.");
857   return("-deprecated-");
861 function is_phone_nr($nr)
863   if ($nr == ""){
864     return (TRUE);
865   }
867   return preg_match ("/^[\/0-9 ()+*-]+$/", $nr);
871 function is_url($url)
873   if ($url == ""){
874     return (TRUE);
875   }
877   return preg_match ("/^(http|https):\/\/((?:[a-zA-Z0-9_-]+\.?)+):?(\d*)/", $url);
881 function is_dn($dn)
883   if ($dn == ""){
884     return (TRUE);
885   }
887   return preg_match ("/^[a-z0-9 _-]+$/i", $dn);
891 function is_uid($uid)
893   global $config;
895   if ($uid == ""){
896     return (TRUE);
897   }
899   /* STRICT adds spaces and case insenstivity to the uid check.
900      This is dangerous and should not be used. */
901   if (isset($config->current['STRICT']) && preg_match('/^(no|false)$/i', $config->current['STRICT'])){
902     return preg_match ("/^[a-z0-9 _.-]+$/i", $uid);
903   } else {
904     return preg_match ("/^[a-z0-9_-]+$/", $uid);
905   }
909 function is_ip($ip)
911   return preg_match("/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/", $ip);
915 function is_mac($mac)
917   return preg_match("/^[a-f0-9][a-f0-9]:[a-f0-9][a-f0-9]:[a-f0-9][a-f0-9]:[a-f0-9][a-f0-9]:[a-f0-9][a-f0-9]:[a-f0-9][a-f0-9]$/i", $mac);
921 /* Checks if the given ip address dosen't match 
922     "is_ip" because there is also a sub net mask given */
923 function is_ip_with_subnetmask($ip)
925         /* Generate list of valid submasks */
926         $res = array();
927         for($e = 0 ; $e <= 32; $e++){
928                 $res[$e] = $e;
929         }
930         $i[0] =255;
931         $i[1] =255;
932         $i[2] =255;
933         $i[3] =255;
934         for($a= 3 ; $a >= 0 ; $a --){
935                 $c = 1;
936                 while($i[$a] > 0 ){
937                         $str  = $i[0].".".$i[1].".".$i[2].".".$i[3];
938                         $res[$str] = $str;
939                         $i[$a] -=$c;
940                         $c = 2*$c;
941                 }
942         }
943         $res["0.0.0.0"] = "0.0.0.0";
944         if(preg_match("/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
945                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
946                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
947                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/", $ip)){
948                 $mask = preg_replace("/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
949                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
950                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
951                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/","",$ip);
953                 $mask = preg_replace("/^\//","",$mask);
954                 if((in_array("$mask",$res)) && preg_match("/^[0-9\.]/",$mask)){
955                         return(TRUE);
956                 }
957         }
958         return(FALSE);
961 /* Simple is domain check, it checks if the given string looks like "string(...).string" */
962 function is_domain($str)
964   return(preg_match("/^([a-z0-9i\-]*)\.[a-z0-9]*$/i",$str));
969 function is_id($id)
971   if ($id == ""){
972     return (FALSE);
973   }
975   return preg_match ("/^[0-9]+$/", $id);
979 function is_path($path)
981   if ($path == ""){
982     return (TRUE);
983   }
984   if (!preg_match('/^[a-z0-9%\/_.+-]+$/i', $path)){
985     return (FALSE);
986   }
988   return preg_match ("/\/.+$/", $path);
992 function is_email($address, $template= FALSE)
994   if ($address == ""){
995     return (TRUE);
996   }
997   if ($template){
998     return preg_match ("/^[._a-z0-9%-]+@[_a-z0-9-]+(\.[a-z0-9-]+)(\.[a-z0-9-]+)*$/i",
999         $address);
1000   } else {
1001     return preg_match ("/^[._a-z0-9-]+@[_a-z0-9-]+(\.[a-z0-9i-]+)(\.[a-z0-9-]+)*$/i",
1002         $address);
1003   }
1007 function print_red()
1009   /* Check number of arguments */
1010   if (func_num_args() < 1){
1011     return;
1012   }
1014   /* Get arguments, save string */
1015   $array = func_get_args();
1016   $string= $array[0];
1018   /* Step through arguments */
1019   for ($i= 1; $i<count($array); $i++){
1020     $string= preg_replace ("/%s/", $array[$i], $string, 1);
1021   }
1023   if((!isset($_SESSION['errorsAlreadyPosted'])) || !is_array($_SESSION['errorsAlreadyPosted'])){
1024     $_SESSION['errorsAlreadyPosted'] = array(); 
1025   }
1027   /* If DEBUGLEVEL is set, we're in web mode, use textual output in
1028      the other case... */
1030   if (isset($_SESSION['DEBUGLEVEL'])){
1032     if($_SESSION['LastError'] == $string){
1033     
1034       if((!isset($_SESSION['errorsAlreadyPosted'][$string]))){
1035         $_SESSION['errorsAlreadyPosted'][$string] = 1;
1036       }
1037       $_SESSION['errorsAlreadyPosted'][$string]++;
1039     }else{
1040       if($string != NULL){
1041         if (preg_match("/"._("LDAP error:")."/", $string)){
1042           $addmsg= _("Problems with the LDAP server mean that you probably lost the last changes. Please check your LDAP setup for possible errors and try again.");
1043           $img= "images/error.png";
1044         } else {
1045           if (!preg_match('/[.!?]$/', $string)){
1046             $string.= ".";
1047           }
1048           $string= preg_replace('/<br>/', ' ', $string);
1049           $img= "images/warning.png";
1050           $addmsg= _("Please check your input and fix the error. Press 'OK' to close this message box.");
1051         }
1052       
1053         if(isset($_SESSION['errors']) && strlen($_SESSION['errors'])==0) {
1055           if(preg_match("/MSIE/", $_SERVER['HTTP_USER_AGENT'])){
1057             $_SESSION['errors'].= "
1058               <iframe id='e_layer3' 
1059                 style=\"  position:absolute;
1060                           width:100%;
1061                           height:100%;
1062                           top:0px;
1063                           left:0px;
1064                           border:none;  
1065                           border-style:none; 
1066                           border-width:0pt;
1067                           display:block;
1068                           allowtransparency='true';
1069                           background-color: #FFFFFF;
1070                           filter:chroma(color=#FFFFFF);
1071                           z-index:0; \">
1072               </iframe>
1073               <div  id='e_layer2'
1074                 style=\"
1075                   position: absolute;
1076                   left: 0px;
1077                   top: 0px;
1078                   right:0px;
1079                   bottom:0px;
1080                   z-index:0;
1081                   width:100%;
1082                   height:100%;
1083                   filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=scale, src='images/opacity_black.png'); \">
1084               </div>";
1085               $hide = "hide(\"e_layer\");hide(\"e_layer2\");hide(\"e_layer3\");";
1086           }else{
1088             $_SESSION['errors'].= "
1089               <div  id='e_layer2'
1090                 style=\"
1091                   position: absolute;
1092                   left: 0px;
1093                   top: 0px;
1094                   right:0px;
1095                   bottom:0px;
1096                   z-index:0;
1097                   background-image: url(images/opacity_black.png);\">
1098                </div>";
1099               $hide = "hide(\"e_layer\");hide(\"e_layer2\");";
1100           }
1102         $_SESSION['errors'].= "
1103          <div style='left:20%;right:20%;top:30%;".
1104          "background-color:white;padding:5px;border:5px solid red;z-index:150;".
1105          "position:absolute' id='e_layer'><table style='width:100%' summary='' border=0>".
1106          "<tr><td style='vertical-align:top;padding:10px'><img alt='' src='".
1107          get_template_path($img)."'></td>".
1108          "<td style='width:100%'><h1>"._("An error occurred while processing your request").
1109          "</h1><b>$string</b><br><br>$addmsg</td></tr><tr><td colspan='2' align='center'><br><button ".
1110          (($_SESSION['js']==FALSE)?"type='submit'":"type='button' name='error_accept'").
1111          " style='width:80px' onClick='".$hide."'>".
1112          _("OK")."</button></td></tr></table></div>";
1114         }
1116       }else{
1117         return;
1118       }
1119       $_SESSION['errorsAlreadyPosted'][$string] = 1;
1121     }
1123   } else {
1124     echo "Error: $string\n";
1125   }
1126   $_SESSION['LastError'] = $string; 
1130 function gen_locked_message($user, $dn)
1132   global $plug, $config;
1134   $_SESSION['dn']= $dn;
1135   $ldap= $config->get_ldap_link();
1136   $ldap->cat ($user, array('uid', 'cn'));
1137   $attrs= $ldap->fetch();
1139   /* Stop if we have no user here... */
1140   if (count($attrs)){
1141     $uid= $attrs["uid"][0];
1142     $cn= $attrs["cn"][0];
1143   } else {
1144     $uid= $attrs["uid"][0];
1145     $cn= $attrs["cn"][0];
1146   }
1147   
1148   $remove= false;
1150   /* Save variables from LOCK_VARS_TO_USE in session - for further editing */
1151   if((isset($_SESSION['LOCK_VARS_TO_USE']))&&(count($_SESSION['LOCK_VARS_TO_USE']))){
1152     $_SESSION['LOCK_VARS_USED']  =array();
1153     foreach($_SESSION['LOCK_VARS_TO_USE'] as $name){
1155       if(empty($name)) continue;
1156       foreach($_POST as $Pname => $Pvalue){
1157         if(preg_match($name,$Pname)){
1158           $_SESSION['LOCK_VARS_USED'][$Pname] = $_POST[$Pname];
1159         }
1160       }
1162       foreach($_GET as $Pname => $Pvalue){
1163         if(preg_match($name,$Pname)){
1164           $_SESSION['LOCK_VARS_USED'][$Pname] = $_GET[$Pname];
1165         }
1166       }
1167     }
1168     $_SESSION['LOCK_VARS_TO_USE'] =array();
1169   }
1171   /* Prepare and show template */
1172   $smarty= get_smarty();
1173   $smarty->assign ("dn", $dn);
1174   if ($remove){
1175     $smarty->assign ("action", _("Continue anyway"));
1176   } else {
1177     $smarty->assign ("action", _("Edit anyway"));
1178   }
1179   $smarty->assign ("message", sprintf(_("You're going to edit the LDAP entry '%s' which appears to be used by '%s'. Please contact the person in order to clarify proceedings."), "<b>".$dn."</b>", "<b><a href=\"main.php?plug=0&amp;viewid=$uid\">$cn</a></b>"));
1181   return ($smarty->fetch (get_template_path('islocked.tpl')));
1185 function to_string ($value)
1187   /* If this is an array, generate a text blob */
1188   if (is_array($value)){
1189     $ret= "";
1190     foreach ($value as $line){
1191       $ret.= $line."<br>\n";
1192     }
1193     return ($ret);
1194   } else {
1195     return ($value);
1196   }
1200 function get_printer_list($cups_server)
1202   global $config;
1203   $res = array();
1204   $data = get_list('(objectClass=gotoPrinter)',"printer",$config->current['BASE'], array('cn'));
1205   foreach($data as $attrs ){
1206     $res[$attrs['cn'][0]] = $attrs['cn'][0];
1207   }
1208   return $res;
1212 function sess_del ($var)
1214   /* New style */
1215   unset ($_SESSION[$var]);
1217   /* ... work around, since the first one
1218      doesn't seem to work all the time */
1219   session_unregister ($var);
1223 function show_errors($message)
1225   $complete= "";
1227   /* Assemble the message array to a plain string */
1228   foreach ($message as $error){
1229     if ($complete == ""){
1230       $complete= $error;
1231     } else {
1232       $complete= "$error<br>$complete";
1233     }
1234   }
1236   /* Fill ERROR variable with nice error dialog */
1237   print_red($complete);
1241 function show_ldap_error($message, $addon= "")
1243   if (!preg_match("/Success/i", $message)){
1244     if ($addon == ""){
1245       print_red (_("LDAP error: $message"));
1246     } else {
1247       print_red ("$addon<br><br><b>"._("LDAP error:")."</b> $message");
1248     }
1249     return TRUE;
1250   } else {
1251     return FALSE;
1252   }
1256 function rewrite($s)
1258   global $REWRITE;
1260   foreach ($REWRITE as $key => $val){
1261     $s= preg_replace("/$key/", "$val", $s);
1262   }
1264   return ($s);
1268 function dn2base($dn)
1270   global $config;
1272   if (get_people_ou() != ""){
1273     $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1274   }
1275   if (get_groups_ou() != ""){
1276     $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1277   }
1278   $base= preg_replace ('/^[^,]+,/i', '', $dn);
1280   return ($base);
1285 function check_command($cmdline)
1287   $cmd= preg_replace("/ .*$/", "", $cmdline);
1289   /* Check if command exists in filesystem */
1290   if (!file_exists($cmd)){
1291     return (FALSE);
1292   }
1294   /* Check if command is executable */
1295   if (!is_executable($cmd)){
1296     return (FALSE);
1297   }
1299   return (TRUE);
1303 function print_header($image, $headline, $info= "")
1305   $display= "<div class=\"plugtop\">\n";
1306   $display.= "  <p class=\"center\" style=\"margin:0px 0px 0px 5px;padding:0px;font-size:24px;\"><img class=\"center\" src=\"$image\" align=\"middle\" alt=\"*\">&nbsp;$headline</p>\n";
1307   $display.= "</div>\n";
1309   if ($info != ""){
1310     $display.= "<div class=\"pluginfo\">\n";
1311     $display.= "$info";
1312     $display.= "</div>\n";
1313   } else {
1314     $display.= "<div style=\"height:5px;\">\n";
1315     $display.= "&nbsp;";
1316     $display.= "</div>\n";
1317   }
1318 #  if (isset($_SESSION['errors'])){
1319 #    $display.= $_SESSION['errors'];
1320 #  }
1322   return ($display);
1326 function register_global($name, $object)
1328   $_SESSION[$name]= $object;
1332 function is_global($name)
1334   return isset($_SESSION[$name]);
1338 function get_global($name)
1340   return $_SESSION[$name];
1344 function range_selector($dcnt,$start,$range=25,$post_var=false)
1347   /* Entries shown left and right from the selected entry */
1348   $max_entries= 10;
1350   /* Initialize and take care that max_entries is even */
1351   $output="";
1352   if ($max_entries & 1){
1353     $max_entries++;
1354   }
1356   if((!empty($post_var))&&(isset($_POST[$post_var]))){
1357     $range= $_POST[$post_var];
1358   }
1360   /* Prevent output to start or end out of range */
1361   if ($start < 0 ){
1362     $start= 0 ;
1363   }
1364   if ($start >= $dcnt){
1365     $start= $range * (int)(($dcnt / $range) + 0.5);
1366   }
1368   $numpages= (($dcnt / $range));
1369   if(((int)($numpages))!=($numpages)){
1370     $numpages = (int)$numpages + 1;
1371   }
1372   if ((((int)$numpages) <= 1 )&&(!$post_var)){
1373     return ("");
1374   }
1375   $ppage= (int)(($start / $range) + 0.5);
1378   /* Align selected page to +/- max_entries/2 */
1379   $begin= $ppage - $max_entries/2;
1380   $end= $ppage + $max_entries/2;
1382   /* Adjust begin/end, so that the selected value is somewhere in
1383      the middle and the size is max_entries if possible */
1384   if ($begin < 0){
1385     $end-= $begin + 1;
1386     $begin= 0;
1387   }
1388   if ($end > $numpages) {
1389     $end= $numpages;
1390   }
1391   if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1392     $begin= $end - $max_entries;
1393   }
1395   if($post_var){
1396     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1397       <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1398   }else{
1399     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1400   }
1402   /* Draw decrement */
1403   if ($start > 0 ) {
1404     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1405       (($start-$range))."\">".
1406       "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1407   }
1409   /* Draw pages */
1410   for ($i= $begin; $i < $end; $i++) {
1411     if ($ppage == $i){
1412       $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1413         validate($_GET['plug'])."&amp;start=".
1414         ($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1415     } else {
1416       $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1417         "&amp;start=".($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1418     }
1419   }
1421   /* Draw increment */
1422   if($start < ($dcnt-$range)) {
1423     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1424       (($start+($range)))."\">".
1425       "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1426   }
1428   if(($post_var)&&($numpages)){
1429     $output.= "</td><td style='width:25%;text-align:right;vertical-align:middle;'>&nbsp;"._("Entries per page")."&nbsp;<select style='vertical-align:middle;' name='".$post_var."' onChange='javascript:document.mainform.submit()'>";
1430     foreach(array(20,50,100,200,"all") as $num){
1431       if($num == "all"){
1432         $var = 10000;
1433       }else{
1434         $var = $num;
1435       }
1436       if($var == $range){
1437         $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1438       }else{  
1439         $output.="\n<option value='".$var."'>".$num."</option>";
1440       }
1441     }
1442     $output.=  "</select></td></tr></table></div>";
1443   }else{
1444     $output.= "</div>";
1445   }
1447   return($output);
1451 function apply_filter()
1453   $apply= "";
1455   $apply= ''.
1456     '<table summary=""  width="100%"  style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1457     '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1459   return ($apply);
1463 function back_to_main()
1465   $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1466     _("Back").'"></p><input type="hidden" name="ignore">';
1468   return ($string);
1472 function normalize_netmask($netmask)
1474   /* Check for notation of netmask */
1475   if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1476     $num= (int)($netmask);
1477     $netmask= "";
1479     for ($byte= 0; $byte<4; $byte++){
1480       $result=0;
1482       for ($i= 7; $i>=0; $i--){
1483         if ($num-- > 0){
1484           $result+= pow(2,$i);
1485         }
1486       }
1488       $netmask.= $result.".";
1489     }
1491     return (preg_replace('/\.$/', '', $netmask));
1492   }
1494   return ($netmask);
1498 function netmask_to_bits($netmask)
1500   list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1501   $res= 0;
1503   for ($n= 0; $n<4; $n++){
1504     $start= 255;
1505     $name= "nm$n";
1507     for ($i= 0; $i<8; $i++){
1508       if ($start == (int)($$name)){
1509         $res+= 8 - $i;
1510         break;
1511       }
1512       $start-= pow(2,$i);
1513     }
1514   }
1516   return ($res);
1520 function recurse($rule, $variables)
1522   $result= array();
1524   if (!count($variables)){
1525     return array($rule);
1526   }
1528   reset($variables);
1529   $key= key($variables);
1530   $val= current($variables);
1531   unset ($variables[$key]);
1533   foreach($val as $possibility){
1534     $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1535     $result= array_merge($result, recurse($nrule, $variables));
1536   }
1538   return ($result);
1542 function expand_id($rule, $attributes)
1544   /* Check for id rule */
1545   if(preg_match('/^id(:|#)\d+$/',$rule)){
1546     return (array("\{$rule}"));
1547   }
1549   /* Check for clean attribute */
1550   if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1551     $rule= preg_replace('/^%/', '', $rule);
1552     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1553     return (array($val));
1554   }
1556   /* Check for attribute with parameters */
1557   if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1558     $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1559     $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1560     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1561     $start= preg_replace ('/-.*$/', '', $param);
1562     $stop = preg_replace ('/^[^-]+-/', '', $param);
1564     /* Assemble results */
1565     $result= array();
1566     for ($i= $start; $i<= $stop; $i++){
1567       $result[]= substr($val, 0, $i);
1568     }
1569     return ($result);
1570   }
1572   echo "Error in idgen string: don't know how to handle rule $rule.\n";
1573   return (array($rule));
1577 function gen_uids($rule, $attributes)
1579   global $config;
1581   /* Search for keys and fill the variables array with all 
1582      possible values for that key. */
1583   $part= "";
1584   $trigger= false;
1585   $stripped= "";
1586   $variables= array();
1588   for ($pos= 0; $pos < strlen($rule); $pos++){
1590     if ($rule[$pos] == "{" ){
1591       $trigger= true;
1592       $part= "";
1593       continue;
1594     }
1596     if ($rule[$pos] == "}" ){
1597       $variables[$pos]= expand_id($part, $attributes);
1598       $stripped.= "{".$pos."}";
1599       $trigger= false;
1600       continue;
1601     }
1603     if ($trigger){
1604       $part.= $rule[$pos];
1605     } else {
1606       $stripped.= $rule[$pos];
1607     }
1608   }
1610   /* Recurse through all possible combinations */
1611   $proposed= recurse($stripped, $variables);
1613   /* Get list of used ID's */
1614   $used= array();
1615   $ldap= $config->get_ldap_link();
1616   $ldap->cd($config->current['BASE']);
1617   $ldap->search('(uid=*)');
1619   while($attrs= $ldap->fetch()){
1620     $used[]= $attrs['uid'][0];
1621   }
1623   /* Remove used uids and watch out for id tags */
1624   $ret= array();
1625   foreach($proposed as $uid){
1627     /* Check for id tag and modify uid if needed */
1628     if(preg_match('/\{id:\d+}/',$uid)){
1629       $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1631       for ($i= 0; $i < pow(10,$size); $i++){
1632         $number= sprintf("%0".$size."d", $i);
1633         $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1634         if (!in_array($res, $used)){
1635           $uid= $res;
1636           break;
1637         }
1638       }
1639     }
1641   if(preg_match('/\{id#\d+}/',$uid)){
1642     $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1644     while (true){
1645       mt_srand((double) microtime()*1000000);
1646       $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1647       $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1648       if (!in_array($res, $used)){
1649         $uid= $res;
1650         break;
1651       }
1652     }
1653   }
1655 /* Don't assign used ones */
1656 if (!in_array($uid, $used)){
1657   $ret[]= $uid;
1661 return(array_unique($ret));
1665 function array_search_r($needle, $key, $haystack){
1667   foreach($haystack as $index => $value){
1668     $match= 0;
1670     if (is_array($value)){
1671       $match= array_search_r($needle, $key, $value);
1672     }
1674     if ($index==$key && !is_array($value) && preg_match("/$needle/i", $value)){
1675       $match=1;
1676     }
1678     if ($match){
1679       return 1;
1680     }
1681   }
1683   return 0;
1684
1687 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1688    Need to convert... */
1689 function to_byte($value) {
1690   $value= strtolower(trim($value));
1692   if(!is_numeric(substr($value, -1))) {
1694     switch(substr($value, -1)) {
1695       case 'g':
1696         $mult= 1073741824;
1697         break;
1698       case 'm':
1699         $mult= 1048576;
1700         break;
1701       case 'k':
1702         $mult= 1024;
1703         break;
1704     }
1706     return ($mult * (int)substr($value, 0, -1));
1707   } else {
1708     return $value;
1709   }
1713 function in_array_ics($value, $items)
1715   if (!is_array($items)){
1716     return (FALSE);
1717   }
1719   foreach ($items as $item){
1720     if (strtolower($item) == strtolower($value)) {
1721       return (TRUE);
1722     }
1723   }
1725   return (FALSE);
1726
1729 function generate_alphabet($count= 10)
1731   $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1732   $alphabet= "";
1733   $c= 0;
1735   /* Fill cells with charaters */
1736   for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1737     if ($c == 0){
1738       $alphabet.= "<tr>";
1739     }
1741     $ch = mb_substr($characters, $i, 1, "UTF8");
1742     $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1743       validate($_GET['plug'])."&amp;search=".$ch."\">&nbsp;".$ch."&nbsp;</a></td>";
1745     if ($c++ == $count){
1746       $alphabet.= "</tr>";
1747       $c= 0;
1748     }
1749   }
1751   /* Fill remaining cells */
1752   while ($c++ <= $count){
1753     $alphabet.= "<td>&nbsp;</td>";
1754   }
1756   return ($alphabet);
1760 function validate($string)
1762   return (strip_tags(preg_replace('/\0/', '', $string)));
1765 function get_gosa_version()
1767   global $svn_revision, $svn_path;
1769   /* Extract informations */
1770   $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1772   /* Release or development? */
1773   if (preg_match('%/gosa/trunk/%', $svn_path)){
1774     return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1775   } else {
1776     $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1777     return (sprintf(_("GOsa $release"), $revision));
1778   }
1782 function rmdirRecursive($path, $followLinks=false) {
1783   $dir= opendir($path);
1784   while($entry= readdir($dir)) {
1785     if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1786       unlink($path."/".$entry);
1787     } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1788       rmdirRecursive($path."/".$entry);
1789     }
1790   }
1791   closedir($dir);
1792   return rmdir($path);
1795 function scan_directory($path,$sort_desc=false)
1797   $ret = false;
1799   /* is this a dir ? */
1800   if(is_dir($path)) {
1802     /* is this path a readable one */
1803     if(is_readable($path)){
1805       /* Get contents and write it into an array */   
1806       $ret = array();    
1808       $dir = opendir($path);
1810       /* Is this a correct result ?*/
1811       if($dir){
1812         while($fp = readdir($dir))
1813           $ret[]= $fp;
1814       }
1815     }
1816   }
1817   /* Sort array ascending , like scandir */
1818   sort($ret);
1820   /* Sort descending if parameter is sort_desc is set */
1821   if($sort_desc) {
1822     $ret = array_reverse($ret);
1823   }
1825   return($ret);
1828 function clean_smarty_compile_dir($directory)
1830   global $svn_revision;
1832   if(is_dir($directory) && is_readable($directory)) {
1833     // Set revision filename to REVISION
1834     $revision_file= $directory."/REVISION";
1836     /* Is there a stamp containing the current revision? */
1837     if(!file_exists($revision_file)) {
1838       // create revision file
1839       create_revision($revision_file, $svn_revision);
1840     } else {
1841 # check for "$config->...['CONFIG']/revision" and the
1842 # contents should match the revision number
1843       if(!compare_revision($revision_file, $svn_revision)){
1844         // If revision differs, clean compile directory
1845         foreach(scan_directory($directory) as $file) {
1846           if(($file==".")||($file=="..")) continue;
1847           if( is_file($directory."/".$file) &&
1848               is_writable($directory."/".$file)) {
1849             // delete file
1850             if(!unlink($directory."/".$file)) {
1851               print_red("File ".$directory."/".$file." could not be deleted.");
1852               // This should never be reached
1853             }
1854           } elseif(is_dir($directory."/".$file) &&
1855               is_writable($directory."/".$file)) {
1856             // Just recursively delete it
1857             rmdirRecursive($directory."/".$file);
1858           }
1859         }
1860         // We should now create a fresh revision file
1861         clean_smarty_compile_dir($directory);
1862       } else {
1863         // Revision matches, nothing to do
1864       }
1865     }
1866   } else {
1867     // Smarty compile dir is not accessible
1868     // (Smarty will warn about this)
1869   }
1872 function create_revision($revision_file, $revision)
1874   $result= false;
1876   if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1877     if($fh= fopen($revision_file, "w")) {
1878       if(fwrite($fh, $revision)) {
1879         $result= true;
1880       }
1881     }
1882     fclose($fh);
1883   } else {
1884     print_red("Can not write to revision file");
1885   }
1887   return $result;
1890 function compare_revision($revision_file, $revision)
1892   // false means revision differs
1893   $result= false;
1895   if(file_exists($revision_file) && is_readable($revision_file)) {
1896     // Open file
1897     if($fh= fopen($revision_file, "r")) {
1898       // Compare File contents with current revision
1899       if($revision == fread($fh, filesize($revision_file))) {
1900         $result= true;
1901       }
1902     } else {
1903       print_red("Can not open revision file");
1904     }
1905     // Close file
1906     fclose($fh);
1907   }
1909   return $result;
1912 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
1914   $str = ""; // Our return value will be saved in this var
1916   $color  = dechex($percentage+150);
1917   $color2 = dechex(150 - $percentage);
1918   $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
1920   $progress = (int)(($percentage /100)*$width);
1922   /* Abort printing out percentage, if divs are to small */
1925   /* If theres a better solution for this, use it... */
1926   $str = "
1927     <div style=\" width:".($width)."px; 
1928     height:".($height)."px;
1929   background-color:#000000;
1930 padding:1px;\">
1932           <div style=\" width:".($width)."px;
1933         background-color:#$bgcolor;
1934 height:".($height)."px;\">
1936          <div style=\" width:".$progress."px;
1937 height:".$height."px;
1938        background-color:#".$color2.$color2.$color."; \">";
1941        if(($height >10)&&($showvalue)){
1942          $str.=                 "<font style=\"font-size:".($height-2)."px;color:#FF0000;align:middle;padding-left:".((int)(($width*0.4)))."px;\">
1943            <b>".$percentage."%</b>
1944            </font>";
1945        }
1947        $str.= "</div></div></div>";
1949        return($str);
1953 function array_key_ics($ikey, $items)
1955   /* Gather keys, make them lowercase */
1956   $tmp= array();
1957   foreach ($items as $key => $value){
1958     $tmp[strtolower($key)]= $key;
1959   }
1961   if (isset($tmp[strtolower($ikey)])){
1962     return($tmp[strtolower($ikey)]);
1963   }
1965   return ("");
1969 function search_config($arr, $name, $return)
1971   if (is_array($arr)){
1972     foreach ($arr as $a){
1973       if (isset($a['CLASS']) &&
1974           strtolower($a['CLASS']) == strtolower($name)){
1976         if (isset($a[$return])){
1977           return ($a[$return]);
1978         } else {
1979           return ("");
1980         }
1981       } else {
1982         $res= search_config ($a, $name, $return);
1983         if ($res != ""){
1984           return $res;
1985         }
1986       }
1987     }
1988   }
1989   return ("");
1993 function array_differs($src, $dst)
1995   /* If the count is differing, the arrays differ */
1996   if (count ($src) != count ($dst)){
1997     return (TRUE);
1998   }
2000   /* So the count is the same - lets check the contents */
2001   $differs= FALSE;
2002   foreach($src as $value){
2003     if (!in_array($value, $dst)){
2004       $differs= TRUE;
2005     }
2006   }
2008   return ($differs);
2012 function saveFilter($a_filter, $values)
2014   if (isset($_POST['regexit'])){
2015     $a_filter["regex"]= $_POST['regexit'];
2017     foreach($values as $type){
2018       if (isset($_POST[$type])) {
2019         $a_filter[$type]= "checked";
2020       } else {
2021         $a_filter[$type]= "";
2022       }
2023     }
2024   }
2026   /* React on alphabet links if needed */
2027   if (isset($_GET['search'])){
2028     $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2029     if ($s == "**"){
2030       $s= "*";
2031     }
2032     $a_filter['regex']= $s;
2033   }
2035   return ($a_filter);
2039 /* Escape all preg_* relevant characters */
2040 function normalizePreg($input)
2042   return (addcslashes($input, '[]()|/.*+-'));
2046 /* Escape all LDAP filter relevant characters */
2047 function normalizeLdap($input)
2049   return (addcslashes($input, '()|'));
2053 /* Resturns the difference between to microtime() results in float  */
2054 function get_MicroTimeDiff($start , $stop)
2056   $a = split("\ ",$start);
2057   $b = split("\ ",$stop);
2059   $secs = $b[1] - $a[1];
2060   $msecs= $b[0] - $a[0]; 
2062   $ret = (float) ($secs+ $msecs);
2063   return($ret);
2067 /* Check if the given department name is valid */
2068 function is_department_name_reserved($name,$base)
2070   $reservedName = array("systems","apps","incomming","internal","accounts","fax","addressbook",
2071                           preg_replace("/ou=(.*),/","\\1",get_people_ou()),
2072                           preg_replace("/ou=(.*),/","\\1",get_groups_ou()));
2073   $follwedNames['/ou=fai,ou=configs,ou=systems,/'] = array("fai","hooks","templates","scripts","disk","packages","variables","profiles");
2075   /* Check if name is one of the reserved names */
2076   if(in_array_ics($name,$reservedName)) {
2077     return(true);
2078   }
2080   /* Check all follow combinations if name is in array && parent base == array_key, return false*/
2081   foreach($follwedNames as $key => $names){
2082     if((in_array_ics($name,$names)) && (preg_match($key,$base))){
2083       return(true);
2084     }
2085   }
2086   return(false);
2090 function get_base_dir()
2092   global $BASE_DIR;
2094   return $BASE_DIR;
2098 function obj_is_readable($dn, $object, $attribute)
2100   global $ui;
2102   return preg_match('/r/', $ui->get_permissions($dn, $object, $attribute));
2106 function obj_is_writable($dn, $object, $attribute)
2108   global $ui;
2110   return preg_match('/w/', $ui->get_permissions($dn, $object, $attribute));
2114 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2116   /* Initialize variables */
2117   $ret  = array("count" => 0);  // Set count to 0
2118   $next = true;                 // if false, then skip next loops and return
2119   $cnt  = 0;                    // Current number of loops
2120   $max  = 100;                  // Just for security, prevent looops
2121   $ldap = NULL;                 // To check if created result a valid
2122   $keep = "";                   // save last failed parse string
2124   /* Check each parsed dn in ldap ? */
2125   if($config!=NULL && $verify_in_ldap){
2126     $ldap = $config->get_ldap_link();
2127   }
2129   /* Lets start */
2130   $called = false;
2131   while(preg_match("/,/",$dn) && $next &&  $cnt < $max){
2133     $cnt ++;
2134     if(!preg_match("/,/",$dn)){
2135       $next = false;
2136     }
2137     $object = preg_replace("/[,].*$/","",$dn);
2138     $dn     = preg_replace("/^[^,]+,/","",$dn);
2140     $called = true;
2142     /* Check if current dn is valid */
2143     if($ldap!=NULL){
2144       $ldap->cd($dn);
2145       $ldap->cat($dn,array("dn"));
2146       if($ldap->count()){
2147         $ret[]  = $keep.$object;
2148         $keep   = "";
2149       }else{
2150         $keep  .= $object.",";
2151       }
2152     }else{
2153       $ret[]  = $keep.$object;
2154       $keep   = "";
2155     }
2156   }
2158   /* No dn was posted */
2159   if($cnt == 0 && !empty($dn)){
2160     $ret[] = $dn;
2161   }
2163   /* Append the rest */
2164   $test = $keep.$dn;
2165   if($called && !empty($test)){
2166     $ret[] = $keep.$dn;
2167   }
2168   $ret['count'] = count($ret) - 1;
2170   return($ret);
2173 function is_php4()
2175   if (isset($_SESSION['PHP4COMPATIBLE'])){
2176     return true;
2177   }
2178   return (preg_match('/^4/', phpversion()));
2181 /* Add "str_split" if this function is missing.
2182  * This function is only available in PHP5
2183  */
2184   if(!function_exists("str_split")){
2185     function str_split($str,$length =1)
2186     {
2187       if($length < 1 ) $length =1;
2189       $ret = array();
2190       for($i = 0 ; $i < strlen($str); $i = $i +$length){
2191         $ret[] = substr($str,$i ,$length);
2192       }
2193       return($ret);
2194     }
2195   }
2198 function get_base_from_hook($dn, $attrib)
2200   global $config;
2202   if (isset($config->current['BASE_HOOK'])){
2203     
2204     /* Call hook script - if present */
2205     $command= $config->current['BASE_HOOK'];
2207     if ($command != ""){
2208       $command.= " '$dn' $attrib";
2209       if (check_command($command)){
2210         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2211         exec($command, $output);
2212         if (preg_match("/^[0-9]+$/", $output[0])){
2213           return ($output[0]);
2214         } else {
2215           print_red(_("Warning - base_hook is not available. Using default base."));
2216           return ($config->current['UIDBASE']);
2217         }
2218       } else {
2219         print_red(_("Warning - base_hook is not available. Using default base."));
2220         return ($config->current['UIDBASE']);
2221       }
2223     } else {
2225       print_red(_("Warning - no base_hook defined. Using default base."));
2226       return ($config->current['UIDBASE']);
2228     }
2229   }
2232 /* Schema validation functions */
2234 function check_schema_version($class, $version)
2236   return preg_match("/\(v$version\)/", $class['DESC']);
2239 function check_schema($cfg,$rfc2307bis = FALSE)
2241   $messages= array();
2243   /* Get objectclasses */
2244   $ldap = new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE,$cfg['tls']);
2245   $objectclasses = $ldap->get_objectclasses();
2246   if(count($objectclasses) == 0){
2247     print_red(_("Can't get schema information from server. No schema check possible!"));
2248   }
2250   /* This is the default block used for each entry.
2251    *  to avoid unset indexes.
2252    */
2253   $def_check = array("REQUIRED_VERSION" => "0",
2254       "SCHEMA_FILES"     => array(),
2255       "CLASSES_REQUIRED" => array(),
2256       "STATUS"           => FALSE,
2257       "IS_MUST_HAVE"     => FALSE,
2258       "MSG"              => "",
2259       "INFO"             => "");#_("There is currently no information specified for this schema extension."));
2261   /* The gosa base schema */
2262   $checks['gosaObject'] = $def_check;
2263   $checks['gosaObject']['REQUIRED_VERSION'] = "2.4";
2264   $checks['gosaObject']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2265   $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2266   $checks['gosaObject']['IS_MUST_HAVE']     = TRUE;
2268   /* GOsa Account class */
2269   $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.4";
2270   $checks["gosaAccount"]["SCHEMA_FILES"]    = array("gosa+samba3.schema","gosa.schema");
2271   $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2272   $checks["gosaAccount"]["IS_MUST_HAVE"]    = TRUE;
2273   $checks["gosaAccount"]["INFO"]            = _("Used to store account specific informations.");
2275   /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2276   $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.4";
2277   $checks["gosaLockEntry"]["SCHEMA_FILES"]     = array("gosa+samba3.schema","gosa.schema");
2278   $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2279   $checks["gosaLockEntry"]["IS_MUST_HAVE"]     = TRUE;
2280   $checks["gosaLockEntry"]["INFO"]             = _("Used to lock currently edited entries to avoid multiple changes at the same time.");
2282   /* Some other checks */
2283   foreach(array(
2284         "gosaCacheEntry"        => array("version" => "2.4"),
2285         "gosaDepartment"        => array("version" => "2.4"),
2286         "goFaxAccount"          => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2287         "goFaxSBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2288         "goFaxRBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2289         "gosaUserTemplate"      => array("version" => "2.4", "class" => "posixAccount","file" => "nis.schema"),
2290         "gosaMailAccount"       => array("version" => "2.4", "class" => "mailAccount","file" => "gosa+samba3.schema"),
2291         "gosaProxyAccount"      => array("version" => "2.4", "class" => "proxyAccount","file" => "gosa+samba3.schema"),
2292         "gosaApplication"       => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2293         "gosaApplicationGroup"  => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2294         "GOhard"                => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2295         "gotoTerminal"          => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2296         "goServer"              => array("version" => "2.4","class" => "server","file" => "goserver.schema"),
2297         "goTerminalServer"      => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2298         "goShareServer"         => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2299         "goNtpServer"           => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2300         "goSyslogServer"        => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2301         "goLdapServer"          => array("version" => "2.4"),
2302         "goCupsServer"          => array("version" => "2.4", "class" => array("posixAccount", "terminals"),),
2303         "goImapServer"          => array("version" => "2.4", "class" => array("mailAccount", "mailgroup"),"file" => "gosa+samba3.        schema"),
2304         "goKrbServer"           => array("version" => "2.4"),
2305         "goFaxServer"           => array("version" => "2.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2306         ) as $name => $values){
2308           $checks[$name] = $def_check;
2309           if(isset($values['version'])){
2310             $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2311           }
2312           if(isset($values['file'])){
2313             $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2314           }
2315           $checks[$name]["CLASSES_REQUIRED"] = array($name);
2316         }
2317   foreach($checks as $name => $value){
2318     foreach($value['CLASSES_REQUIRED'] as $class){
2320       if(!isset($objectclasses[$name])){
2321         $checks[$name]['STATUS'] = FALSE;
2322         if($value['IS_MUST_HAVE']){
2323           $checks[$name]['MSG']    = sprintf(_("The required objectClass '%s' is not present in your schema setup"),$class);
2324         }else{
2325           $checks[$name]['MSG']    = sprintf(_("The optional objectClass '%s' is not present in your schema setup"),$class);
2326         }
2327       }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2328         $checks[$name]['STATUS'] = FALSE;
2330         if($value['IS_MUST_HAVE']){
2331           $checks[$name]['MSG'] = sprintf(_("The required objectclass '%s' does not have version %s"), $class,                           $value['REQUIRED_VERSION']);
2332         }else{
2333           $checks[$name]['MSG'] = sprintf(_("The optional objectclass '%s' does not have version %s"), $class,                           $value['REQUIRED_VERSION']);
2334         }
2335       }else{
2336         $checks[$name]['STATUS'] = TRUE;
2337         $checks[$name]['MSG'] = sprintf(_("Class(es) available"));
2338       }
2339     }
2340   }
2342   $tmp = $objectclasses;
2344   /* The gosa base schema */
2345   $checks['posixGroup'] = $def_check;
2346   $checks['posixGroup']['REQUIRED_VERSION'] = "2.4";
2347   $checks['posixGroup']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2348   $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2349   $checks['posixGroup']['STATUS']           = TRUE;
2350   $checks['posixGroup']['IS_MUST_HAVE']     = TRUE;
2351   $checks['posixGroup']['MSG']              = "";
2352   $checks['posixGroup']['INFO']             = "";
2354   /* Depending on selected rfc2307bis mode, we need different schema configurations */
2355   if(isset($tmp['posixGroup'])){
2357     if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2358       $checks['posixGroup']['STATUS']           = FALSE;
2359       $checks['posixGroup']['MSG']              = _("You have enabled the rfc2307bis option on the 'ldap setup' step, but your schema    configuration do not support this option.");
2360       $checks['posixGroup']['INFO']             = _("In order to use rfc2307bis conform groups the objectClass 'posixGroup' must be      AUXILIARY");
2361     }
2362     if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2363       $checks['posixGroup']['STATUS']           = FALSE;
2364       $checks['posixGroup']['MSG']              = _("You have disabled the rfc2307bis option on the 'ldap setup' step, but your schema   configuration do not support this option.");
2365       $checks['posixGroup']['INFO']             = _("The objectClass 'posixGroup' must be STRUCTURAL");
2366     }
2367   }
2369   return($checks);
2373 function prepare4mailbody($string)
2375   $string = html_entity_decode($string);
2377   $from = array(
2378                 "/%/",
2379                 "/ /",
2380                 "/\n/",
2381                 "/\r/",
2382                 "/!/",
2383                 "/#/",
2384                 "/\*/",
2385                 "/\//",
2386                 "/</",
2387                 "/>/",
2388                 "/\?/",
2389                 "/\"/");
2391   $to = array(
2392                 "%25",
2393                 "%20",
2394                 "%0A",
2395                 "%0D",
2396                 "%21",
2397                 "%23",
2398                 "%2A",
2399                 "%2F",
2400                 "%3C",
2401                 "%3E",
2402                 "%3F",
2403                 "%22");
2405   $string = preg_replace($from,$to,$string);
2407   return($string);
2413 function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FALSE)
2415   $tmp = array(
2416         "de_DE" => "German",
2417         "fr_FR" => "French",
2418         "it_IT" => "Italian",
2419         "es_ES" => "Spanish",
2420         "en_US" => "English",
2421         "nl_NL" => "Dutch",
2422         "pl_PL" => "Polish",
2423         "sv_SE" => "Swedish",
2424         "zh_CN" => "Chinese",
2425         "ru_RU" => "Russian");
2427   $ret = array();
2428   if($languages_in_own_language){
2429     $old_lang = setlocale(LC_ALL, 0);
2430     foreach($tmp as $key => $name){
2431       $lang = $key.".UTF-8";
2432       setlocale(LC_ALL, $lang);
2433       if($strip_region_tag){
2434         $ret[preg_replace("/^([^_]*).*$/","\\1",$key)] = _($name)." (".$name.")";
2435       }else{
2436         $ret[$key] = _($name)." &nbsp;(".$name.")";
2437       }
2438     }
2439     setlocale(LC_ALL, $old_lang);
2440   }else{
2441     foreach($tmp as $key => $name){
2442       if($strip_region_tag){
2443         $ret[preg_replace("/^([^_]*).*/","\\1",$key)] = _($name);
2444       }else{
2445         $ret[$key] = _($name);
2446       }
2447     }
2448   }
2449   return($ret);
2453 /* Returns contents of the given POST variable and check magic quotes settings */
2454 function get_post($name)
2456   if(!isset($_POST[$name])){
2457     trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2458     return(FALSE);
2459   }
2460   if(get_magic_quotes_gpc()){
2461     return(stripcslashes($_POST[$name]));
2462   }else{
2463     return($_POST[$name]);
2464   }
2468 /* Check if $ip1 and $ip2 represents a valid IP range 
2469  *  returns TRUE in case of a valid range, FALSE in case of an error. 
2470  */
2471 function is_ip_range($ip1,$ip2)
2473   if(!is_ip($ip1) || !is_ip($ip2)){
2474     return(FALSE);
2475   }else{
2476     $ar1 = split("\.",$ip1);
2477     $var1 = $ar1[0] * (16777216) + $ar1[1] * (65536) + $ar1[2] * (256) + $ar1[3];
2479     $ar2 = split("\.",$ip2);
2480     $var2 = $ar2[0] * (16777216) + $ar2[1] * (65536) + $ar2[2] * (256) + $ar2[3];
2481     return($var1 < $var2);
2482   }
2486 /* Check if the specified IP address $address is inside the given network */
2487 function is_in_network($network, $netmask, $address)
2489   $nw= split('\.', $network);
2490   $nm= split('\.', $netmask);
2491   $ad= split('\.', $address);
2493   /* Generate inverted netmask */
2494   for ($i= 0; $i<4; $i++){
2495     $ni[$i]= 255-$nm[$i];
2496     $la[$i]= $nw[$i] | $ni[$i];
2497   }
2499   /* Transform to integer */
2500   $first= $nw[0] * (16777216) + $nw[1] * (65536) + $nw[2] * (256) + $nw[3];
2501   $curr=  $ad[0] * (16777216) + $ad[1] * (65536) + $ad[2] * (256) + $ad[3];
2502   $last=  $la[0] * (16777216) + $la[1] * (65536) + $la[2] * (256) + $la[3];
2504   return ($first < $curr&& $last > $curr);
2508 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2509 ?>