Code

Added dhcp plugin to general include list
[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)
760   global $ui;
762   $final= "";
763   foreach($acl_array as $acl){
765     /* Check for selfflag (!) in ACL to determine if
766        the user is allowed to change parts of his/her
767        own account */
768     if (preg_match("/^!/", $acl)){
769       if ($dn != "" && $dn != $ui->dn){
771         /* No match for own DN, give up on this ACL */
772         continue;
774       } else {
776         /* Matches own DN, remove the selfflag */
777         $acl= preg_replace("/^!/", "", $acl);
779       }
780     }
782     /* Remove leading garbage */
783     $acl= preg_replace("/^:/", "", $acl);
785     /* Discover if we've access to the submodule by comparing
786        all allowed submodules specified in the ACL */
787     $tmp= split(",", $acl);
788     foreach ($tmp as $mod){
789       if (preg_match("/^$module#/", $mod)){
790         $final= strstr($mod, "#")."#";
791         continue;
792       }
793       if (preg_match("/[^#]$module$/", $mod)){
794         return ("#all#");
795       }
796       if (preg_match("/^all$/", $mod)){
797         return ("#all#");
798       }
799     }
800   }
802   /* Return assembled ACL, or none */
803   if ($final != ""){
804     return (preg_replace('/##/', '#', $final));
805   }
807   /* Nothing matches - disable access for this object */
808   return ("#none#");
812 function get_userinfo()
814   global $ui;
816   return $ui;
820 function get_smarty()
822   global $smarty;
824   return $smarty;
828 function convert_department_dn($dn)
830   $dep= "";
832   /* Build a sub-directory style list of the tree level
833      specified in $dn */
834   foreach (split(',', $dn) as $rdn){
836     /* We're only interested in organizational units... */
837     if (substr($rdn,0,3) == 'ou='){
838       $dep= substr($rdn,3)."/$dep";
839     }
841     /* ... and location objects */
842     if (substr($rdn,0,2) == 'l='){
843       $dep= substr($rdn,2)."/$dep";
844     }
845   }
847   /* Return and remove accidently trailing slashes */
848   return rtrim($dep, "/");
852 /* Strip off the last sub department part of a '/level1/level2/.../'
853  * style value. It removes the trailing '/', too. */
854 function get_sub_department($value)
856   return (@LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
860 function get_ou($name)
862   global $config;
864   /* Preset ou... */
865   if (isset($config->current[$name])){
866     $ou= $config->current[$name];
867   } else {
868     return "";
869   }
870   
871   if ($ou != ""){
872     if (!preg_match('/^[^=]+=[^=]+/', $ou)){
873       return @LDAP::convert("ou=$ou,");
874     } else {
875       return @LDAP::convert("$ou,");
876     }
877   } else {
878     return "";
879   }
883 function get_people_ou()
885   return (get_ou("PEOPLE"));
889 function get_groups_ou()
891   return (get_ou("GROUPS"));
895 function get_winstations_ou()
897   return (get_ou("WINSTATIONS"));
901 function get_base_from_people($dn)
903   global $config;
905   $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/i";
906   $base= preg_replace($pattern, '', $dn);
908   /* Set to base, if we're not on a correct subtree */
909   if (!isset($config->idepartments[$base])){
910     $base= $config->current['BASE'];
911   }
913   return ($base);
917 function chkacl($acl, $name)
919   /* Look for attribute in ACL */
920   if (preg_match("/#$name#/", $acl) || $acl == "#all#"){
921     return ("");
922   }
924   /* Optically disable html object for no match */
925   return (" disabled ");
929 function is_phone_nr($nr)
931   if ($nr == ""){
932     return (TRUE);
933   }
935   return preg_match ("/^[\/0-9 ()+*-]+$/", $nr);
939 function is_url($url)
941   if ($url == ""){
942     return (TRUE);
943   }
945   return preg_match ("/^(http|https):\/\/((?:[a-zA-Z0-9_-]+\.?)+):?(\d*)/", $url);
949 function is_dn($dn)
951   if ($dn == ""){
952     return (TRUE);
953   }
955   return preg_match ("/^[a-z0-9 _-]+$/i", $dn);
959 function is_uid($uid)
961   global $config;
963   if ($uid == ""){
964     return (TRUE);
965   }
967   /* STRICT adds spaces and case insenstivity to the uid check.
968      This is dangerous and should not be used. */
969   if (isset($config->current['STRICT']) && preg_match('/^(no|false)$/i', $config->current['STRICT'])){
970     return preg_match ("/^[a-z0-9 _.-]+$/i", $uid);
971   } else {
972     return preg_match ("/^[a-z0-9_-]+$/", $uid);
973   }
977 function is_ip($ip)
979   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);
983 function is_mac($mac)
985   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);
989 /* Checks if the given ip address doesn't match
990     "is_ip" because there is also a sub net mask given */
991 function is_ip_with_subnetmask($ip)
993         /* Generate list of valid submasks */
994         $res = array();
995         for($e = 0 ; $e <= 32; $e++){
996                 $res[$e] = $e;
997         }
998         $i[0] =255;
999         $i[1] =255;
1000         $i[2] =255;
1001         $i[3] =255;
1002         for($a= 3 ; $a >= 0 ; $a --){
1003                 $c = 1;
1004                 while($i[$a] > 0 ){
1005                         $str  = $i[0].".".$i[1].".".$i[2].".".$i[3];
1006                         $res[$str] = $str;
1007                         $i[$a] -=$c;
1008                         $c = 2*$c;
1009                 }
1010         }
1011         $res["0.0.0.0"] = "0.0.0.0";
1012         if(preg_match("/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1013                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1014                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1015                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/", $ip)){
1016                 $mask = preg_replace("/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1017                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1018                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1019                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/","",$ip);
1021                 $mask = preg_replace("/^\//","",$mask);
1022                 if((in_array("$mask",$res)) && preg_match("/^[0-9\.]/",$mask)){
1023                         return(TRUE);
1024                 }
1025         }
1026         return(FALSE);
1029 /* Simple is domain check, it checks if the given string looks like "string(...).string" */
1030 function is_domain($str)
1032   return(preg_match("/^([a-z0-9i\-]*)\.[a-z0-9]*$/i",$str));
1036 function is_id($id)
1038   if ($id == ""){
1039     return (FALSE);
1040   }
1042   return preg_match ("/^[0-9]+$/", $id);
1046 function is_path($path)
1048   if ($path == ""){
1049     return (TRUE);
1050   }
1051   if (!preg_match('/^[a-z0-9%\/_.+-]+$/i', $path)){
1052     return (FALSE);
1053   }
1055   return preg_match ("/\/.+$/", $path);
1059 function is_email($address, $template= FALSE)
1061   if ($address == ""){
1062     return (TRUE);
1063   }
1064   if ($template){
1065     return preg_match ("/^[._a-z0-9%-]+@[_a-z0-9-]+(\.[a-z0-9-]+)(\.[a-z0-9-]+)*$/i",
1066         $address);
1067   } else {
1068     return preg_match ("/^[._a-z0-9-]+@[_a-z0-9-]+(\.[a-z0-9i-]+)(\.[a-z0-9-]+)*$/i",
1069         $address);
1070   }
1074 function print_red()
1076   /* Check number of arguments */
1077   if (func_num_args() < 1){
1078     return;
1079   }
1081   /* Get arguments, save string */
1082   $array = func_get_args();
1083   $string= $array[0];
1085   /* Step through arguments */
1086   for ($i= 1; $i<count($array); $i++){
1087     $string= preg_replace ("/%s/", $array[$i], $string, 1);
1088   }
1090   if((!isset($_SESSION['errorsAlreadyPosted'])) || !is_array($_SESSION['errorsAlreadyPosted'])){
1091     $_SESSION['errorsAlreadyPosted'] = array(); 
1092   }
1094   /* If DEBUGLEVEL is set, we're in web mode, use textual output in
1095      the other case... */
1097   if (isset($_SESSION['DEBUGLEVEL'])){
1099     if($_SESSION['LastError'] == $string){
1100     
1101       if((!isset($_SESSION['errorsAlreadyPosted'][$string]))){
1102         $_SESSION['errorsAlreadyPosted'][$string] = 1;
1103       }
1104       $_SESSION['errorsAlreadyPosted'][$string]++;
1106     }else{
1107       if($string != NULL){
1108         if (preg_match("/"._("LDAP error:")."/", $string)){
1109           $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.");
1110           $img= "images/error.png";
1111         } else {
1112           if (!preg_match('/[.!?]$/', $string)){
1113             $string.= ".";
1114           }
1115           $string= preg_replace('/<br>/', ' ', $string);
1116           $img= "images/warning.png";
1117           $addmsg= _("Please check your input and fix the error. Press 'OK' to close this message box.");
1118         }
1119       
1120         if(isset($_SESSION['errors']) && strlen($_SESSION['errors'])==0) {
1123   if(preg_match("/MSIE/", $_SERVER['HTTP_USER_AGENT'])){
1125             $_SESSION['errors'].= "
1126               <iframe id='e_layer3'
1127                 style=\"  position:absolute;
1128                           width:100%;
1129                           height:100%;
1130                           top:0px;
1131                           left:0px;
1132                           border:none;
1133                           display:block;
1134                           allowtransparency='true';
1135                           background-color: #FFFFFF;
1136                           filter:chroma(color=#FFFFFF);
1137                           z-index:0; \">
1138               </iframe>
1139               <div  id='e_layer2'
1140                 style=\"
1141                   position: absolute;
1142                   left: 0px;
1143                   top: 0px;
1144                   right:0px;
1145                   bottom:0px;
1146                   z-index:0;
1147                   width:100%;
1148                   height:100%;
1149                   filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=scale, src='images/opacity_black.png'); \">
1150               </div>";
1151               $hide = "hide(\"e_layer\");hide(\"e_layer2\");hide(\"e_layer3\");";
1152           }else{
1154             $_SESSION['errors'].= "
1155               <div  id='e_layer2'
1156                 style=\"
1157                   position: absolute;
1158                   left: 0px;
1159                   top: 0px;
1160                   right:0px;
1161                   bottom:0px;
1162                   z-index:0;
1163                   background-image: url(images/opacity_black.png);\">
1164                </div>";
1165               $hide = "hide(\"e_layer\");hide(\"e_layer2\");";
1166           }
1168           $_SESSION['errors'].= "
1169           <div style='left:20%;right:20%;top:30%;".
1170             "background-color:white;padding:5px;border:5px solid red;z-index:150;".
1171             "position:absolute' id='e_layer'><table style='width:100%' summary='' border=0>".
1172             "<tr><td style='vertical-align:top;padding:10px'><img alt='' src='".
1173             get_template_path($img)."'></td>".
1174             "<td style='width:100%'><b>$string</b><br><br>$addmsg</td></tr><tr><td colspan='2' align='center'><br><button ".
1175             (($_SESSION['js']==FALSE)?"type='submit'":"type='button' name='error_accept'").
1176             " style='width:80px' onClick='".$hide."'>".
1177             _("OK")."</button></td></tr></table></div>";
1178         }
1180       }else{
1181         return;
1182       }
1183       $_SESSION['errorsAlreadyPosted'][$string] = 1;
1185     }
1187   } else {
1188     echo "Error: $string\n";
1189   }
1190   $_SESSION['LastError'] = $string; 
1194 function gen_locked_message($user, $dn)
1196   global $plug, $config;
1198   $_SESSION['dn']= $dn;
1199   $ldap= $config->get_ldap_link();
1200   $ldap->cat ($user, array('uid', 'cn'));
1201   $attrs= $ldap->fetch();
1203   /* Stop if we have no user here... */
1204   if (count($attrs)){
1205     $uid= $attrs["uid"][0];
1206     $cn= $attrs["cn"][0];
1207   } else {
1208     $uid= $attrs["uid"][0];
1209     $cn= $attrs["cn"][0];
1210   }
1211   
1212   $remove= false;
1214   if((isset($_SESSION['LOCK_VARS_TO_USE']))&&(count($_SESSION['LOCK_VARS_TO_USE']))){
1215     $_SESSION['LOCK_VARS_USED']  =array();
1216     foreach($_SESSION['LOCK_VARS_TO_USE'] as $name){
1218       if(empty($name)) continue;
1219       foreach($_POST as $Pname => $Pvalue){
1220         if(preg_match($name,$Pname)){
1221           $_SESSION['LOCK_VARS_USED'][$Pname] = $_POST[$Pname];
1222         }
1223       }
1225       foreach($_GET as $Pname => $Pvalue){
1226         if(preg_match($name,$Pname)){
1227           $_SESSION['LOCK_VARS_USED'][$Pname] = $_GET[$Pname];
1228         }
1229       }
1230     }
1231     $_SESSION['LOCK_VARS_TO_USE'] =array();
1232   }
1234   /* Prepare and show template */
1235   $smarty= get_smarty();
1236   $smarty->assign ("dn", $dn);
1237   if ($remove){
1238     $smarty->assign ("action", _("Continue anyway"));
1239   } else {
1240     $smarty->assign ("action", _("Edit anyway"));
1241   }
1242   $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>"));
1244   return ($smarty->fetch (get_template_path('islocked.tpl')));
1248 function to_string ($value)
1250   /* If this is an array, generate a text blob */
1251   if (is_array($value)){
1252     $ret= "";
1253     foreach ($value as $line){
1254       $ret.= $line."<br>\n";
1255     }
1256     return ($ret);
1257   } else {
1258     return ($value);
1259   }
1263 function get_printer_list($cups_server)
1265   global $config;
1267   $res= array();
1269   /* Use CUPS, if we've access to it */
1270   if (function_exists('cups_get_dest_list')){
1271     $dest_list= cups_get_dest_list ($cups_server);
1273     foreach ($dest_list as $prt){
1274       $attr= cups_get_printer_attributes ($cups_server, $prt->name);
1276       foreach ($attr as $prt_info){
1277         if ($prt_info->name == "printer-info"){
1278           $info= $prt_info->value;
1279           break;
1280         }
1281       }
1282       $res[$prt->name]= "$info [$prt->name]";
1283     }
1285     /* CUPS is not available, try lpstat as a replacement */
1286   } else {
1287     $ar = false;
1288     exec("lpstat -p", $ar);
1289     foreach($ar as $val){
1290       @list($dummy, $printer, $rest)= split(' ', $val, 3);
1291       if (preg_match('/^[^@]+$/', $printer)){
1292         $res[$printer]= "$printer";
1293       }
1294     }
1295   }
1297   /* Merge in printers from LDAP */
1298   $ldap= $config->get_ldap_link();
1299   $ldap->cd ($config->current['BASE']);
1300   $ui= get_userinfo();
1301   if (isset($config->current['STRICT_UNITS']) && preg_match('/TRUE/i', $config->current['STRICT_UNITS']) && $ui->gosaUnitTag != ""){   
1302     $ldap->search('((objectClass=gotoPrinter)(gosaUnitTag='.$ui->gosaUnitTag.'))', array('cn'));
1303   } else {
1304     $ldap->search('(objectClass=gotoPrinter)', array('cn'));
1305   }
1306   while($attrs = $ldap->fetch()){
1307     $res[$attrs['cn'][0]] = $attrs['cn'][0];
1308   }
1310   return $res;
1314 function sess_del ($var)
1316   /* New style */
1317   unset ($_SESSION[$var]);
1319   /* ... work around, since the first one
1320      doesn't seem to work all the time */
1321   session_unregister ($var);
1325 function show_errors($message)
1327   $complete= "";
1329   /* Assemble the message array to a plain string */
1330   foreach ($message as $error){
1331     if ($complete == ""){
1332       $complete= $error;
1333     } else {
1334       $complete= "$error<br>$complete";
1335     }
1336   }
1338   /* Fill ERROR variable with nice error dialog */
1339   print_red($complete);
1343 function show_ldap_error($message, $addon= "")
1345   if (!preg_match("/Success/i", $message)){
1346     if ($addon == ""){
1347       print_red (_("LDAP error: $message"));
1348     } else {
1349       print_red ("$addon<br><br><b>"._("LDAP error:")."</b> $message");
1350     }
1351     return TRUE;
1352   } else {
1353     return FALSE;
1354   }
1358 function rewrite($s)
1360   global $REWRITE;
1362   foreach ($REWRITE as $key => $val){
1363     $s= preg_replace("/$key/", "$val", $s);
1364   }
1366   return ($s);
1370 function dn2base($dn)
1372   global $config;
1374   if (get_people_ou() != ""){
1375     $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1376   }
1377   if (get_groups_ou() != ""){
1378     $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1379   }
1380   $base= preg_replace ('/^[^,]+,/i', '', $dn);
1382   return ($base);
1387 function check_command($cmdline)
1389   $cmd= preg_replace("/ .*$/", "", $cmdline);
1391   /* Check if command exists in filesystem */
1392   if (!file_exists($cmd)){
1393     return (FALSE);
1394   }
1396   /* Check if command is executable */
1397   if (!is_executable($cmd)){
1398     return (FALSE);
1399   }
1401   return (TRUE);
1405 function print_header($image, $headline, $info= "")
1407   $display= "<div class=\"plugtop\">\n";
1408   $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";
1409   $display.= "</div>\n";
1411   if ($info != ""){
1412     $display.= "<div class=\"pluginfo\">\n";
1413     $display.= "$info";
1414     $display.= "</div>\n";
1415   } else {
1416     $display.= "<div style=\"height:5px;\">\n";
1417     $display.= "&nbsp;";
1418     $display.= "</div>\n";
1419   }
1420 #  if (isset($_SESSION['errors'])){
1421 #    $display.= $_SESSION['errors'];
1422 #  }
1424   return ($display);
1428 function register_global($name, $object)
1430   $_SESSION[$name]= $object;
1434 function is_global($name)
1436   return isset($_SESSION[$name]);
1440 function get_global($name)
1442   return $_SESSION[$name];
1446 function range_selector($dcnt,$start,$range=25,$post_var=false)
1449   /* Entries shown left and right from the selected entry */
1450   $max_entries= 10;
1452   /* Initialize and take care that max_entries is even */
1453   $output="";
1454   if ($max_entries & 1){
1455     $max_entries++;
1456   }
1458   if((!empty($post_var))&&(isset($_POST[$post_var]))){
1459     $range= $_POST[$post_var];
1460   }
1462   /* Prevent output to start or end out of range */
1463   if ($start < 0 ){
1464     $start= 0 ;
1465   }
1466   if ($start >= $dcnt){
1467     $start= $range * (int)(($dcnt / $range) + 0.5);
1468   }
1470   $numpages= (($dcnt / $range));
1471   if(((int)($numpages))!=($numpages)){
1472     $numpages = (int)$numpages + 1;
1473   }
1474   if ((((int)$numpages) <= 1 )&&(!$post_var)){
1475     return ("");
1476   }
1477   $ppage= (int)(($start / $range) + 0.5);
1480   /* Align selected page to +/- max_entries/2 */
1481   $begin= $ppage - $max_entries/2;
1482   $end= $ppage + $max_entries/2;
1484   /* Adjust begin/end, so that the selected value is somewhere in
1485      the middle and the size is max_entries if possible */
1486   if ($begin < 0){
1487     $end-= $begin + 1;
1488     $begin= 0;
1489   }
1490   if ($end > $numpages) {
1491     $end= $numpages;
1492   }
1493   if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1494     $begin= $end - $max_entries;
1495   }
1497   if($post_var){
1498     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1499       <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1500   }else{
1501     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1502   }
1504   /* Draw decrement */
1505   if ($start > 0 ) {
1506     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1507       (($start-$range))."\">".
1508       "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1509   }
1511   /* Draw pages */
1512   for ($i= $begin; $i < $end; $i++) {
1513     if ($ppage == $i){
1514       $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1515         validate($_GET['plug'])."&amp;start=".
1516         ($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1517     } else {
1518       $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1519         "&amp;start=".($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1520     }
1521   }
1523   /* Draw increment */
1524   if($start < ($dcnt-$range)) {
1525     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1526       (($start+($range)))."\">".
1527       "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1528   }
1530   if(($post_var)&&($numpages)){
1531     $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()'>";
1532     foreach(array(20,50,100,200,"all") as $num){
1533       if($num == "all"){
1534         $var = 10000;
1535       }else{
1536         $var = $num;
1537       }
1538       if($var == $range){
1539         $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1540       }else{  
1541         $output.="\n<option value='".$var."'>".$num."</option>";
1542       }
1543     }
1544     $output.=  "</select></td></tr></table></div>";
1545   }else{
1546     $output.= "</div>";
1547   }
1549   return($output);
1553 function apply_filter()
1555   $apply= "";
1557   $apply= ''.
1558     '<table summary=""  width="100%"  style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1559     '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1561   return ($apply);
1565 function back_to_main()
1567   $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1568     _("Back").'"></p><input type="hidden" name="ignore">';
1570   return ($string);
1574 function normalize_netmask($netmask)
1576   /* Check for notation of netmask */
1577   if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1578     $num= (int)($netmask);
1579     $netmask= "";
1581     for ($byte= 0; $byte<4; $byte++){
1582       $result=0;
1584       for ($i= 7; $i>=0; $i--){
1585         if ($num-- > 0){
1586           $result+= pow(2,$i);
1587         }
1588       }
1590       $netmask.= $result.".";
1591     }
1593     return (preg_replace('/\.$/', '', $netmask));
1594   }
1596   return ($netmask);
1600 function netmask_to_bits($netmask)
1602   list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1603   $res= 0;
1605   for ($n= 0; $n<4; $n++){
1606     $start= 255;
1607     $name= "nm$n";
1609     for ($i= 0; $i<8; $i++){
1610       if ($start == (int)($$name)){
1611         $res+= 8 - $i;
1612         break;
1613       }
1614       $start-= pow(2,$i);
1615     }
1616   }
1618   return ($res);
1622 function recurse($rule, $variables)
1624   $result= array();
1626   if (!count($variables)){
1627     return array($rule);
1628   }
1630   reset($variables);
1631   $key= key($variables);
1632   $val= current($variables);
1633   unset ($variables[$key]);
1635   foreach($val as $possibility){
1636     $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1637     $result= array_merge($result, recurse($nrule, $variables));
1638   }
1640   return ($result);
1644 function expand_id($rule, $attributes)
1646   /* Check for id rule */
1647   if(preg_match('/^id(:|#)\d+$/',$rule)){
1648     return (array("\{$rule}"));
1649   }
1651   /* Check for clean attribute */
1652   if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1653     $rule= preg_replace('/^%/', '', $rule);
1654     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1655     return (array($val));
1656   }
1658   /* Check for attribute with parameters */
1659   if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1660     $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1661     $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1662     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1663     $start= preg_replace ('/-.*$/', '', $param);
1664     $stop = preg_replace ('/^[^-]+-/', '', $param);
1666     /* Assemble results */
1667     $result= array();
1668     for ($i= $start; $i<= $stop; $i++){
1669       $result[]= substr($val, 0, $i);
1670     }
1671     return ($result);
1672   }
1674   echo "Error in idgen string: don't know how to handle rule $rule.\n";
1675   return (array($rule));
1679 function gen_uids($rule, $attributes)
1681   global $config;
1683   /* Search for keys and fill the variables array with all 
1684      possible values for that key. */
1685   $part= "";
1686   $trigger= false;
1687   $stripped= "";
1688   $variables= array();
1690   for ($pos= 0; $pos < strlen($rule); $pos++){
1692     if ($rule[$pos] == "{" ){
1693       $trigger= true;
1694       $part= "";
1695       continue;
1696     }
1698     if ($rule[$pos] == "}" ){
1699       $variables[$pos]= expand_id($part, $attributes);
1700       $stripped.= "{".$pos."}";
1701       $trigger= false;
1702       continue;
1703     }
1705     if ($trigger){
1706       $part.= $rule[$pos];
1707     } else {
1708       $stripped.= $rule[$pos];
1709     }
1710   }
1712   /* Recurse through all possible combinations */
1713   $proposed= recurse($stripped, $variables);
1715   /* Get list of used ID's */
1716   $used= array();
1717   $ldap= $config->get_ldap_link();
1718   $ldap->cd($config->current['BASE']);
1719   $ldap->search('(uid=*)');
1721   while($attrs= $ldap->fetch()){
1722     $used[]= $attrs['uid'][0];
1723   }
1725   /* Remove used uids and watch out for id tags */
1726   $ret= array();
1727   foreach($proposed as $uid){
1729     /* Check for id tag and modify uid if needed */
1730     if(preg_match('/\{id:\d+}/',$uid)){
1731       $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1733       for ($i= 0; $i < pow(10,$size); $i++){
1734         $number= sprintf("%0".$size."d", $i);
1735         $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1736         if (!in_array($res, $used)){
1737           $uid= $res;
1738           break;
1739         }
1740       }
1741     }
1743   if(preg_match('/\{id#\d+}/',$uid)){
1744     $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1746     while (true){
1747       mt_srand((double) microtime()*1000000);
1748       $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1749       $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1750       if (!in_array($res, $used)){
1751         $uid= $res;
1752         break;
1753       }
1754     }
1755   }
1757 /* Don't assign used ones */
1758 if (!in_array($uid, $used)){
1759   $ret[]= $uid;
1763 return(array_unique($ret));
1767 function array_search_r($needle, $key, $haystack){
1769   foreach($haystack as $index => $value){
1770     $match= 0;
1772     if (is_array($value)){
1773       $match= array_search_r($needle, $key, $value);
1774     }
1776     if ($index==$key && !is_array($value) && preg_match("/$needle/i", $value)){
1777       $match=1;
1778     }
1780     if ($match){
1781       return 1;
1782     }
1783   }
1785   return 0;
1786
1789 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1790    Need to convert... */
1791 function to_byte($value) {
1792   $value= strtolower(trim($value));
1794   if(!is_numeric(substr($value, -1))) {
1796     switch(substr($value, -1)) {
1797       case 'g':
1798         $mult= 1073741824;
1799         break;
1800       case 'm':
1801         $mult= 1048576;
1802         break;
1803       case 'k':
1804         $mult= 1024;
1805         break;
1806     }
1808     return ($mult * (int)substr($value, 0, -1));
1809   } else {
1810     return $value;
1811   }
1815 function in_array_ics($value, $items)
1817   if (!is_array($items)){
1818     return (FALSE);
1819   }
1821   foreach ($items as $item){
1822     if (strtolower($item) == strtolower($value)) {
1823       return (TRUE);
1824     }
1825   }
1827   return (FALSE);
1828
1831 function generate_alphabet($count= 10)
1833   $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1834   $alphabet= "";
1835   $c= 0;
1837   /* Fill cells with charaters */
1838   for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1839     if ($c == 0){
1840       $alphabet.= "<tr>";
1841     }
1843     $ch = mb_substr($characters, $i, 1, "UTF8");
1844     $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1845       validate($_GET['plug'])."&amp;search=".$ch."\">&nbsp;".$ch."&nbsp;</a></td>";
1847     if ($c++ == $count){
1848       $alphabet.= "</tr>";
1849       $c= 0;
1850     }
1851   }
1853   /* Fill remaining cells */
1854   while ($c++ <= $count){
1855     $alphabet.= "<td>&nbsp;</td>";
1856   }
1858   return ($alphabet);
1862 function validate($string)
1864   return (strip_tags(preg_replace('/\0/', '', $string)));
1867 function get_gosa_version()
1869   global $svn_revision, $svn_path;
1871   /* Extract informations */
1872   $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1874   /* Release or development? */
1875   if (preg_match('%/gosa/trunk/%', $svn_path)){
1876     return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1877   } else {
1878     $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1879     return (_("GOsa $release"));
1880   }
1884 function rmdirRecursive($path, $followLinks=false) {
1885   $dir= opendir($path);
1886   while($entry= readdir($dir)) {
1887     if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1888       unlink($path."/".$entry);
1889     } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1890       rmdirRecursive($path."/".$entry);
1891     }
1892   }
1893   closedir($dir);
1894   return rmdir($path);
1897 function scan_directory($path,$sort_desc=false)
1899   $ret = false;
1901   /* is this a dir ? */
1902   if(is_dir($path)) {
1904     /* is this path a readable one */
1905     if(is_readable($path)){
1907       /* Get contents and write it into an array */   
1908       $ret = array();    
1910       $dir = opendir($path);
1912       /* Is this a correct result ?*/
1913       if($dir){
1914         while($fp = readdir($dir))
1915           $ret[]= $fp;
1916       }
1917     }
1918   }
1919   /* Sort array ascending , like scandir */
1920   sort($ret);
1922   /* Sort descending if parameter is sort_desc is set */
1923   if($sort_desc) {
1924     $ret = array_reverse($ret);
1925   }
1927   return($ret);
1930 function clean_smarty_compile_dir($directory)
1932   global $svn_revision;
1934   if(is_dir($directory) && is_readable($directory)) {
1935     // Set revision filename to REVISION
1936     $revision_file= $directory."/REVISION";
1938     /* Is there a stamp containing the current revision? */
1939     if(!file_exists($revision_file)) {
1940       // create revision file
1941       create_revision($revision_file, $svn_revision);
1942     } else {
1943 # check for "$config->...['CONFIG']/revision" and the
1944 # contents should match the revision number
1945       if(!compare_revision($revision_file, $svn_revision)){
1946         // If revision differs, clean compile directory
1947         foreach(scan_directory($directory) as $file) {
1948           if(($file==".")||($file=="..")) continue;
1949           if( is_file($directory."/".$file) &&
1950               is_writable($directory."/".$file)) {
1951             // delete file
1952             if(!unlink($directory."/".$file)) {
1953               print_red("File ".$directory."/".$file." could not be deleted.");
1954               // This should never be reached
1955             }
1956           } elseif(is_dir($directory."/".$file) &&
1957               is_writable($directory."/".$file)) {
1958             // Just recursively delete it
1959             rmdirRecursive($directory."/".$file);
1960           }
1961         }
1962         // We should now create a fresh revision file
1963         clean_smarty_compile_dir($directory);
1964       } else {
1965         // Revision matches, nothing to do
1966       }
1967     }
1968   } else {
1969     // Smarty compile dir is not accessible
1970     // (Smarty will warn about this)
1971   }
1974 function create_revision($revision_file, $revision)
1976   $result= false;
1978   if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1979     if($fh= fopen($revision_file, "w")) {
1980       if(fwrite($fh, $revision)) {
1981         $result= true;
1982       }
1983     }
1984     fclose($fh);
1985   } else {
1986     print_red("Can not write to revision file");
1987   }
1989   return $result;
1992 function compare_revision($revision_file, $revision)
1994   // false means revision differs
1995   $result= false;
1997   if(file_exists($revision_file) && is_readable($revision_file)) {
1998     // Open file
1999     if($fh= fopen($revision_file, "r")) {
2000       // Compare File contents with current revision
2001       if($revision == fread($fh, filesize($revision_file))) {
2002         $result= true;
2003       }
2004     } else {
2005       print_red("Can not open revision file");
2006     }
2007     // Close file
2008     fclose($fh);
2009   }
2011   return $result;
2014 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
2016   $str = ""; // Our return value will be saved in this var
2018   $color  = dechex($percentage+150);
2019   $color2 = dechex(150 - $percentage);
2020   $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
2022   $progress = (int)(($percentage /100)*$width);
2024   /* Abort printing out percentage, if divs are to small */
2027   /* If theres a better solution for this, use it... */
2028   $str = "
2029     <div style=\" width:".($width)."px; 
2030     height:".($height)."px;
2031   background-color:#000000;
2032 padding:1px;\">
2034           <div style=\" width:".($width)."px;
2035         background-color:#$bgcolor;
2036 height:".($height)."px;\">
2038          <div style=\" width:".$progress."px;
2039 height:".$height."px;
2040        background-color:#".$color2.$color2.$color."; \">";
2043        if(($height >10)&&($showvalue)){
2044          $str.=                 "<font style=\"font-size:".($height-2)."px;color:#FF0000;align:middle;padding-left:".((int)(($width*0.4)))."px;\">
2045            <b>".$percentage."%</b>
2046            </font>";
2047        }
2049        $str.= "</div></div></div>";
2051        return($str);
2055 function array_key_ics($ikey, $items)
2057   /* Gather keys, make them lowercase */
2058   $tmp= array();
2059   foreach ($items as $key => $value){
2060     $tmp[strtolower($key)]= $key;
2061   }
2063   if (isset($tmp[strtolower($ikey)])){
2064     return($tmp[strtolower($ikey)]);
2065   }
2067   return ("");
2071 function search_config($arr, $name, $return)
2073   if (is_array($arr)){
2074     foreach ($arr as $a){
2075       if (isset($a['CLASS']) &&
2076           strtolower($a['CLASS']) == strtolower($name)){
2078         if (isset($a[$return])){
2079           return ($a[$return]);
2080         } else {
2081           return ("");
2082         }
2083       } else {
2084         $res= search_config ($a, $name, $return);
2085         if ($res != ""){
2086           return $res;
2087         }
2088       }
2089     }
2090   }
2091   return ("");
2095 function array_differs($src, $dst)
2097   /* If the count is differing, the arrays differ */
2098   if (count ($src) != count ($dst)){
2099     return (TRUE);
2100   }
2102   /* So the count is the same - lets check the contents */
2103   $differs= FALSE;
2104   foreach($src as $value){
2105     if (!in_array($value, $dst)){
2106       $differs= TRUE;
2107     }
2108   }
2110   return ($differs);
2114 function saveFilter($a_filter, $values)
2116   if (isset($_POST['regexit'])){
2117     $a_filter["regex"]= $_POST['regexit'];
2119     foreach($values as $type){
2120       if (isset($_POST[$type])) {
2121         $a_filter[$type]= "checked";
2122       } else {
2123         $a_filter[$type]= "";
2124       }
2125     }
2126   }
2128   /* React on alphabet links if needed */
2129   if (isset($_GET['search'])){
2130     $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2131     if ($s == "**"){
2132       $s= "*";
2133     }
2134     $a_filter['regex']= $s;
2135   }
2137   return ($a_filter);
2141 /* Escape all preg_* relevant characters */
2142 function normalizePreg($input)
2144   return (addcslashes($input, '[]()|/.*+-'));
2148 /* Escape all LDAP filter relevant characters */
2149 function normalizeLdap($input)
2151   return (addcslashes($input, '()|'));
2155 /* Resturns the difference between to microtime() results in float  */
2156 function get_MicroTimeDiff($start , $stop)
2158   $a = split("\ ",$start);
2159   $b = split("\ ",$stop);
2161   $secs = $b[1] - $a[1];
2162   $msecs= $b[0] - $a[0]; 
2164   $ret = (float) ($secs+ $msecs);
2165   return($ret);
2169 /* Check if the given department name is valid */
2170 function is_department_name_reserved($name,$base)
2172   $reservedName = array("systems","apps","incomming","internal","accounts","fax","addressbook",
2173                           preg_replace("/ou=(.*),/","\\1",get_people_ou()),
2174                           preg_replace("/ou=(.*),/","\\1",get_groups_ou()));
2175   $follwedNames['/ou=fai,ou=configs,ou=systems,/'] = array("fai","hooks","templates","scripts","disk","packages","variables","profiles");
2177   /* Check if name is one of the reserved names */
2178   if(in_array_ics($name,$reservedName)) {
2179     return(true);
2180   }
2182   /* Check all follow combinations if name is in array && parent base == array_key, return false*/
2183   foreach($follwedNames as $key => $names){
2184     if((in_array_ics($name,$names)) && (preg_match($key,$base))){
2185       return(true);
2186     }
2187   }
2188   return(false);
2192 function is_php4()
2194   if (isset($_SESSION['PHP4COMPATIBLE'])){
2195     return true;
2196   }
2197   return (preg_match('/^4/', phpversion()));
2201 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2203   /* Initialize variables */
2204   $ret  = array("count" => 0);  // Set count to 0
2205   $next = true;                 // if false, then skip next loops and return
2206   $cnt  = 0;                    // Current number of loops
2207   $max  = 100;                  // Just for security, prevent looops
2208   $ldap = NULL;                 // To check if created result a valid
2209   $keep = "";                   // save last failed parse string
2211   /* Check each parsed dn in ldap ? */
2212   if($config!=NULL && $verify_in_ldap){
2213     $ldap = $config->get_ldap_link();
2214   }
2216   /* Lets start */
2217   $called = false;
2218   while(preg_match("/,/",$dn) && $next &&  $cnt < $max){
2220     $cnt ++;
2221     if(!preg_match("/,/",$dn)){
2222       $next = false;
2223     }
2224     $object = preg_replace("/[,].*$/","",$dn);
2225     $dn     = preg_replace("/^[^,]+,/","",$dn);
2227     $called = true;
2229     /* Check if current dn is valid */
2230     if($ldap!=NULL){
2231       $ldap->cd($dn);
2232       $ldap->cat($dn,array("dn"));
2233       if($ldap->count()){
2234         $ret[]  = $keep.$object;
2235         $keep   = "";
2236       }else{
2237         $keep  .= $object.",";
2238       }
2239     }else{
2240       $ret[]  = $keep.$object;
2241       $keep   = "";
2242     }
2243   }
2245   /* No dn was posted */
2246   if($cnt == 0 && !empty($dn)){
2247     $ret[] = $dn;
2248   }
2250   /* Append the rest */
2251   $test = $keep.$dn;
2252   if($called && !empty($test)){
2253     $ret[] = $keep.$dn;
2254   }
2255   $ret['count'] = count($ret) - 1;
2257   return($ret);
2261 function get_base_from_hook($dn, $attrib)
2263   global $config;
2265   if (isset($config->current['BASE_HOOK'])){
2266     
2267     /* Call hook script - if present */
2268     $command= $config->current['BASE_HOOK'];
2270     if ($command != ""){
2271       $command.= " '$dn' $attrib";
2272       if (check_command($command)){
2273         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2274         exec($command, $output);
2275         if (preg_match("/^[0-9]+$/", $output[0])){
2276           return ($output[0]);
2277         } else {
2278           print_red(_("Warning - base_hook is not available. Using default base."));
2279           return ($config->current['UIDBASE']);
2280         }
2281       } else {
2282         print_red(_("Warning - base_hook is not available. Using default base."));
2283         return ($config->current['UIDBASE']);
2284       }
2286     } else {
2288       print_red(_("Warning - no base_hook defined. Using default base."));
2289       return ($config->current['UIDBASE']);
2291     }
2292   }
2295 /* Schema validation functions */
2297   function check_schema_version($class, $version)
2298   {
2299     return preg_match("/\(v$version\)/", $class['DESC']);
2300   }
2302   
2304   function check_schema($cfg,$rfc2307bis = FALSE)
2305   {
2307     $messages= array();
2309     /* Get objectclasses */
2310     $ldap = new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE,$cfg['tls']);
2311     $objectclasses = $ldap->get_objectclasses();
2312     if(count($objectclasses) == 0){
2313       print_red(_("Can't get schema information from server. No schema check possible!"));
2314     }
2316     /* This is the default block used for each entry.
2317      *  to avoid unset indexes.
2318      */
2319     $def_check = array("REQUIRED_VERSION" => "0",
2320                        "SCHEMA_FILES"     => array(),
2321                        "CLASSES_REQUIRED" => array(),
2322                        "STATUS"           => FALSE,
2323                        "IS_MUST_HAVE"     => FALSE,
2324                        "MSG"              => "",
2325                        "INFO"             => "");#_("There is currently no information specified for this schema extension."));
2327  /* The gosa base schema */
2328     $checks['gosaObject'] = $def_check;
2329     $checks['gosaObject']['REQUIRED_VERSION'] = "2.4";
2330     $checks['gosaObject']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2331     $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2332     $checks['gosaObject']['IS_MUST_HAVE']     = TRUE;
2334     /* GOsa Account class */
2335     $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.4";
2336     $checks["gosaAccount"]["SCHEMA_FILES"]    = array("gosa+samba3.schema","gosa.schema");
2337     $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2338     $checks["gosaAccount"]["IS_MUST_HAVE"]    = TRUE;
2339     $checks["gosaAccount"]["INFO"]            = _("Used to store account specific informations.");
2341     /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2342     $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.4";
2343     $checks["gosaLockEntry"]["SCHEMA_FILES"]     = array("gosa+samba3.schema","gosa.schema");
2344     $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2345     $checks["gosaLockEntry"]["IS_MUST_HAVE"]     = TRUE;
2346     $checks["gosaLockEntry"]["INFO"]             = _("Used to lock currently edited entries to avoid multiple changes at the same time.");
2348   /* Some other checks */
2349     foreach(array(
2350           "gosaCacheEntry"        => array("version" => "2.4"),
2351           "gosaDepartment"        => array("version" => "2.4"),
2352           "goFaxAccount"          => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2353           "goFaxSBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2354           "goFaxRBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2355           "gosaUserTemplate"      => array("version" => "2.4", "class" => "posixAccount","file" => "nis.schema"),
2356           "gosaMailAccount"       => array("version" => "2.4", "class" => "mailAccount","file" => "gosa+samba3.schema"),
2357           "gosaProxyAccount"      => array("version" => "2.4", "class" => "proxyAccount","file" => "gosa+samba3.schema"),
2358           "gosaApplication"       => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2359           "gosaApplicationGroup"  => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2360           "GOhard"                => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2361           "gotoTerminal"          => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2362           "goServer"              => array("version" => "2.4","class" => "server","file" => "goserver.schema"),
2363           "goTerminalServer"      => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2364           "goShareServer"         => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2365           "goNtpServer"           => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2366           "goSyslogServer"        => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2367           "goLdapServer"          => array("version" => "2.4"),
2368           "goCupsServer"          => array("version" => "2.4", "class" => array("posixAccount", "terminals"),),
2369           "goImapServer"          => array("version" => "2.4", "class" => array("mailAccount", "mailgroup"),"file" => "gosa+samba3.        schema"),
2370           "goKrbServer"           => array("version" => "2.4"),
2371           "goFaxServer"           => array("version" => "2.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2372           ) as $name => $values){
2374       $checks[$name] = $def_check;
2375       if(isset($values['version'])){
2376         $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2377       }
2378       if(isset($values['file'])){
2379         $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2380       }
2381       $checks[$name]["CLASSES_REQUIRED"] = array($name);
2382     }
2383    foreach($checks as $name => $value){
2384       foreach($value['CLASSES_REQUIRED'] as $class){
2386         if(!isset($objectclasses[$name])){
2387           $checks[$name]['STATUS'] = FALSE;
2388           if($value['IS_MUST_HAVE']){
2389             $checks[$name]['MSG']    = sprintf(_("The required objectClass '%s' is not present in your schema setup"),$class);
2390           }else{
2391             $checks[$name]['MSG']    = sprintf(_("The optional objectClass '%s' is not present in your schema setup"),$class);
2392           }
2393         }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2394           $checks[$name]['STATUS'] = FALSE;
2396           if($value['IS_MUST_HAVE']){
2397             $checks[$name]['MSG'] = sprintf(_("The required objectclass '%s' does not have version %s"), $class,                           $value['REQUIRED_VERSION']);
2398           }else{
2399             $checks[$name]['MSG'] = sprintf(_("The optional objectclass '%s' does not have version %s"), $class,                           $value['REQUIRED_VERSION']);
2400           }
2401         }else{
2402           $checks[$name]['STATUS'] = TRUE;
2403           $checks[$name]['MSG'] = sprintf(_("Class(es) available"));
2404         }
2405       }
2406     }
2408     $tmp = $objectclasses;
2411     /* The gosa base schema */
2412     $checks['posixGroup'] = $def_check;
2413     $checks['posixGroup']['REQUIRED_VERSION'] = "2.4";
2414     $checks['posixGroup']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2415     $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2416     $checks['posixGroup']['STATUS']           = TRUE;
2417     $checks['posixGroup']['IS_MUST_HAVE']     = TRUE;
2418     $checks['posixGroup']['MSG']              = "";
2419     $checks['posixGroup']['INFO']             = "";
2421     /* Depending on selected rfc2307bis mode, we need different schema configurations */
2422     if(isset($tmp['posixGroup'])){
2424       if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2425         $checks['posixGroup']['STATUS']           = FALSE;
2426         $checks['posixGroup']['MSG']              = _("You have enabled the rfc2307bis option on the 'ldap setup' step, but your schema    configuration do not support this option.");
2427         $checks['posixGroup']['INFO']             = _("In order to use rfc2307bis conform groups the objectClass 'posixGroup' must be      AUXILIARY");
2428       }
2429       if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2430         $checks['posixGroup']['STATUS']           = FALSE;
2431         $checks['posixGroup']['MSG']              = _("You have disabled the rfc2307bis option on the 'ldap setup' step, but your schema   configuration do not support this option.");
2432         $checks['posixGroup']['INFO']             = _("The objectClass 'posixGroup' must be STRUCTURAL");
2433       }
2434     }
2436     return($checks);
2437   }
2440 function prepare4mailbody($string)
2442   $string = html_entity_decode($string);
2444   $from = array(
2445                 "/%/",
2446                 "/ /",
2447                 "/\n/",  
2448                 "/\r/",
2449                 "/!/",
2450                 "/#/",
2451                 "/\*/",
2452                 "/\//",
2453                 "/</",
2454                 "/>/",
2455                 "/\?/",
2456                 "/\&/",
2457                 "/\(/",
2458                 "/\)/",
2459                 "/\"/");
2460   
2461   $to = array(  
2462                 "%25",
2463                 "%20",
2464                 "%0A",
2465                 "%0D",
2466                 "%21",
2467                 "%23",
2468                 "%2A",
2469                 "%2F",
2470                 "%3C",
2471                 "%3E",
2472                 "%3F",
2473                 "%38",
2474                 "%28",
2475                 "%29",
2476                 "%22");
2478   $string = preg_replace($from,$to,$string);
2480   return($string);
2484 function mac2company($mac)
2486   $vendor= "";
2488   /* Generate a normailzed mac... */
2489   $mac= substr(preg_replace('/[:-]/', '', $mac), 0, 6);
2491   /* Check for existance of the oui file */
2492   if (!is_readable(CONFIG_DIR."/oui.txt")){
2493     return ("");
2494   }
2496   /* Open file and look for mac addresses... */
2497   $handle = @fopen(CONFIG_DIR."/oui.txt", "r");
2498   if ($handle) {
2499     while (!feof($handle)) {
2500       $line = fgets($handle, 4096);
2502       if (preg_match("/^$mac/i", $line)){
2503         $vendor= substr($line, 32);
2504       }
2505     }
2506     fclose($handle);
2507   }
2509   return ($vendor);
2513 function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FALSE)
2515   $tmp = array(
2516         "de_DE" => "German",
2517         "fr_FR" => "French",
2518         "it_IT" => "Italian",
2519         "es_ES" => "Spanish",
2520         "en_US" => "English",
2521         "nl_NL" => "Dutch",
2522         "pl_PL" => "Polish",
2523         "sv_SE" => "Swedish",
2524         "zh_CN" => "Chinese",
2525         "ru_RU" => "Russian");
2526   
2527   $tmp2= array(
2528         "de_DE" => _("German"),
2529         "fr_FR" => _("French"),
2530         "it_IT" => _("Italian"),
2531         "es_ES" => _("Spanish"),
2532         "en_US" => _("English"),
2533         "nl_NL" => _("Dutch"),
2534         "pl_PL" => _("Polish"),
2535         "sv_SE" => _("Swedish"),
2536         "zh_CN" => _("Chinese"),
2537         "ru_RU" => _("Russian"));
2539   $ret = array();
2540   if($languages_in_own_language){
2542     $old_lang = setlocale(LC_ALL, 0);
2543     foreach($tmp as $key => $name){
2544       $lang = $key.".UTF-8";
2545       setlocale(LC_ALL, $lang);
2546       if($strip_region_tag){
2547         $ret[preg_replace("/^([^_]*).*$/","\\1",$key)] = _($name)." (".$tmp2[$key].")";
2548       }else{
2549         $ret[$key] = _($name)." &nbsp;(".$tmp2[$key].")";
2550       }
2551     }
2552     setlocale(LC_ALL, $old_lang);
2553   }else{
2554     foreach($tmp as $key => $name){
2555       if($strip_region_tag){
2556         $ret[preg_replace("/^([^_]*).*/","\\1",$key)] = _($name);
2557       }else{
2558         $ret[$key] = _($name);
2559       }
2560     }
2561   }
2562   return($ret);
2566 /* Check if $ip1 and $ip2 represents a valid IP range 
2567  *  returns TRUE in case of a valid range, FALSE in case of an error. 
2568  */
2569 function is_ip_range($ip1,$ip2)
2571   if(!is_ip($ip1) || !is_ip($ip2)){
2572     return(FALSE);
2573   }else{
2574     $ar1 = split("\.",$ip1);
2575     $var1 = $ar1[0] * (16777216) + $ar1[1] * (65536) + $ar1[2] * (256) + $ar1[3];
2577     $ar2 = split("\.",$ip2);
2578     $var2 = $ar2[0] * (16777216) + $ar2[1] * (65536) + $ar2[2] * (256) + $ar2[3];
2579     return($var1 < $var2);
2580   }
2584 /* Check if the specified IP address $address is inside the given network */
2585 function is_in_network($network, $netmask, $address)
2587   $nw= split('\.', $network);
2588   $nm= split('\.', $netmask);
2589   $ad= split('\.', $address);
2591   /* Generate inverted netmask */
2592   for ($i= 0; $i<4; $i++){
2593     $ni[$i]= 255-$nm[$i];
2594     $la[$i]= $nw[$i] | $ni[$i];
2595   }
2597   /* Transform to integer */
2598   $first= $nw[0] * (16777216) + $nw[1] * (65536) + $nw[2] * (256) + $nw[3];
2599   $curr=  $ad[0] * (16777216) + $ad[1] * (65536) + $ad[2] * (256) + $ad[3];
2600   $last=  $la[0] * (16777216) + $la[1] * (65536) + $la[2] * (256) + $la[3];
2602   return ($first < $curr&& $last > $curr);
2606 /* Returns contents of the given POST variable and check magic quotes settings */
2607 function get_post($name)
2609   if(!isset($_POST[$name])){
2610     trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2611     return(FALSE);
2612   }
2613   if(get_magic_quotes_gpc()){
2614     return(stripcslashes($_POST[$name]));
2615   }else{
2616     return($_POST[$name]);
2617   }
2620 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2621 ?>