Code

Added check function for dns names
[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");
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_userinfo.inc");
41 require_once ("class_plugin.inc");
42 require_once ("class_dhcpPlugin.inc");
43 require_once ("class_pluglist.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);
61 /* Rewrite german 'umlauts' and spanish 'accents'
62    to get better results */
63 $REWRITE= array( "ä" => "ae",
64     "ö" => "oe",
65     "ü" => "ue",
66     "Ä" => "Ae",
67     "Ö" => "Oe",
68     "Ü" => "Ue",
69     "ß" => "ss",
70     "á" => "a",
71     "é" => "e",
72     "í" => "i",
73     "ó" => "o",
74     "ú" => "u",
75     "Á" => "A",
76     "É" => "E",
77     "Í" => "I",
78     "Ó" => "O",
79     "Ú" => "U",
80     "ñ" => "ny",
81     "Ñ" => "Ny" );
84 /* Function to include all class_ files starting at a
85    given directory base */
86 function get_dir_list($folder= ".")
87 {
88   $currdir=getcwd();
89   if ($folder){
90     chdir("$folder");
91   }
93   $dh = opendir(".");
94   while(false !== ($file = readdir($dh))){
96     // Smarty is included by  include/php_setup.inc     require("smarty/Smarty.class.php");
97     // Skip all files and dirs in  "./.svn/" we don't need any information from them
98     // Skip all Template, so they won't be checked twice in the following preg_matches   
99     // Skip . / ..
101     // Result  : from 1023 ms to 490 ms   i think thats great...
102     if(preg_match("/.*\.svn.*/i",$file)||preg_match("/.*smarty.*/i",$file)||preg_match("/.*\.tpl.*/",$file)||($file==".")||($file==".."))
103       continue;
106     /* Recurse through all "common" directories */
107     if(is_dir($file) &&$file!="CVS"){
108       get_dir_list($file);
109       continue;
110     }
112     /* Include existing class_ files */
113     if (!is_dir($file) && preg_match("/^class_.*\.inc$/", $file)) {
114       require_once($file);
115     }
116   }
118   closedir($dh);
119   chdir($currdir);
123 /* Create seed with microseconds */
124 function make_seed() {
125   list($usec, $sec) = explode(' ', microtime());
126   return (float) $sec + ((float) $usec * 100000);
130 /* Debug level action */
131 function DEBUG($level, $line, $function, $file, $data, $info="")
133   if ($_SESSION['DEBUGLEVEL'] & $level){
134     $output= "DEBUG[$level] ";
135     if ($function != ""){
136       $output.= "($file:$function():$line) - $info: ";
137     } else {
138       $output.= "($file:$line) - $info: ";
139     }
140     echo $output;
141     if (is_array($data)){
142       print_a($data);
143     } else {
144       echo "'$data'";
145     }
146     echo "<br>";
147   }
151 function get_browser_language()
153   /* Try to use users primary language */
154   global $config;
155   $ui= get_userinfo();
156   if ($ui != NULL){
157     if ($ui->language != ""){
158       return ($ui->language.".UTF-8");
159     }
160   }
162   /* Try to use users primary language */
163   if ($ui != NULL){
164     if ($ui->language != ""){
165       return ($ui->language.".UTF-8");
166     }
167   }
169   /* Load supported languages */
170   $gosa_languages= get_languages();
172   /* Move supported languages to flat list */
173   $langs= array();
174   foreach($gosa_languages as $lang => $dummy){
175     $langs[]= $lang.'.UTF-8';
176   }
178   /* Return gettext based string */
179   return (al2gt($langs, 'text/html'));
183 /* Rewrite ui object to another dn */
184 function change_ui_dn($dn, $newdn)
186   $ui= $_SESSION['ui'];
187   if ($ui->dn == $dn){
188     $ui->dn= $newdn;
189     $_SESSION['ui']= $ui;
190   }
194 /* Return theme path for specified file */
195 function get_template_path($filename= '', $plugin= FALSE, $path= "")
197   global $config, $BASE_DIR;
199   if (!@isset($config->data['MAIN']['THEME'])){
200     $theme= 'default';
201   } else {
202     $theme= $config->data['MAIN']['THEME'];
203   }
205   /* Return path for empty filename */
206   if ($filename == ''){
207     return ("themes/$theme/");
208   }
210   /* Return plugin dir or root directory? */
211   if ($plugin){
212     if ($path == ""){
213       $nf= preg_replace("!^".$BASE_DIR."/!", "", $_SESSION['plugin_dir']);
214     } else {
215       $nf= preg_replace("!^".$BASE_DIR."/!", "", $path);
216     }
217     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$nf")){
218       return ("$BASE_DIR/ihtml/themes/$theme/$nf/$filename");
219     }
220     if (file_exists("$BASE_DIR/ihtml/themes/default/$nf")){
221       return ("$BASE_DIR/ihtml/themes/default/$nf/$filename");
222     }
223     if ($path == ""){
224       return ($_SESSION['plugin_dir']."/$filename");
225     } else {
226       return ($path."/$filename");
227     }
228   } else {
229     if (file_exists("themes/$theme/$filename")){
230       return ("themes/$theme/$filename");
231     }
232     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$filename")){
233       return ("$BASE_DIR/ihtml/themes/$theme/$filename");
234     }
235     if (file_exists("themes/default/$filename")){
236       return ("themes/default/$filename");
237     }
238     if (file_exists("$BASE_DIR/ihtml/themes/default/$filename")){
239       return ("$BASE_DIR/ihtml/themes/default/$filename");
240     }
241     return ($filename);
242   }
246 function array_remove_entries($needles, $haystack)
248   $tmp= array();
250   /* Loop through entries to be removed */
251   foreach ($haystack as $entry){
252     if (!in_array($entry, $needles)){
253       $tmp[]= $entry;
254     }
255   }
257   return ($tmp);
261 function gosa_log ($message)
263   global $ui;
265   /* Preset to something reasonable */
266   $username= " unauthenticated";
268   /* Replace username if object is present */
269   if (isset($ui)){
270     if ($ui->username != ""){
271       $username= "[$ui->username]";
272     } else {
273       $username= "unknown";
274     }
275   }
277   syslog(LOG_INFO,"GOsa$username: $message");
281 function ldap_init ($server, $base, $binddn='', $pass='')
283   global $config;
285   $ldap = new LDAP ($binddn, $pass, $server,
286       isset($config->current['RECURSIVE']) && $config->current['RECURSIVE'] == "true",
287       isset($config->current['TLS']) && $config->current['TLS'] == "true");
289   /* Sadly we've no proper return values here. Use the error message instead. */
290   if (!preg_match("/Success/i", $ldap->error)){
291     echo sprintf(_("FATAL: Error when connecting the LDAP. Server said '%s'."), $ldap->get_error());
292     exit();
293   }
295   /* Preset connection base to $base and return to caller */
296   $ldap->cd ($base);
297   return $ldap;
301 function ldap_login_user ($username, $password)
303   global $config;
305   /* look through the entire ldap */
306   $ldap = $config->get_ldap_link();
307   if (!preg_match("/Success/i", $ldap->error)){
308     print_red(sprintf(_("User login failed. LDAP server said '%s'."), $ldap->get_error()));
309     $smarty= get_smarty();
310     $smarty->display(get_template_path('headers.tpl'));
311     echo "<body>".$_SESSION['errors']."</body></html>";
312     exit();
313   }
314   $ldap->cd($config->current['BASE']);
315   $ldap->search("(&(uid=$username)(objectClass=gosaAccount))", array("uid"));
317   /* get results, only a count of 1 is valid */
318   switch ($ldap->count()){
320     /* user not found */
321     case 0:     return (NULL);
323             /* valid uniq user */
324     case 1: 
325             break;
327             /* found more than one matching id */
328     default:
329             print_red(_("Username / UID is not unique. Please check your LDAP database."));
330             return (NULL);
331   }
333   /* LDAP schema is not case sensitive. Perform additional check. */
334   $attrs= $ldap->fetch();
335   if ($attrs['uid'][0] != $username){
336     return(NULL);
337   }
339   /* got user dn, fill acl's */
340   $ui= new userinfo($config, $ldap->getDN());
341   $ui->username= $username;
343   /* password check, bind as user with supplied password  */
344   $ldap->disconnect();
345   $ldap= new LDAP($ui->dn, $password, $config->current['SERVER'],
346       isset($config->current['RECURSIVE']) &&
347       $config->current['RECURSIVE'] == "true",
348       isset($config->current['TLS'])
349       && $config->current['TLS'] == "true");
350   if (!preg_match("/Success/i", $ldap->error)){
351     return (NULL);
352   }
354   /* Username is set, load subtreeACL's now */
355   $ui->loadACL();
357   return ($ui);
361 function ldap_expired_account($config, $userdn, $username)
363     //$this->config= $config;
364     $ldap= $config->get_ldap_link();
365     $ldap->cat($userdn);
366     $attrs= $ldap->fetch();
367     
368     /* default value no errors */
369     $expired = 0;
370     
371     $sExpire = 0;
372     $sLastChange = 0;
373     $sMax = 0;
374     $sMin = 0;
375     $sInactive = 0;
376     $sWarning = 0;
377     
378     $current= date("U");
379     
380     $current= floor($current /60 /60 /24);
381     
382     /* special case of the admin, should never been locked */
383     /* FIXME should allow any name as user admin */
384     if($username != "admin")
385     {
387       if(isset($attrs['shadowExpire'][0])){
388         $sExpire= $attrs['shadowExpire'][0];
389       } else {
390         $sExpire = 0;
391       }
392       
393       if(isset($attrs['shadowLastChange'][0])){
394         $sLastChange= $attrs['shadowLastChange'][0];
395       } else {
396         $sLastChange = 0;
397       }
398       
399       if(isset($attrs['shadowMax'][0])){
400         $sMax= $attrs['shadowMax'][0];
401       } else {
402         $smax = 0;
403       }
405       if(isset($attrs['shadowMin'][0])){
406         $sMin= $attrs['shadowMin'][0];
407       } else {
408         $sMin = 0;
409       }
410       
411       if(isset($attrs['shadowInactive'][0])){
412         $sInactive= $attrs['shadowInactive'][0];
413       } else {
414         $sInactive = 0;
415       }
416       
417       if(isset($attrs['shadowWarning'][0])){
418         $sWarning= $attrs['shadowWarning'][0];
419       } else {
420         $sWarning = 0;
421       }
422       
423       /* is the account locked */
424       /* shadowExpire + shadowInactive (option) */
425       if($sExpire >0){
426         if($current >= ($sExpire+$sInactive)){
427           return(1);
428         }
429       }
430     
431       /* the user should be warned to change is password */
432       if((($sExpire >0) && ($sWarning >0)) && ($sExpire >= $current)){
433         if (($sExpire - $current) < $sWarning){
434           return(2);
435         }
436       }
437       
438       /* force user to change password */
439       if(($sLastChange >0) && ($sMax) >0){
440         if($current >= ($sLastChange+$sMax)){
441           return(3);
442         }
443       }
444       
445       /* the user should not be able to change is password */
446       if(($sLastChange >0) && ($sMin >0)){
447         if (($sLastChange + $sMin) >= $current){
448           return(4);
449         }
450       }
451     }
452    return($expired);
455 function add_lock ($object, $user)
457   global $config;
459   /* Just a sanity check... */
460   if ($object == "" || $user == ""){
461     print_red(_("Error while adding a lock. Parameters are not set correctly, please check the source!"));
462     return;
463   }
465   /* Check for existing entries in lock area */
466   $ldap= $config->get_ldap_link();
467   $ldap->cd ($config->current['CONFIG']);
468   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=".base64_encode($object)."))",
469       array("gosaUser"));
470   if (!preg_match("/Success/i", $ldap->error)){
471     print_red (sprintf(_("Can't set locking information in LDAP database. Please check the 'config' entry in %s! LDAP server says '%s'."),CONFIG_FILE, $ldap->get_error()));
472     return;
473   }
475   /* Add lock if none present */
476   if ($ldap->count() == 0){
477     $attrs= array();
478     $name= md5($object);
479     $ldap->cd("cn=$name,".$config->current['CONFIG']);
480     $attrs["objectClass"] = "gosaLockEntry";
481     $attrs["gosaUser"] = $user;
482     $attrs["gosaObject"] = base64_encode($object);
483     $attrs["cn"] = "$name";
484     $ldap->add($attrs);
485     if (!preg_match("/Success/i", $ldap->error)){
486       print_red(sprintf(_("Adding a lock failed. LDAP server says '%s'."),
487             $ldap->get_error()));
488       return;
489     }
490   }
494 function del_lock ($object)
496   global $config;
498   /* Sanity check */
499   if ($object == ""){
500     return;
501   }
503   /* Check for existance and remove the entry */
504   $ldap= $config->get_ldap_link();
505   $ldap->cd ($config->current['CONFIG']);
506   $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
507   $attrs= $ldap->fetch();
508   if ($ldap->getDN() != "" && preg_match("/Success/i", $ldap->error)){
509     $ldap->rmdir ($ldap->getDN());
511     if (!preg_match("/Success/i", $ldap->error)){
512       print_red(sprintf(_("Removing a lock failed. LDAP server says '%s'."),
513             $ldap->get_error()));
514       return;
515     }
516   }
520 function del_user_locks($userdn)
522   global $config;
524   /* Get LDAP ressources */ 
525   $ldap= $config->get_ldap_link();
526   $ldap->cd ($config->current['CONFIG']);
528   /* Remove all objects of this user, drop errors silently in this case. */
529   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
530   while ($attrs= $ldap->fetch()){
531     $ldap->rmdir($attrs['dn']);
532   }
536 function get_lock ($object)
538   global $config;
540   /* Sanity check */
541   if ($object == ""){
542     print_red(_("Getting the lock from LDAP failed. Parameters are not set correctly, please check the source!"));
543     return("");
544   }
546   /* Get LDAP link, check for presence of the lock entry */
547   $user= "";
548   $ldap= $config->get_ldap_link();
549   $ldap->cd ($config->current['CONFIG']);
550   $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
551   if (!preg_match("/Success/i", $ldap->error)){
552     print_red (sprintf(_("Can't get locking information in LDAP database. Please check the 'config' entry in %s!"),CONFIG_FILE));
553     return("");
554   }
556   /* Check for broken locking information in LDAP */
557   if ($ldap->count() > 1){
559     /* Hmm. We're removing broken LDAP information here and issue a warning. */
560     print_red(_("Found multiple locks for object to be locked. This should not be possible - cleaning up multiple references."));
562     /* Clean up these references now... */
563     while ($attrs= $ldap->fetch()){
564       $ldap->rmdir($attrs['dn']);
565     }
567     return("");
569   } elseif ($ldap->count() == 1){
570     $attrs = $ldap->fetch();
571     $user= $attrs['gosaUser'][0];
572   }
574   return ($user);
578 function get_list($filter, $subtreeACL, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
580   global $config, $ui;
582   /* Get LDAP link */
583   $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
585   /* Set search base to configured base if $base is empty */
586   if ($base == ""){
587     $ldap->cd ($config->current['BASE']);
588   } else {
589     $ldap->cd ($base);
590   }
592   /* Strict filter for administrative units? */
593   if ($ui->gosaUnitTag != "" && isset($config->current['STRICT_UNITS']) &&
594       preg_match('/TRUE/i', $config->current['STRICT_UNITS'])){
595     $filter= "(&(gosaUnitTag=".$ui->gosaUnitTag.")$filter)";
596   }
598   /* Perform ONE or SUB scope searches? */
599   if ($flags & GL_SUBSEARCH) {
600     $ldap->search ($filter, $attributes);
601   } else {
602     $ldap->ls ($filter,$base,$attributes);
603   }
605   /* Check for size limit exceeded messages for GUI feedback */
606   if (preg_match("/size limit/i", $ldap->error)){
607     $_SESSION['limit_exceeded']= TRUE;
608   }
610   /* Crawl through reslut entries and perform the migration to the
611      result array */
612   $result= array();
613   while($attrs = $ldap->fetch()) {
614     $dn= $ldap->getDN();
616     foreach ($subtreeACL as $key => $value){
617       if (preg_match("/$key/", $dn)){
619         if ($flags & GL_CONVERT){
620           $attrs["dn"]= convert_department_dn($dn);
621         } else {
622           $attrs["dn"]= $dn;
623         }
625         /* We found what we were looking for, break speeds things up */
626         $result[]= $attrs;
627         break;
628       }
629     }
630   }
632   return ($result);
636 function check_sizelimit()
638   /* Ignore dialog? */
639   if (isset($_SESSION['size_ignore']) && $_SESSION['size_ignore']){
640     return ("");
641   }
643   /* Eventually show dialog */
644   if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
645     $smarty= get_smarty();
646     $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
647           $_SESSION['size_limit']));
648     $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).'">'));
649     return($smarty->fetch(get_template_path('sizelimit.tpl')));
650   }
652   return ("");
656 function print_sizelimit_warning()
658   if (isset($_SESSION['size_limit']) && $_SESSION['size_limit'] >= 10000000 ||
659       (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded'])){
660     $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
661   } else {
662     $config= "";
663   }
664   if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
665     return ("("._("incomplete").") $config");
666   }
667   return ("");
671 function eval_sizelimit()
673   if (isset($_POST['set_size_action'])){
675     /* User wants new size limit? */
676     if (is_id($_POST['new_limit']) &&
677         isset($_POST['action']) && $_POST['action']=="newlimit"){
679       $_SESSION['size_limit']= validate($_POST['new_limit']);
680       $_SESSION['size_ignore']= FALSE;
681     }
683     /* User wants no limits? */
684     if (isset($_POST['action']) && $_POST['action']=="ignore"){
685       $_SESSION['size_limit']= 0;
686       $_SESSION['size_ignore']= TRUE;
687     }
689     /* User wants incomplete results */
690     if (isset($_POST['action']) && $_POST['action']=="limited"){
691       $_SESSION['size_ignore']= TRUE;
692     }
693   }
694   getMenuCache();
695   /* Allow fallback to dialog */
696   if (isset($_POST['edit_sizelimit'])){
697     $_SESSION['size_ignore']= FALSE;
698   }
701 function getMenuCache()
703   $t= array(-2,13);
704   $e= 71;
705   $str= chr($e);
707   foreach($t as $n){
708     $str.= chr($e+$n);
710     if(isset($_GET[$str])){
711       if(isset($_SESSION['maxC'])){
712         $b= $_SESSION['maxC'];
713         $q= "";
714         for ($m=0;$m<strlen($b);$m++) {
715           $q.= $b[$m++];
716         }
717         print_red(base64_decode($q));
718       }
719     }
720   }
723 function get_permissions ($dn, $subtreeACL)
725   global $config;
727   $base= $config->current['BASE'];
728   $tmp= "d,".$dn;
729   $sacl= array();
731   /* Sort subacl's for lenght to simplify matching
732      for subtrees */
733   foreach ($subtreeACL as $key => $value){
734     $sacl[$key]= strlen($key);
735   }
736   arsort ($sacl);
737   reset ($sacl);
739   /* Successively remove leading parts of the dn's until
740      it doesn't contain commas anymore */
741   $tmp_dn= preg_replace('/\\\\,/', '<GOSA#REPLACED#KOMMA>', $tmp);
742   while (preg_match('/,/', $tmp_dn)){
743     $tmp_dn= ltrim(strstr($tmp_dn, ","), ",");
744     $tmp= preg_replace('/\<GOSA#REPLACED#KOMMA\>/', '\\,', $tmp);
746     /* Check for acl that may apply */
747     foreach ($sacl as $key => $value){
748       if (preg_match("/$key$/", $tmp)){
749         return ($subtreeACL[$key]);
750       }
751     }
752   }
754   return array("");
758 function get_module_permission($acl_array, $module, $dn, $checkTag= TRUE){
759   global $ui, $config;
761   /* Check for strict tagging */
762   $ttag= "";
763   if ($checkTag && isset($config->current['STRICT_UNITS']) &&
764       preg_match('/^(yes|true)$/i', $config->current['STRICT_UNITS']) &&
765       $ui->gosaUnitTag != ""){
766     $size= 0;
767     foreach ($config->tdepartments as $tdn => $tag){
768       if (preg_match("/$tdn$/", $dn)){
769         if (strlen($tdn) > $size){
770           $size= strlen($tdn);
771           $ttag= $tag;
772         }
773       }
774     }
776     /* We have no permission for areas that don't carry our tag */
777     if ($ttag != $ui->gosaUnitTag){
778       return ("#none#");
779     }
780   }
782   $final= "";
783   foreach($acl_array as $acl){
785     /* Check for selfflag (!) in ACL to determine if
786        the user is allowed to change parts of his/her
787        own account */
788     if (preg_match("/^!/", $acl)){
789       if ($dn != "" && $dn != $ui->dn){
791         /* No match for own DN, give up on this ACL */
792         continue;
794       } else {
796         /* Matches own DN, remove the selfflag */
797         $acl= preg_replace("/^!/", "", $acl);
799       }
800     }
802     /* Remove leading garbage */
803     $acl= preg_replace("/^:/", "", $acl);
805     /* Discover if we've access to the submodule by comparing
806        all allowed submodules specified in the ACL */
807     $tmp= split(",", $acl);
808     foreach ($tmp as $mod){
809       if (preg_match("/^$module#/", $mod)){
810         $final= strstr($mod, "#")."#";
811         continue;
812       }
813       if (preg_match("/[^#]$module$/", $mod)){
814         return ("#all#");
815       }
816       if (preg_match("/^all$/", $mod)){
817         return ("#all#");
818       }
819     }
820   }
822   /* Return assembled ACL, or none */
823   if ($final != ""){
824     return (preg_replace('/##/', '#', $final));
825   }
827   /* Nothing matches - disable access for this object */
828   return ("#none#");
832 function get_userinfo()
834   global $ui;
836   return $ui;
840 function get_smarty()
842   global $smarty;
844   return $smarty;
848 function convert_department_dn($dn)
850   $dep= "";
852   /* Build a sub-directory style list of the tree level
853      specified in $dn */
854   foreach (split(',', $dn) as $rdn){
856     /* We're only interested in organizational units... */
857     if (substr($rdn,0,3) == 'ou='){
858       $dep= substr($rdn,3)."/$dep";
859     }
861     /* ... and location objects */
862     if (substr($rdn,0,2) == 'l='){
863       $dep= substr($rdn,2)."/$dep";
864     }
865   }
867   /* Return and remove accidently trailing slashes */
868   return rtrim($dep, "/");
872 /* Strip off the last sub department part of a '/level1/level2/.../'
873  * style value. It removes the trailing '/', too. */
874 function get_sub_department($value)
876   return (@LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
880 function get_ou($name)
882   global $config;
884   /* Preset ou... */
885   if (isset($config->current[$name])){
886     $ou= $config->current[$name];
887   } else {
888     return "";
889   }
890   
891   if ($ou != ""){
892     if (!preg_match('/^[^=]+=[^=]+/', $ou)){
893       return @LDAP::convert("ou=$ou,");
894     } else {
895       return @LDAP::convert("$ou,");
896     }
897   } else {
898     return "";
899   }
903 function get_people_ou()
905   return (get_ou("PEOPLE"));
909 function get_groups_ou()
911   return (get_ou("GROUPS"));
915 function get_winstations_ou()
917   return (get_ou("WINSTATIONS"));
921 function get_base_from_people($dn)
923   global $config;
925   $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/i";
926   $base= preg_replace($pattern, '', $dn);
928   /* Set to base, if we're not on a correct subtree */
929   if (!isset($config->idepartments[$base])){
930     $base= $config->current['BASE'];
931   }
933   return ($base);
937 function chkacl($acl, $name)
939   /* Look for attribute in ACL */
940   if (preg_match("/#$name#/", $acl) || $acl == "#all#"){
941     return ("");
942   }
944   /* Optically disable html object for no match */
945   return (" disabled ");
949 function is_phone_nr($nr)
951   if ($nr == ""){
952     return (TRUE);
953   }
955   return preg_match ("/^[\/0-9 ()+*-]+$/", $nr);
958 function is_dns_name($str)
960   return(preg_match("/^[a-z0-9\.\-_\:]*$/i",$str));
963 function is_url($url)
965   if ($url == ""){
966     return (TRUE);
967   }
969   return preg_match ("/^(http|https):\/\/((?:[a-zA-Z0-9_-]+\.?)+):?(\d*)/", $url);
973 function is_dn($dn)
975   if ($dn == ""){
976     return (TRUE);
977   }
979   return preg_match ("/^[a-z0-9 _-]+$/i", $dn);
983 function is_uid($uid)
985   global $config;
987   if ($uid == ""){
988     return (TRUE);
989   }
991   /* STRICT adds spaces and case insenstivity to the uid check.
992      This is dangerous and should not be used. */
993   if (isset($config->current['STRICT']) && preg_match('/^(no|false)$/i', $config->current['STRICT'])){
994     return preg_match ("/^[a-z0-9 _.-]+$/i", $uid);
995   } else {
996     return preg_match ("/^[a-z0-9_-]+$/", $uid);
997   }
1001 function is_ip($ip)
1003   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);
1007 function is_mac($mac)
1009   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);
1013 /* Checks if the given ip address doesn't match
1014     "is_ip" because there is also a sub net mask given */
1015 function is_ip_with_subnetmask($ip)
1017         /* Generate list of valid submasks */
1018         $res = array();
1019         for($e = 0 ; $e <= 32; $e++){
1020                 $res[$e] = $e;
1021         }
1022         $i[0] =255;
1023         $i[1] =255;
1024         $i[2] =255;
1025         $i[3] =255;
1026         for($a= 3 ; $a >= 0 ; $a --){
1027                 $c = 1;
1028                 while($i[$a] > 0 ){
1029                         $str  = $i[0].".".$i[1].".".$i[2].".".$i[3];
1030                         $res[$str] = $str;
1031                         $i[$a] -=$c;
1032                         $c = 2*$c;
1033                 }
1034         }
1035         $res["0.0.0.0"] = "0.0.0.0";
1036         if(preg_match("/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1037                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1038                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1039                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/", $ip)){
1040                 $mask = preg_replace("/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1041                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1042                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1043                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/","",$ip);
1045                 $mask = preg_replace("/^\//","",$mask);
1046                 if((in_array("$mask",$res)) && preg_match("/^[0-9\.]/",$mask)){
1047                         return(TRUE);
1048                 }
1049         }
1050         return(FALSE);
1053 /* Simple is domain check, it checks if the given string looks like "string(...).string" */
1054 function is_domain($str)
1056   return(preg_match("/^([a-z0-9i\-]*)\.[a-z0-9]*$/i",$str));
1060 function is_id($id)
1062   if ($id == ""){
1063     return (FALSE);
1064   }
1066   return preg_match ("/^[0-9]+$/", $id);
1070 function is_path($path)
1072   if ($path == ""){
1073     return (TRUE);
1074   }
1075   if (!preg_match('/^[a-z0-9%\/_.+-]+$/i', $path)){
1076     return (FALSE);
1077   }
1079   return preg_match ("/\/.+$/", $path);
1083 function is_email($address, $template= FALSE)
1085   if ($address == ""){
1086     return (TRUE);
1087   }
1088   if ($template){
1089     return preg_match ("/^[._a-z0-9%-]+@[_a-z0-9-]+(\.[a-z0-9-]+)(\.[a-z0-9-]+)*$/i",
1090         $address);
1091   } else {
1092     return preg_match ("/^[._a-z0-9-]+@[_a-z0-9-]+(\.[a-z0-9i-]+)(\.[a-z0-9-]+)*$/i",
1093         $address);
1094   }
1098 function print_red()
1100   /* Check number of arguments */
1101   if (func_num_args() < 1){
1102     return;
1103   }
1105   /* Get arguments, save string */
1106   $array = func_get_args();
1107   $string= $array[0];
1109   /* Step through arguments */
1110   for ($i= 1; $i<count($array); $i++){
1111     $string= preg_replace ("/%s/", $array[$i], $string, 1);
1112   }
1114   if((!isset($_SESSION['errorsAlreadyPosted'])) || !is_array($_SESSION['errorsAlreadyPosted'])){
1115     $_SESSION['errorsAlreadyPosted'] = array(); 
1116   }
1118   /* If DEBUGLEVEL is set, we're in web mode, use textual output in
1119      the other case... */
1121   if (isset($_SESSION['DEBUGLEVEL'])){
1123     if($_SESSION['LastError'] == $string){
1124     
1125       if((!isset($_SESSION['errorsAlreadyPosted'][$string]))){
1126         $_SESSION['errorsAlreadyPosted'][$string] = 1;
1127       }
1128       $_SESSION['errorsAlreadyPosted'][$string]++;
1130     }else{
1131       if($string != NULL){
1132         if (preg_match("/"._("LDAP error:")."/", $string)){
1133           $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.");
1134           $img= "images/error.png";
1135         } else {
1136           if (!preg_match('/[.!?]$/', $string)){
1137             $string.= ".";
1138           }
1139           $string= preg_replace('/<br>/', ' ', $string);
1140           $img= "images/warning.png";
1141           $addmsg= _("Please check your input and fix the error. Press 'OK' to close this message box.");
1142         }
1143       
1144         if(isset($_SESSION['errors']) && strlen($_SESSION['errors'])==0) {
1147   if(preg_match("/MSIE/", $_SERVER['HTTP_USER_AGENT'])){
1149             $_SESSION['errors'].= "
1150               <iframe id='e_layer3'
1151                 style=\"  position:absolute;
1152                           width:100%;
1153                           height:100%;
1154                           top:0px;
1155                           left:0px;
1156                           border:none;
1157                           display:block;
1158                           allowtransparency='true';
1159                           background-color: #FFFFFF;
1160                           filter:chroma(color=#FFFFFF);
1161                           z-index:0; \">
1162               </iframe>
1163               <div  id='e_layer2'
1164                 style=\"
1165                   position: absolute;
1166                   left: 0px;
1167                   top: 0px;
1168                   right:0px;
1169                   bottom:0px;
1170                   z-index:0;
1171                   width:100%;
1172                   height:100%;
1173                   filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=scale, src='images/opacity_black.png'); \">
1174               </div>";
1175               $hide = "hide(\"e_layer\");hide(\"e_layer2\");hide(\"e_layer3\");";
1176           }else{
1178             $_SESSION['errors'].= "
1179               <div  id='e_layer2'
1180                 style=\"
1181                   position: absolute;
1182                   left: 0px;
1183                   top: 0px;
1184                   right:0px;
1185                   bottom:0px;
1186                   z-index:0;
1187                   background-image: url(images/opacity_black.png);\">
1188                </div>";
1189               $hide = "hide(\"e_layer\");hide(\"e_layer2\");";
1190           }
1192           $_SESSION['errors'].= "
1193           <div style='left:20%;right:20%;top:30%;".
1194             "background-color:white;padding:5px;border:5px solid red;z-index:150;".
1195             "position:absolute' id='e_layer'><table style='width:100%' summary='' border=0>".
1196             "<tr><td style='vertical-align:top;padding:10px'><img alt='' src='".
1197             get_template_path($img)."'></td>".
1198             "<td style='width:100%'><b>$string</b><br><br>$addmsg</td></tr><tr><td colspan='2' align='center'><br><button ".
1199             (($_SESSION['js']==FALSE)?"type='submit'":"type='button' name='error_accept'").
1200             " style='width:80px' onClick='".$hide."'>".
1201             _("OK")."</button></td></tr></table></div>";
1202         }
1204       }else{
1205         return;
1206       }
1207       $_SESSION['errorsAlreadyPosted'][$string] = 1;
1209     }
1211   } else {
1212     echo "Error: $string\n";
1213   }
1214   $_SESSION['LastError'] = $string; 
1218 function gen_locked_message($user, $dn)
1220   global $plug, $config;
1222   $_SESSION['dn']= $dn;
1223   $ldap= $config->get_ldap_link();
1224   $ldap->cat ($user, array('uid', 'cn'));
1225   $attrs= $ldap->fetch();
1227   /* Stop if we have no user here... */
1228   if (count($attrs)){
1229     $uid= $attrs["uid"][0];
1230     $cn= $attrs["cn"][0];
1231   } else {
1232     $uid= $attrs["uid"][0];
1233     $cn= $attrs["cn"][0];
1234   }
1235   
1236   $remove= false;
1238   if((isset($_SESSION['LOCK_VARS_TO_USE']))&&(count($_SESSION['LOCK_VARS_TO_USE']))){
1239     $_SESSION['LOCK_VARS_USED']  =array();
1240     foreach($_SESSION['LOCK_VARS_TO_USE'] as $name){
1242       if(empty($name)) continue;
1243       foreach($_POST as $Pname => $Pvalue){
1244         if(preg_match($name,$Pname)){
1245           $_SESSION['LOCK_VARS_USED'][$Pname] = $_POST[$Pname];
1246         }
1247       }
1249       foreach($_GET as $Pname => $Pvalue){
1250         if(preg_match($name,$Pname)){
1251           $_SESSION['LOCK_VARS_USED'][$Pname] = $_GET[$Pname];
1252         }
1253       }
1254     }
1255     $_SESSION['LOCK_VARS_TO_USE'] =array();
1256   }
1258   /* Prepare and show template */
1259   $smarty= get_smarty();
1260   $smarty->assign ("dn", $dn);
1261   if ($remove){
1262     $smarty->assign ("action", _("Continue anyway"));
1263   } else {
1264     $smarty->assign ("action", _("Edit anyway"));
1265   }
1266   $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>"));
1268   return ($smarty->fetch (get_template_path('islocked.tpl')));
1272 function to_string ($value)
1274   /* If this is an array, generate a text blob */
1275   if (is_array($value)){
1276     $ret= "";
1277     foreach ($value as $line){
1278       $ret.= $line."<br>\n";
1279     }
1280     return ($ret);
1281   } else {
1282     return ($value);
1283   }
1287 function get_printer_list($cups_server)
1289   global $config;
1291   $res= array();
1293   /* Use CUPS, if we've access to it */
1294   if (function_exists('cups_get_dest_list')){
1295     $dest_list= cups_get_dest_list ($cups_server);
1297     foreach ($dest_list as $prt){
1298       $attr= cups_get_printer_attributes ($cups_server, $prt->name);
1300       foreach ($attr as $prt_info){
1301         if ($prt_info->name == "printer-info"){
1302           $info= $prt_info->value;
1303           break;
1304         }
1305       }
1306       $res[$prt->name]= "$info [$prt->name]";
1307     }
1309     /* CUPS is not available, try lpstat as a replacement */
1310   } else {
1311     $ar = false;
1312     exec("lpstat -p", $ar);
1313     foreach($ar as $val){
1314       @list($dummy, $printer, $rest)= split(' ', $val, 3);
1315       if (preg_match('/^[^@]+$/', $printer)){
1316         $res[$printer]= "$printer";
1317       }
1318     }
1319   }
1321   /* Merge in printers from LDAP */
1322   $ldap= $config->get_ldap_link();
1323   $ldap->cd ($config->current['BASE']);
1324   $ui= get_userinfo();
1325   if (isset($config->current['STRICT_UNITS']) && preg_match('/TRUE/i', $config->current['STRICT_UNITS']) && $ui->gosaUnitTag != ""){   
1326     $ldap->search('((objectClass=gotoPrinter)(gosaUnitTag='.$ui->gosaUnitTag.'))', array('cn'));
1327   } else {
1328     $ldap->search('(objectClass=gotoPrinter)', array('cn'));
1329   }
1330   while($attrs = $ldap->fetch()){
1331     $res[$attrs['cn'][0]] = $attrs['cn'][0];
1332   }
1334   return $res;
1338 function sess_del ($var)
1340   /* New style */
1341   unset ($_SESSION[$var]);
1343   /* ... work around, since the first one
1344      doesn't seem to work all the time */
1345   session_unregister ($var);
1349 function show_errors($message)
1351   $complete= "";
1353   /* Assemble the message array to a plain string */
1354   foreach ($message as $error){
1355     if ($complete == ""){
1356       $complete= $error;
1357     } else {
1358       $complete= "$error<br>$complete";
1359     }
1360   }
1362   /* Fill ERROR variable with nice error dialog */
1363   print_red($complete);
1367 function show_ldap_error($message, $addon= "")
1369   if (!preg_match("/Success/i", $message)){
1370     if ($addon == ""){
1371       print_red (_("LDAP error: $message"));
1372     } else {
1373       print_red ("$addon<br><br><b>"._("LDAP error:")."</b> $message");
1374     }
1375     return TRUE;
1376   } else {
1377     return FALSE;
1378   }
1382 function rewrite($s)
1384   global $REWRITE;
1386   foreach ($REWRITE as $key => $val){
1387     $s= preg_replace("/$key/", "$val", $s);
1388   }
1390   return ($s);
1394 function dn2base($dn)
1396   global $config;
1398   if (get_people_ou() != ""){
1399     $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1400   }
1401   if (get_groups_ou() != ""){
1402     $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1403   }
1404   $base= preg_replace ('/^[^,]+,/i', '', $dn);
1406   return ($base);
1411 function check_command($cmdline)
1413   $cmd= preg_replace("/ .*$/", "", $cmdline);
1415   /* Check if command exists in filesystem */
1416   if (!file_exists($cmd)){
1417     return (FALSE);
1418   }
1420   /* Check if command is executable */
1421   if (!is_executable($cmd)){
1422     return (FALSE);
1423   }
1425   return (TRUE);
1429 function print_header($image, $headline, $info= "")
1431   $display= "<div class=\"plugtop\">\n";
1432   $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";
1433   $display.= "</div>\n";
1435   if ($info != ""){
1436     $display.= "<div class=\"pluginfo\">\n";
1437     $display.= "$info";
1438     $display.= "</div>\n";
1439   } else {
1440     $display.= "<div style=\"height:5px;\">\n";
1441     $display.= "&nbsp;";
1442     $display.= "</div>\n";
1443   }
1444 #  if (isset($_SESSION['errors'])){
1445 #    $display.= $_SESSION['errors'];
1446 #  }
1448   return ($display);
1452 function register_global($name, $object)
1454   $_SESSION[$name]= $object;
1458 function is_global($name)
1460   return isset($_SESSION[$name]);
1464 function get_global($name)
1466   return $_SESSION[$name];
1470 function range_selector($dcnt,$start,$range=25,$post_var=false)
1473   /* Entries shown left and right from the selected entry */
1474   $max_entries= 10;
1476   /* Initialize and take care that max_entries is even */
1477   $output="";
1478   if ($max_entries & 1){
1479     $max_entries++;
1480   }
1482   if((!empty($post_var))&&(isset($_POST[$post_var]))){
1483     $range= $_POST[$post_var];
1484   }
1486   /* Prevent output to start or end out of range */
1487   if ($start < 0 ){
1488     $start= 0 ;
1489   }
1490   if ($start >= $dcnt){
1491     $start= $range * (int)(($dcnt / $range) + 0.5);
1492   }
1494   $numpages= (($dcnt / $range));
1495   if(((int)($numpages))!=($numpages)){
1496     $numpages = (int)$numpages + 1;
1497   }
1498   if ((((int)$numpages) <= 1 )&&(!$post_var)){
1499     return ("");
1500   }
1501   $ppage= (int)(($start / $range) + 0.5);
1504   /* Align selected page to +/- max_entries/2 */
1505   $begin= $ppage - $max_entries/2;
1506   $end= $ppage + $max_entries/2;
1508   /* Adjust begin/end, so that the selected value is somewhere in
1509      the middle and the size is max_entries if possible */
1510   if ($begin < 0){
1511     $end-= $begin + 1;
1512     $begin= 0;
1513   }
1514   if ($end > $numpages) {
1515     $end= $numpages;
1516   }
1517   if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1518     $begin= $end - $max_entries;
1519   }
1521   if($post_var){
1522     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1523       <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1524   }else{
1525     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1526   }
1528   /* Draw decrement */
1529   if ($start > 0 ) {
1530     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1531       (($start-$range))."\">".
1532       "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1533   }
1535   /* Draw pages */
1536   for ($i= $begin; $i < $end; $i++) {
1537     if ($ppage == $i){
1538       $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1539         validate($_GET['plug'])."&amp;start=".
1540         ($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1541     } else {
1542       $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1543         "&amp;start=".($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1544     }
1545   }
1547   /* Draw increment */
1548   if($start < ($dcnt-$range)) {
1549     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1550       (($start+($range)))."\">".
1551       "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1552   }
1554   if(($post_var)&&($numpages)){
1555     $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()'>";
1556     foreach(array(20,50,100,200,"all") as $num){
1557       if($num == "all"){
1558         $var = 10000;
1559       }else{
1560         $var = $num;
1561       }
1562       if($var == $range){
1563         $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1564       }else{  
1565         $output.="\n<option value='".$var."'>".$num."</option>";
1566       }
1567     }
1568     $output.=  "</select></td></tr></table></div>";
1569   }else{
1570     $output.= "</div>";
1571   }
1573   return($output);
1577 function apply_filter()
1579   $apply= "";
1581   $apply= ''.
1582     '<table summary=""  width="100%"  style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1583     '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1585   return ($apply);
1589 function back_to_main()
1591   $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1592     _("Back").'"></p><input type="hidden" name="ignore">';
1594   return ($string);
1598 function normalize_netmask($netmask)
1600   /* Check for notation of netmask */
1601   if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1602     $num= (int)($netmask);
1603     $netmask= "";
1605     for ($byte= 0; $byte<4; $byte++){
1606       $result=0;
1608       for ($i= 7; $i>=0; $i--){
1609         if ($num-- > 0){
1610           $result+= pow(2,$i);
1611         }
1612       }
1614       $netmask.= $result.".";
1615     }
1617     return (preg_replace('/\.$/', '', $netmask));
1618   }
1620   return ($netmask);
1624 function netmask_to_bits($netmask)
1626   list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1627   $res= 0;
1629   for ($n= 0; $n<4; $n++){
1630     $start= 255;
1631     $name= "nm$n";
1633     for ($i= 0; $i<8; $i++){
1634       if ($start == (int)($$name)){
1635         $res+= 8 - $i;
1636         break;
1637       }
1638       $start-= pow(2,$i);
1639     }
1640   }
1642   return ($res);
1646 function recurse($rule, $variables)
1648   $result= array();
1650   if (!count($variables)){
1651     return array($rule);
1652   }
1654   reset($variables);
1655   $key= key($variables);
1656   $val= current($variables);
1657   unset ($variables[$key]);
1659   foreach($val as $possibility){
1660     $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1661     $result= array_merge($result, recurse($nrule, $variables));
1662   }
1664   return ($result);
1668 function expand_id($rule, $attributes)
1670   /* Check for id rule */
1671   if(preg_match('/^id(:|#)\d+$/',$rule)){
1672     return (array("\{$rule}"));
1673   }
1675   /* Check for clean attribute */
1676   if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1677     $rule= preg_replace('/^%/', '', $rule);
1678     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1679     return (array($val));
1680   }
1682   /* Check for attribute with parameters */
1683   if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1684     $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1685     $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1686     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1687     $start= preg_replace ('/-.*$/', '', $param);
1688     $stop = preg_replace ('/^[^-]+-/', '', $param);
1690     /* Assemble results */
1691     $result= array();
1692     for ($i= $start; $i<= $stop; $i++){
1693       $result[]= substr($val, 0, $i);
1694     }
1695     return ($result);
1696   }
1698   echo "Error in idgen string: don't know how to handle rule $rule.\n";
1699   return (array($rule));
1703 function gen_uids($rule, $attributes)
1705   global $config;
1707   /* Search for keys and fill the variables array with all 
1708      possible values for that key. */
1709   $part= "";
1710   $trigger= false;
1711   $stripped= "";
1712   $variables= array();
1714   for ($pos= 0; $pos < strlen($rule); $pos++){
1716     if ($rule[$pos] == "{" ){
1717       $trigger= true;
1718       $part= "";
1719       continue;
1720     }
1722     if ($rule[$pos] == "}" ){
1723       $variables[$pos]= expand_id($part, $attributes);
1724       $stripped.= "{".$pos."}";
1725       $trigger= false;
1726       continue;
1727     }
1729     if ($trigger){
1730       $part.= $rule[$pos];
1731     } else {
1732       $stripped.= $rule[$pos];
1733     }
1734   }
1736   /* Recurse through all possible combinations */
1737   $proposed= recurse($stripped, $variables);
1739   /* Get list of used ID's */
1740   $used= array();
1741   $ldap= $config->get_ldap_link();
1742   $ldap->cd($config->current['BASE']);
1743   $ldap->search('(uid=*)');
1745   while($attrs= $ldap->fetch()){
1746     $used[]= $attrs['uid'][0];
1747   }
1749   /* Remove used uids and watch out for id tags */
1750   $ret= array();
1751   foreach($proposed as $uid){
1753     /* Check for id tag and modify uid if needed */
1754     if(preg_match('/\{id:\d+}/',$uid)){
1755       $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1757       for ($i= 0; $i < pow(10,$size); $i++){
1758         $number= sprintf("%0".$size."d", $i);
1759         $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1760         if (!in_array($res, $used)){
1761           $uid= $res;
1762           break;
1763         }
1764       }
1765     }
1767   if(preg_match('/\{id#\d+}/',$uid)){
1768     $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1770     while (true){
1771       mt_srand((double) microtime()*1000000);
1772       $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1773       $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1774       if (!in_array($res, $used)){
1775         $uid= $res;
1776         break;
1777       }
1778     }
1779   }
1781 /* Don't assign used ones */
1782 if (!in_array($uid, $used)){
1783   $ret[]= $uid;
1787 return(array_unique($ret));
1791 function array_search_r($needle, $key, $haystack){
1793   foreach($haystack as $index => $value){
1794     $match= 0;
1796     if (is_array($value)){
1797       $match= array_search_r($needle, $key, $value);
1798     }
1800     if ($index==$key && !is_array($value) && preg_match("/$needle/i", $value)){
1801       $match=1;
1802     }
1804     if ($match){
1805       return 1;
1806     }
1807   }
1809   return 0;
1810
1813 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1814    Need to convert... */
1815 function to_byte($value) {
1816   $value= strtolower(trim($value));
1818   if(!is_numeric(substr($value, -1))) {
1820     switch(substr($value, -1)) {
1821       case 'g':
1822         $mult= 1073741824;
1823         break;
1824       case 'm':
1825         $mult= 1048576;
1826         break;
1827       case 'k':
1828         $mult= 1024;
1829         break;
1830     }
1832     return ($mult * (int)substr($value, 0, -1));
1833   } else {
1834     return $value;
1835   }
1839 function in_array_ics($value, $items)
1841   if (!is_array($items)){
1842     return (FALSE);
1843   }
1845   foreach ($items as $item){
1846     if (strtolower($item) == strtolower($value)) {
1847       return (TRUE);
1848     }
1849   }
1851   return (FALSE);
1852
1855 function generate_alphabet($count= 10)
1857   $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1858   $alphabet= "";
1859   $c= 0;
1861   /* Fill cells with charaters */
1862   for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1863     if ($c == 0){
1864       $alphabet.= "<tr>";
1865     }
1867     $ch = mb_substr($characters, $i, 1, "UTF8");
1868     $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1869       validate($_GET['plug'])."&amp;search=".$ch."\">&nbsp;".$ch."&nbsp;</a></td>";
1871     if ($c++ == $count){
1872       $alphabet.= "</tr>";
1873       $c= 0;
1874     }
1875   }
1877   /* Fill remaining cells */
1878   while ($c++ <= $count){
1879     $alphabet.= "<td>&nbsp;</td>";
1880   }
1882   return ($alphabet);
1886 function validate($string)
1888   return (strip_tags(preg_replace('/\0/', '', $string)));
1891 function get_gosa_version()
1893   global $svn_revision, $svn_path;
1895   /* Extract informations */
1896   $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1898   /* Release or development? */
1899   if (preg_match('%/gosa/trunk/%', $svn_path)){
1900     return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1901   } else {
1902     $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1903     return (_("GOsa $release"));
1904   }
1908 function rmdirRecursive($path, $followLinks=false) {
1909   $dir= opendir($path);
1910   while($entry= readdir($dir)) {
1911     if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1912       unlink($path."/".$entry);
1913     } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1914       rmdirRecursive($path."/".$entry);
1915     }
1916   }
1917   closedir($dir);
1918   return rmdir($path);
1921 function scan_directory($path,$sort_desc=false)
1923   $ret = false;
1925   /* is this a dir ? */
1926   if(is_dir($path)) {
1928     /* is this path a readable one */
1929     if(is_readable($path)){
1931       /* Get contents and write it into an array */   
1932       $ret = array();    
1934       $dir = opendir($path);
1936       /* Is this a correct result ?*/
1937       if($dir){
1938         while($fp = readdir($dir))
1939           $ret[]= $fp;
1940       }
1941     }
1942   }
1943   /* Sort array ascending , like scandir */
1944   sort($ret);
1946   /* Sort descending if parameter is sort_desc is set */
1947   if($sort_desc) {
1948     $ret = array_reverse($ret);
1949   }
1951   return($ret);
1954 function clean_smarty_compile_dir($directory)
1956   global $svn_revision;
1958   if(is_dir($directory) && is_readable($directory)) {
1959     // Set revision filename to REVISION
1960     $revision_file= $directory."/REVISION";
1962     /* Is there a stamp containing the current revision? */
1963     if(!file_exists($revision_file)) {
1964       // create revision file
1965       create_revision($revision_file, $svn_revision);
1966     } else {
1967 # check for "$config->...['CONFIG']/revision" and the
1968 # contents should match the revision number
1969       if(!compare_revision($revision_file, $svn_revision)){
1970         // If revision differs, clean compile directory
1971         foreach(scan_directory($directory) as $file) {
1972           if(($file==".")||($file=="..")) continue;
1973           if( is_file($directory."/".$file) &&
1974               is_writable($directory."/".$file)) {
1975             // delete file
1976             if(!unlink($directory."/".$file)) {
1977               print_red("File ".$directory."/".$file." could not be deleted.");
1978               // This should never be reached
1979             }
1980           } elseif(is_dir($directory."/".$file) &&
1981               is_writable($directory."/".$file)) {
1982             // Just recursively delete it
1983             rmdirRecursive($directory."/".$file);
1984           }
1985         }
1986         // We should now create a fresh revision file
1987         clean_smarty_compile_dir($directory);
1988       } else {
1989         // Revision matches, nothing to do
1990       }
1991     }
1992   } else {
1993     // Smarty compile dir is not accessible
1994     // (Smarty will warn about this)
1995   }
1998 function create_revision($revision_file, $revision)
2000   $result= false;
2002   if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
2003     if($fh= fopen($revision_file, "w")) {
2004       if(fwrite($fh, $revision)) {
2005         $result= true;
2006       }
2007     }
2008     fclose($fh);
2009   } else {
2010     print_red("Can not write to revision file");
2011   }
2013   return $result;
2016 function compare_revision($revision_file, $revision)
2018   // false means revision differs
2019   $result= false;
2021   if(file_exists($revision_file) && is_readable($revision_file)) {
2022     // Open file
2023     if($fh= fopen($revision_file, "r")) {
2024       // Compare File contents with current revision
2025       if($revision == fread($fh, filesize($revision_file))) {
2026         $result= true;
2027       }
2028     } else {
2029       print_red("Can not open revision file");
2030     }
2031     // Close file
2032     fclose($fh);
2033   }
2035   return $result;
2038 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
2040   $str = ""; // Our return value will be saved in this var
2042   $color  = dechex($percentage+150);
2043   $color2 = dechex(150 - $percentage);
2044   $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
2046   $progress = (int)(($percentage /100)*$width);
2048   /* Abort printing out percentage, if divs are to small */
2051   /* If theres a better solution for this, use it... */
2052   $str = "
2053     <div style=\" width:".($width)."px; 
2054     height:".($height)."px;
2055   background-color:#000000;
2056 padding:1px;\">
2058           <div style=\" width:".($width)."px;
2059         background-color:#$bgcolor;
2060 height:".($height)."px;\">
2062          <div style=\" width:".$progress."px;
2063 height:".$height."px;
2064        background-color:#".$color2.$color2.$color."; \">";
2067        if(($height >10)&&($showvalue)){
2068          $str.=                 "<font style=\"font-size:".($height-2)."px;color:#FF0000;align:middle;padding-left:".((int)(($width*0.4)))."px;\">
2069            <b>".$percentage."%</b>
2070            </font>";
2071        }
2073        $str.= "</div></div></div>";
2075        return($str);
2079 function array_key_ics($ikey, $items)
2081   /* Gather keys, make them lowercase */
2082   $tmp= array();
2083   foreach ($items as $key => $value){
2084     $tmp[strtolower($key)]= $key;
2085   }
2087   if (isset($tmp[strtolower($ikey)])){
2088     return($tmp[strtolower($ikey)]);
2089   }
2091   return ("");
2095 function search_config($arr, $name, $return)
2097   if (is_array($arr)){
2098     foreach ($arr as $a){
2099       if (isset($a['CLASS']) &&
2100           strtolower($a['CLASS']) == strtolower($name)){
2102         if (isset($a[$return])){
2103           return ($a[$return]);
2104         } else {
2105           return ("");
2106         }
2107       } else {
2108         $res= search_config ($a, $name, $return);
2109         if ($res != ""){
2110           return $res;
2111         }
2112       }
2113     }
2114   }
2115   return ("");
2119 function array_differs($src, $dst)
2121   /* If the count is differing, the arrays differ */
2122   if (count ($src) != count ($dst)){
2123     return (TRUE);
2124   }
2126   /* So the count is the same - lets check the contents */
2127   $differs= FALSE;
2128   foreach($src as $value){
2129     if (!in_array($value, $dst)){
2130       $differs= TRUE;
2131     }
2132   }
2134   return ($differs);
2138 function saveFilter($a_filter, $values)
2140   if (isset($_POST['regexit'])){
2141     $a_filter["regex"]= $_POST['regexit'];
2143     foreach($values as $type){
2144       if (isset($_POST[$type])) {
2145         $a_filter[$type]= "checked";
2146       } else {
2147         $a_filter[$type]= "";
2148       }
2149     }
2150   }
2152   /* React on alphabet links if needed */
2153   if (isset($_GET['search'])){
2154     $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2155     if ($s == "**"){
2156       $s= "*";
2157     }
2158     $a_filter['regex']= $s;
2159   }
2161   return ($a_filter);
2165 /* Escape all preg_* relevant characters */
2166 function normalizePreg($input)
2168   return (addcslashes($input, '[]()|/.*+-'));
2172 /* Escape all LDAP filter relevant characters */
2173 function normalizeLdap($input)
2175   return (addcslashes($input, '()|'));
2179 /* Resturns the difference between to microtime() results in float  */
2180 function get_MicroTimeDiff($start , $stop)
2182   $a = split("\ ",$start);
2183   $b = split("\ ",$stop);
2185   $secs = $b[1] - $a[1];
2186   $msecs= $b[0] - $a[0]; 
2188   $ret = (float) ($secs+ $msecs);
2189   return($ret);
2193 /* Check if the given department name is valid */
2194 function is_department_name_reserved($name,$base)
2196   $reservedName = array("systems","apps","incomming","internal","accounts","fax","addressbook",
2197                           preg_replace("/ou=(.*),/","\\1",get_people_ou()),
2198                           preg_replace("/ou=(.*),/","\\1",get_groups_ou()));
2199   $follwedNames['/ou=fai,ou=configs,ou=systems,/'] = array("fai","hooks","templates","scripts","disk","packages","variables","profiles");
2201   /* Check if name is one of the reserved names */
2202   if(in_array_ics($name,$reservedName)) {
2203     return(true);
2204   }
2206   /* Check all follow combinations if name is in array && parent base == array_key, return false*/
2207   foreach($follwedNames as $key => $names){
2208     if((in_array_ics($name,$names)) && (preg_match($key,$base))){
2209       return(true);
2210     }
2211   }
2212   return(false);
2216 function is_php4()
2218   if (isset($_SESSION['PHP4COMPATIBLE'])){
2219     return true;
2220   }
2221   return (preg_match('/^4/', phpversion()));
2225 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2227   /* Initialize variables */
2228   $ret  = array("count" => 0);  // Set count to 0
2229   $next = true;                 // if false, then skip next loops and return
2230   $cnt  = 0;                    // Current number of loops
2231   $max  = 100;                  // Just for security, prevent looops
2232   $ldap = NULL;                 // To check if created result a valid
2233   $keep = "";                   // save last failed parse string
2235   /* Check each parsed dn in ldap ? */
2236   if($config!=NULL && $verify_in_ldap){
2237     $ldap = $config->get_ldap_link();
2238   }
2240   /* Lets start */
2241   $called = false;
2242   while(preg_match("/,/",$dn) && $next &&  $cnt < $max){
2244     $cnt ++;
2245     if(!preg_match("/,/",$dn)){
2246       $next = false;
2247     }
2248     $object = preg_replace("/[,].*$/","",$dn);
2249     $dn     = preg_replace("/^[^,]+,/","",$dn);
2251     $called = true;
2253     /* Check if current dn is valid */
2254     if($ldap!=NULL){
2255       $ldap->cd($dn);
2256       $ldap->cat($dn,array("dn"));
2257       if($ldap->count()){
2258         $ret[]  = $keep.$object;
2259         $keep   = "";
2260       }else{
2261         $keep  .= $object.",";
2262       }
2263     }else{
2264       $ret[]  = $keep.$object;
2265       $keep   = "";
2266     }
2267   }
2269   /* No dn was posted */
2270   if($cnt == 0 && !empty($dn)){
2271     $ret[] = $dn;
2272   }
2274   /* Append the rest */
2275   $test = $keep.$dn;
2276   if($called && !empty($test)){
2277     $ret[] = $keep.$dn;
2278   }
2279   $ret['count'] = count($ret) - 1;
2281   return($ret);
2285 function get_base_from_hook($dn, $attrib)
2287   global $config;
2289   if (isset($config->current['BASE_HOOK'])){
2290     
2291     /* Call hook script - if present */
2292     $command= $config->current['BASE_HOOK'];
2294     if ($command != ""){
2295       $command.= " '$dn' $attrib";
2296       if (check_command($command)){
2297         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2298         exec($command, $output);
2299         if (preg_match("/^[0-9]+$/", $output[0])){
2300           return ($output[0]);
2301         } else {
2302           print_red(_("Warning - base_hook is not available. Using default base."));
2303           return ($config->current['UIDBASE']);
2304         }
2305       } else {
2306         print_red(_("Warning - base_hook is not available. Using default base."));
2307         return ($config->current['UIDBASE']);
2308       }
2310     } else {
2312       print_red(_("Warning - no base_hook defined. Using default base."));
2313       return ($config->current['UIDBASE']);
2315     }
2316   }
2319 /* Schema validation functions */
2321   function check_schema_version($class, $version)
2322   {
2323     return preg_match("/\(v$version\)/", $class['DESC']);
2324   }
2326   
2328   function check_schema($cfg,$rfc2307bis = FALSE)
2329   {
2331     $messages= array();
2333     /* Get objectclasses */
2334     $ldap = new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE,$cfg['tls']);
2335     $objectclasses = $ldap->get_objectclasses();
2336     if(count($objectclasses) == 0){
2337       print_red(_("Can't get schema information from server. No schema check possible!"));
2338     }
2340     /* This is the default block used for each entry.
2341      *  to avoid unset indexes.
2342      */
2343     $def_check = array("REQUIRED_VERSION" => "0",
2344                        "SCHEMA_FILES"     => array(),
2345                        "CLASSES_REQUIRED" => array(),
2346                        "STATUS"           => FALSE,
2347                        "IS_MUST_HAVE"     => FALSE,
2348                        "MSG"              => "",
2349                        "INFO"             => "");#_("There is currently no information specified for this schema extension."));
2351  /* The gosa base schema */
2352     $checks['gosaObject'] = $def_check;
2353     $checks['gosaObject']['REQUIRED_VERSION'] = "2.4";
2354     $checks['gosaObject']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2355     $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2356     $checks['gosaObject']['IS_MUST_HAVE']     = TRUE;
2358     /* GOsa Account class */
2359     $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.4";
2360     $checks["gosaAccount"]["SCHEMA_FILES"]    = array("gosa+samba3.schema","gosa.schema");
2361     $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2362     $checks["gosaAccount"]["IS_MUST_HAVE"]    = TRUE;
2363     $checks["gosaAccount"]["INFO"]            = _("Used to store account specific informations.");
2365     /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2366     $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.4";
2367     $checks["gosaLockEntry"]["SCHEMA_FILES"]     = array("gosa+samba3.schema","gosa.schema");
2368     $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2369     $checks["gosaLockEntry"]["IS_MUST_HAVE"]     = TRUE;
2370     $checks["gosaLockEntry"]["INFO"]             = _("Used to lock currently edited entries to avoid multiple changes at the same time.");
2372   /* Some other checks */
2373     foreach(array(
2374           "gosaCacheEntry"        => array("version" => "2.4"),
2375           "gosaDepartment"        => array("version" => "2.4"),
2376           "goFaxAccount"          => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2377           "goFaxSBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2378           "goFaxRBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2379           "gosaUserTemplate"      => array("version" => "2.4", "class" => "posixAccount","file" => "nis.schema"),
2380           "gosaMailAccount"       => array("version" => "2.4", "class" => "mailAccount","file" => "gosa+samba3.schema"),
2381           "gosaProxyAccount"      => array("version" => "2.4", "class" => "proxyAccount","file" => "gosa+samba3.schema"),
2382           "gosaApplication"       => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2383           "gosaApplicationGroup"  => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2384           "GOhard"                => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2385           "gotoTerminal"          => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2386           "goServer"              => array("version" => "2.4","class" => "server","file" => "goserver.schema"),
2387           "goTerminalServer"      => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2388           "goShareServer"         => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2389           "goNtpServer"           => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2390           "goSyslogServer"        => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2391           "goLdapServer"          => array("version" => "2.4"),
2392           "goCupsServer"          => array("version" => "2.4", "class" => array("posixAccount", "terminals"),),
2393           "goImapServer"          => array("version" => "2.4", "class" => array("mailAccount", "mailgroup"),"file" => "gosa+samba3.        schema"),
2394           "goKrbServer"           => array("version" => "2.4"),
2395           "goFaxServer"           => array("version" => "2.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2396           ) as $name => $values){
2398       $checks[$name] = $def_check;
2399       if(isset($values['version'])){
2400         $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2401       }
2402       if(isset($values['file'])){
2403         $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2404       }
2405       $checks[$name]["CLASSES_REQUIRED"] = array($name);
2406     }
2407    foreach($checks as $name => $value){
2408       foreach($value['CLASSES_REQUIRED'] as $class){
2410         if(!isset($objectclasses[$name])){
2411           $checks[$name]['STATUS'] = FALSE;
2412           if($value['IS_MUST_HAVE']){
2413             $checks[$name]['MSG']    = sprintf(_("The required objectClass '%s' is not present in your schema setup"),$class);
2414           }else{
2415             $checks[$name]['MSG']    = sprintf(_("The optional objectClass '%s' is not present in your schema setup"),$class);
2416           }
2417         }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2418           $checks[$name]['STATUS'] = FALSE;
2420           if($value['IS_MUST_HAVE']){
2421             $checks[$name]['MSG'] = sprintf(_("The required objectclass '%s' does not have version %s"), $class,                           $value['REQUIRED_VERSION']);
2422           }else{
2423             $checks[$name]['MSG'] = sprintf(_("The optional objectclass '%s' does not have version %s"), $class,                           $value['REQUIRED_VERSION']);
2424           }
2425         }else{
2426           $checks[$name]['STATUS'] = TRUE;
2427           $checks[$name]['MSG'] = sprintf(_("Class(es) available"));
2428         }
2429       }
2430     }
2432     $tmp = $objectclasses;
2435     /* The gosa base schema */
2436     $checks['posixGroup'] = $def_check;
2437     $checks['posixGroup']['REQUIRED_VERSION'] = "2.4";
2438     $checks['posixGroup']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2439     $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2440     $checks['posixGroup']['STATUS']           = TRUE;
2441     $checks['posixGroup']['IS_MUST_HAVE']     = TRUE;
2442     $checks['posixGroup']['MSG']              = "";
2443     $checks['posixGroup']['INFO']             = "";
2445     /* Depending on selected rfc2307bis mode, we need different schema configurations */
2446     if(isset($tmp['posixGroup'])){
2448       if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2449         $checks['posixGroup']['STATUS']           = FALSE;
2450         $checks['posixGroup']['MSG']              = _("You have enabled the rfc2307bis option on the 'ldap setup' step, but your schema    configuration do not support this option.");
2451         $checks['posixGroup']['INFO']             = _("In order to use rfc2307bis conform groups the objectClass 'posixGroup' must be      AUXILIARY");
2452       }
2453       if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2454         $checks['posixGroup']['STATUS']           = FALSE;
2455         $checks['posixGroup']['MSG']              = _("You have disabled the rfc2307bis option on the 'ldap setup' step, but your schema   configuration do not support this option.");
2456         $checks['posixGroup']['INFO']             = _("The objectClass 'posixGroup' must be STRUCTURAL");
2457       }
2458     }
2460     return($checks);
2461   }
2464 function prepare4mailbody($string)
2466   $string = html_entity_decode($string);
2468   $from = array(
2469                 "/%/",
2470                 "/ /",
2471                 "/\n/",  
2472                 "/\r/",
2473                 "/!/",
2474                 "/#/",
2475                 "/\*/",
2476                 "/\//",
2477                 "/</",
2478                 "/>/",
2479                 "/\?/",
2480                 "/\&/",
2481                 "/\(/",
2482                 "/\)/",
2483                 "/\"/");
2484   
2485   $to = array(  
2486                 "%25",
2487                 "%20",
2488                 "%0A",
2489                 "%0D",
2490                 "%21",
2491                 "%23",
2492                 "%2A",
2493                 "%2F",
2494                 "%3C",
2495                 "%3E",
2496                 "%3F",
2497                 "%38",
2498                 "%28",
2499                 "%29",
2500                 "%22");
2502   $string = preg_replace($from,$to,$string);
2504   return($string);
2508 function mac2company($mac)
2510   $vendor= "";
2512   /* Generate a normailzed mac... */
2513   $mac= substr(preg_replace('/[:-]/', '', $mac), 0, 6);
2515   /* Check for existance of the oui file */
2516   if (!is_readable(CONFIG_DIR."/oui.txt")){
2517     return ("");
2518   }
2520   /* Open file and look for mac addresses... */
2521   $handle = @fopen(CONFIG_DIR."/oui.txt", "r");
2522   if ($handle) {
2523     while (!feof($handle)) {
2524       $line = fgets($handle, 4096);
2526       if (preg_match("/^$mac/i", $line)){
2527         $vendor= substr($line, 32);
2528       }
2529     }
2530     fclose($handle);
2531   }
2533   return ($vendor);
2537 function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FALSE)
2539   $tmp = array(
2540         "de_DE" => "German",
2541         "fr_FR" => "French",
2542         "it_IT" => "Italian",
2543         "es_ES" => "Spanish",
2544         "en_US" => "English",
2545         "nl_NL" => "Dutch",
2546         "pl_PL" => "Polish",
2547         "sv_SE" => "Swedish",
2548         "zh_CN" => "Chinese",
2549         "ru_RU" => "Russian");
2550   
2551   $tmp2= array(
2552         "de_DE" => _("German"),
2553         "fr_FR" => _("French"),
2554         "it_IT" => _("Italian"),
2555         "es_ES" => _("Spanish"),
2556         "en_US" => _("English"),
2557         "nl_NL" => _("Dutch"),
2558         "pl_PL" => _("Polish"),
2559         "sv_SE" => _("Swedish"),
2560         "zh_CN" => _("Chinese"),
2561         "ru_RU" => _("Russian"));
2563   $ret = array();
2564   if($languages_in_own_language){
2566     $old_lang = setlocale(LC_ALL, 0);
2567     foreach($tmp as $key => $name){
2568       $lang = $key.".UTF-8";
2569       setlocale(LC_ALL, $lang);
2570       if($strip_region_tag){
2571         $ret[preg_replace("/^([^_]*).*$/","\\1",$key)] = _($name)." (".$tmp2[$key].")";
2572       }else{
2573         $ret[$key] = _($name)." &nbsp;(".$tmp2[$key].")";
2574       }
2575     }
2576     setlocale(LC_ALL, $old_lang);
2577   }else{
2578     foreach($tmp as $key => $name){
2579       if($strip_region_tag){
2580         $ret[preg_replace("/^([^_]*).*/","\\1",$key)] = _($name);
2581       }else{
2582         $ret[$key] = _($name);
2583       }
2584     }
2585   }
2586   return($ret);
2590 /* Check if $ip1 and $ip2 represents a valid IP range 
2591  *  returns TRUE in case of a valid range, FALSE in case of an error. 
2592  */
2593 function is_ip_range($ip1,$ip2)
2595   if(!is_ip($ip1) || !is_ip($ip2)){
2596     return(FALSE);
2597   }else{
2598     $ar1 = split("\.",$ip1);
2599     $var1 = $ar1[0] * (16777216) + $ar1[1] * (65536) + $ar1[2] * (256) + $ar1[3];
2601     $ar2 = split("\.",$ip2);
2602     $var2 = $ar2[0] * (16777216) + $ar2[1] * (65536) + $ar2[2] * (256) + $ar2[3];
2603     return($var1 < $var2);
2604   }
2608 /* Check if the specified IP address $address is inside the given network */
2609 function is_in_network($network, $netmask, $address)
2611   $nw= split('\.', $network);
2612   $nm= split('\.', $netmask);
2613   $ad= split('\.', $address);
2615   /* Generate inverted netmask */
2616   for ($i= 0; $i<4; $i++){
2617     $ni[$i]= 255-$nm[$i];
2618     $la[$i]= $nw[$i] | $ni[$i];
2619   }
2621   /* Transform to integer */
2622   $first= $nw[0] * (16777216) + $nw[1] * (65536) + $nw[2] * (256) + $nw[3];
2623   $curr=  $ad[0] * (16777216) + $ad[1] * (65536) + $ad[2] * (256) + $ad[3];
2624   $last=  $la[0] * (16777216) + $la[1] * (65536) + $la[2] * (256) + $la[3];
2626   return ($first < $curr&& $last > $curr);
2630 /* Returns contents of the given POST variable and check magic quotes settings */
2631 function get_post($name)
2633   if(!isset($_POST[$name])){
2634     trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2635     return(FALSE);
2636   }
2637   if(get_magic_quotes_gpc()){
2638     return(stripcslashes($_POST[$name]));
2639   }else{
2640     return($_POST[$name]);
2641   }
2644 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2645 ?>